test.cc 611 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. #ifdef CPPHTTPLIB_SSL_ENABLED
  50. namespace httplib {
  51. namespace tls {
  52. // Declared here for the split build, where the TLS abstraction declarations
  53. // live below the split border; the definition is linked from httplib.cc.
  54. ca_store_t create_ca_store(const char *pem, size_t len);
  55. } // namespace tls
  56. } // namespace httplib
  57. #endif
  58. using namespace std;
  59. using namespace httplib;
  60. const char *HOST = "localhost";
  61. static int get_base_port() {
  62. const char *shard = getenv("GTEST_SHARD_INDEX");
  63. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  64. }
  65. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  66. // New standalone tests MUST use svr.bind_to_any_port() instead.
  67. const int PORT = get_base_port();
  68. const string LONG_QUERY_VALUE = string(25000, '@');
  69. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  70. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  71. const string TOO_LONG_QUERY_URL =
  72. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  73. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  74. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  75. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  76. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  77. return file.name == key;
  78. });
  79. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  80. return *it;
  81. #else
  82. if (it != items.end()) { return *it; }
  83. throw std::runtime_error("invalid multipart form data name error");
  84. #endif
  85. }
  86. static void read_file(const std::string &path, std::string &out) {
  87. std::ifstream fs(path, std::ios_base::binary);
  88. if (!fs) {
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return;
  91. #else
  92. throw std::runtime_error("File not found: " + path);
  93. #endif
  94. }
  95. fs.seekg(0, std::ios_base::end);
  96. auto size = fs.tellg();
  97. fs.seekg(0);
  98. out.resize(static_cast<size_t>(size));
  99. fs.read(&out[0], static_cast<std::streamsize>(size));
  100. }
  101. class UnixSocketTest : public ::testing::Test {
  102. protected:
  103. void TearDown() override { std::remove(pathname_.c_str()); }
  104. void client_GET(const std::string &addr) {
  105. httplib::Client cli{addr};
  106. cli.set_address_family(AF_UNIX);
  107. ASSERT_TRUE(cli.is_valid());
  108. const auto &result = cli.Get(pattern_);
  109. ASSERT_TRUE(result) << "error: " << result.error();
  110. const auto &resp = result.value();
  111. EXPECT_EQ(resp.status, StatusCode::OK_200);
  112. EXPECT_EQ(resp.body, content_);
  113. }
  114. static std::string make_sock_path() {
  115. const char *shard = getenv("GTEST_SHARD_INDEX");
  116. return shard ? std::string("./httplib-server-") + shard + ".sock"
  117. : "./httplib-server.sock";
  118. }
  119. const std::string pathname_{make_sock_path()};
  120. const std::string pattern_{"/hi"};
  121. const std::string content_{"Hello World!"};
  122. };
  123. TEST_F(UnixSocketTest, pathname) {
  124. httplib::Server svr;
  125. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  126. res.set_content(content_, "text/plain");
  127. });
  128. std::thread t{[&] {
  129. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  130. }};
  131. auto se = detail::scope_exit([&] {
  132. svr.stop();
  133. t.join();
  134. ASSERT_FALSE(svr.is_running());
  135. });
  136. svr.wait_until_ready();
  137. ASSERT_TRUE(svr.is_running());
  138. client_GET(pathname_);
  139. }
  140. #if defined(__linux__) || \
  141. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  142. TEST_F(UnixSocketTest, PeerPid) {
  143. httplib::Server svr;
  144. std::string remote_port_val;
  145. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  146. res.set_content(content_, "text/plain");
  147. remote_port_val = std::to_string(req.remote_port);
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  161. }
  162. #endif
  163. #ifdef __linux__
  164. TEST_F(UnixSocketTest, abstract) {
  165. constexpr char svr_path[]{"\x00httplib-server.sock"};
  166. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  167. httplib::Server svr;
  168. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. });
  171. std::thread t{[&] {
  172. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  173. }};
  174. auto se = detail::scope_exit([&] {
  175. svr.stop();
  176. t.join();
  177. ASSERT_FALSE(svr.is_running());
  178. });
  179. svr.wait_until_ready();
  180. ASSERT_TRUE(svr.is_running());
  181. client_GET(abstract_addr);
  182. }
  183. #endif
  184. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  185. httplib::Server svr;
  186. std::string received_host_header;
  187. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  188. // Capture the Host header sent by the client
  189. auto host_iter = req.headers.find("Host");
  190. if (host_iter != req.headers.end()) {
  191. received_host_header = host_iter->second;
  192. }
  193. res.set_content(content_, "text/plain");
  194. });
  195. std::thread t{[&] {
  196. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  197. }};
  198. auto se = detail::scope_exit([&] {
  199. svr.stop();
  200. t.join();
  201. ASSERT_FALSE(svr.is_running());
  202. });
  203. svr.wait_until_ready();
  204. ASSERT_TRUE(svr.is_running());
  205. // Test that Host header is automatically set to "localhost" for Unix socket
  206. // connections
  207. httplib::Client cli{pathname_};
  208. cli.set_address_family(AF_UNIX);
  209. ASSERT_TRUE(cli.is_valid());
  210. const auto &result = cli.Get(pattern_);
  211. ASSERT_TRUE(result) << "error: " << result.error();
  212. const auto &resp = result.value();
  213. EXPECT_EQ(resp.status, StatusCode::OK_200);
  214. EXPECT_EQ(resp.body, content_);
  215. // Verify that Host header was automatically set to "localhost"
  216. EXPECT_EQ(received_host_header, "localhost");
  217. }
  218. #ifndef _WIN32
  219. TEST(SocketStream, wait_writable_UNIX) {
  220. int fds[2];
  221. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  222. const auto asSocketStream = [&](socket_t fd,
  223. std::function<bool(Stream &)> func) {
  224. return detail::process_client_socket(
  225. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  226. };
  227. asSocketStream(fds[0], [&](Stream &s0) {
  228. EXPECT_EQ(s0.socket(), fds[0]);
  229. EXPECT_TRUE(s0.wait_writable());
  230. EXPECT_TRUE(s0.is_peer_alive());
  231. EXPECT_EQ(0, close(fds[1]));
  232. EXPECT_FALSE(s0.is_peer_alive());
  233. return true;
  234. });
  235. EXPECT_EQ(0, close(fds[0]));
  236. }
  237. TEST(SocketStream, wait_writable_INET) {
  238. sockaddr_in addr;
  239. memset(&addr, 0, sizeof(addr));
  240. addr.sin_family = AF_INET;
  241. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  242. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  243. int disconnected_svr_sock = -1;
  244. std::thread svr{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, listen(s, 1));
  249. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  250. ASSERT_EQ(0, close(s));
  251. }};
  252. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  253. std::thread cli{[&] {
  254. const int s = socket(AF_INET, SOCK_STREAM, 0);
  255. ASSERT_LE(0, s);
  256. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  257. ASSERT_EQ(0, close(s));
  258. }};
  259. cli.join();
  260. svr.join();
  261. ASSERT_NE(disconnected_svr_sock, -1);
  262. const auto asSocketStream = [&](socket_t fd,
  263. std::function<bool(Stream &)> func) {
  264. return detail::process_client_socket(
  265. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  266. };
  267. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  268. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  269. // wait_writable() returns true because select_write() only checks if the
  270. // send buffer has space. Peer disconnection is detected later by send().
  271. EXPECT_TRUE(ss.wait_writable());
  272. return true;
  273. });
  274. ASSERT_EQ(0, close(disconnected_svr_sock));
  275. }
  276. #endif // #ifndef _WIN32
  277. TEST(SetSocketOptTest, TcpNoDelay) {
  278. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  279. ASSERT_NE(sock, INVALID_SOCKET);
  280. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  281. int val = 0;
  282. socklen_t len = sizeof(val);
  283. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  284. reinterpret_cast<char *>(&val), &len));
  285. EXPECT_NE(val, 0);
  286. detail::close_socket(sock);
  287. }
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. U8("descrip=Gastos áéíóúñÑ 6"));
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(DecodePathTest, UnicodeEncoding) {
  317. // %u0041 = 'A' (1-byte UTF-8)
  318. EXPECT_EQ("A", decode_path_component("%u0041"));
  319. // %u00E9 = 'é' (2-byte UTF-8)
  320. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  321. // %u3042 = 'あ' (3-byte UTF-8)
  322. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  323. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  324. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  325. // %uD800 = surrogate (invalid, silently dropped)
  326. EXPECT_EQ("", decode_path_component("%uD800"));
  327. }
  328. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  329. // A sign or whitespace inside the two-character escape window must not be
  330. // accepted as a valid percent-encoding; the sequence is passed through
  331. // literally, matching decode_uri_component / decode_path_component.
  332. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  333. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  334. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  335. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  336. // Well-formed escapes still decode.
  337. EXPECT_EQ("-", decode_query_component("%2D", false));
  338. EXPECT_EQ("A", decode_query_component("%41", false));
  339. }
  340. TEST(SanitizeFilenameTest, VariousPatterns) {
  341. // Path traversal
  342. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  343. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  344. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  345. // Normal and edge cases
  346. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  347. EXPECT_EQ("filename.txt",
  348. httplib::sanitize_filename("/path/to/filename.txt"));
  349. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  350. EXPECT_EQ("", httplib::sanitize_filename(".."));
  351. EXPECT_EQ("", httplib::sanitize_filename(""));
  352. // Null bytes stripped
  353. EXPECT_EQ("safe.txt",
  354. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  355. // Whitespace-only rejected
  356. EXPECT_EQ("", httplib::sanitize_filename(" "));
  357. }
  358. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  359. string unescapedCharacters = "-_.!~*'()";
  360. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  361. }
  362. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  363. string reservedCharacters = ";,/?:@&=+$";
  364. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  365. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  366. }
  367. TEST(ClientQueryOrder, PreserveOrder) {
  368. // This test reproduces Issue #2259: client may reorder query parameters
  369. // when sending a GET request. The expected behavior is that the client
  370. // preserves the original query string order when the caller supplied it
  371. // as part of the path.
  372. Server svr;
  373. svr.Get("/", [&](const Request &req, Response &res) {
  374. // Echo back the raw target so the test can assert ordering
  375. res.set_content(req.target, "text/plain");
  376. });
  377. std::thread t{[&] { svr.listen(HOST, PORT); }};
  378. auto se = detail::scope_exit([&] {
  379. svr.stop();
  380. t.join();
  381. ASSERT_FALSE(svr.is_running());
  382. });
  383. svr.wait_until_ready();
  384. Client cli(HOST, PORT);
  385. ASSERT_TRUE(cli.is_valid());
  386. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  387. auto res = cli.Get(original);
  388. ASSERT_TRUE(res);
  389. // Expect the echoed target to exactly match the original path (order
  390. // preserved)
  391. EXPECT_EQ(res->body, original);
  392. }
  393. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  394. string chineseCharacters = U8("中国語");
  395. string russianCharacters = U8("дом");
  396. string brazilianCharacters = U8("óculos");
  397. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  398. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  399. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  400. "%D0%B4%D0%BE%D0%BC");
  401. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  402. }
  403. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  404. string unescapedCharacters = "-_.!~*'()";
  405. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  406. }
  407. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  408. string reservedCharacters = ";,/?:@&=+$";
  409. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  410. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  411. }
  412. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  413. string chineseCharacters = U8("中国語");
  414. string russianCharacters = U8("дом");
  415. string brazilianCharacters = U8("óculos");
  416. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  417. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  418. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  419. "%D0%B4%D0%BE%D0%BC");
  420. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  421. }
  422. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  423. // Issue #2082 use case: encoding path component with ampersand
  424. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  425. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  426. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  427. }
  428. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$#";
  434. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  435. }
  436. TEST(EncodeUriTest, TestUTF8Characters) {
  437. string chineseCharacters = U8("中国語");
  438. string russianCharacters = U8("дом");
  439. string brazilianCharacters = U8("óculos");
  440. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  441. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  442. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  443. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  444. }
  445. TEST(EncodeUriTest, TestCompleteUri) {
  446. string uri =
  447. "https://example.com/path/to/resource?query=value&param=test#fragment";
  448. EXPECT_EQ(
  449. httplib::encode_uri(uri),
  450. "https://example.com/path/to/resource?query=value&param=test#fragment");
  451. }
  452. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  453. string uri =
  454. "https://example.com/path with spaces/file name.html?q=hello world";
  455. EXPECT_EQ(httplib::encode_uri(uri),
  456. "https://example.com/path%20with%20spaces/"
  457. "file%20name.html?q=hello%20world");
  458. }
  459. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  461. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  462. }
  463. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'()";
  465. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  466. }
  467. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  476. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  477. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  478. "Piri Tommy Villiers - on & on");
  479. }
  480. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  481. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  482. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  483. }
  484. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  485. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  486. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  487. }
  488. TEST(DecodeUriTest, TestUTF8Characters) {
  489. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  490. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  491. string encodedBrazilian = "%C3%B3culos";
  492. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  493. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  494. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  495. }
  496. TEST(DecodeUriTest, TestCompleteUri) {
  497. string encodedUri = "https://example.com/path%20with%20spaces/"
  498. "file%20name.html?q=hello%20world";
  499. EXPECT_EQ(
  500. httplib::decode_uri(encodedUri),
  501. "https://example.com/path with spaces/file name.html?q=hello world");
  502. }
  503. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  504. string original =
  505. "https://example.com/path with spaces/file name.html?q=hello world";
  506. string encoded = httplib::encode_uri(original);
  507. string decoded = httplib::decode_uri(encoded);
  508. EXPECT_EQ(decoded, original);
  509. }
  510. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  511. string original = "Piri Tommy Villiers - on & on";
  512. string encoded = httplib::encode_uri_component(original);
  513. string decoded = httplib::decode_uri_component(encoded);
  514. EXPECT_EQ(decoded, original);
  515. }
  516. TEST(TrimTests, TrimStringTests) {
  517. EXPECT_EQ("abc", detail::trim_copy("abc"));
  518. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  519. EXPECT_TRUE(detail::trim_copy("").empty());
  520. }
  521. TEST(FromCharsTest, Double) {
  522. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  523. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  524. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  525. auto parse = [](const std::string &s, double &v) {
  526. return detail::from_chars(s.data(), s.data() + s.size(), v);
  527. };
  528. double v = -1.0;
  529. // Representative quality values.
  530. EXPECT_EQ(parse("0", v).ec, std::errc{});
  531. EXPECT_DOUBLE_EQ(v, 0.0);
  532. EXPECT_EQ(parse("1", v).ec, std::errc{});
  533. EXPECT_DOUBLE_EQ(v, 1.0);
  534. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  535. EXPECT_DOUBLE_EQ(v, 0.8);
  536. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  537. EXPECT_DOUBLE_EQ(v, 0.001);
  538. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  539. EXPECT_DOUBLE_EQ(v, 1.0);
  540. // A missing integer or fractional part is tolerated.
  541. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  542. EXPECT_DOUBLE_EQ(v, 0.5);
  543. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  544. EXPECT_DOUBLE_EQ(v, 5.0);
  545. // Values outside [0, 1] still parse; the caller range-checks them.
  546. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  547. EXPECT_DOUBLE_EQ(v, 123.456);
  548. // Stops at the first byte that is not part of the number and reports where.
  549. std::string trailing = "0.9, text/html";
  550. auto r = parse(trailing, v);
  551. EXPECT_EQ(r.ec, std::errc{});
  552. EXPECT_DOUBLE_EQ(v, 0.9);
  553. EXPECT_EQ(*r.ptr, ',');
  554. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  555. // outright, and an 'e'/'E' simply ends the number.
  556. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  557. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  558. std::string exp_input = "1.5e3";
  559. r = parse(exp_input, v);
  560. EXPECT_EQ(r.ec, std::errc{});
  561. EXPECT_DOUBLE_EQ(v, 1.5);
  562. EXPECT_EQ(*r.ptr, 'e');
  563. // Invalid inputs.
  564. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  565. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  566. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  567. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  568. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  569. // Pathological but well-formed inputs must stay bounded (no overflow, no
  570. // out-of-bounds table access) and stay within [0, 1] for the caller.
  571. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  572. std::errc{});
  573. EXPECT_DOUBLE_EQ(v, 0.0);
  574. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  575. std::errc{});
  576. EXPECT_GE(v, 0.0);
  577. EXPECT_LE(v, 1.0);
  578. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  579. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  580. }
  581. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  582. // Simple case without quality values
  583. std::vector<std::string> result1;
  584. EXPECT_TRUE(detail::parse_accept_header(
  585. "text/html,application/json,text/plain", result1));
  586. EXPECT_EQ(result1.size(), 3U);
  587. EXPECT_EQ(result1[0], "text/html");
  588. EXPECT_EQ(result1[1], "application/json");
  589. EXPECT_EQ(result1[2], "text/plain");
  590. // With quality values
  591. std::vector<std::string> result2;
  592. EXPECT_TRUE(detail::parse_accept_header(
  593. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  594. EXPECT_EQ(result2.size(), 3U);
  595. EXPECT_EQ(result2[0], "application/json"); // highest q value
  596. EXPECT_EQ(result2[1], "text/html");
  597. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  598. }
  599. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  600. // Mixed with and without quality values
  601. std::vector<std::string> result;
  602. EXPECT_TRUE(detail::parse_accept_header(
  603. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  604. EXPECT_EQ(result.size(), 3U);
  605. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  606. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  607. EXPECT_EQ(result[2], "application/json"); // q=0.5
  608. }
  609. TEST(ParseAcceptHeaderTest, EdgeCases) {
  610. // Empty header
  611. std::vector<std::string> empty_result;
  612. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  613. EXPECT_TRUE(empty_result.empty());
  614. // Single type
  615. std::vector<std::string> single_result;
  616. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  617. EXPECT_EQ(single_result.size(), 1U);
  618. EXPECT_EQ(single_result[0], "application/json");
  619. // Wildcard types
  620. std::vector<std::string> wildcard_result;
  621. EXPECT_TRUE(detail::parse_accept_header(
  622. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  623. EXPECT_EQ(wildcard_result.size(), 3U);
  624. EXPECT_EQ(wildcard_result[0], "application/json");
  625. EXPECT_EQ(wildcard_result[1], "text/*");
  626. EXPECT_EQ(wildcard_result[2], "*/*");
  627. }
  628. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  629. // Common browser Accept header
  630. std::vector<std::string> browser_result;
  631. EXPECT_TRUE(
  632. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  633. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  634. browser_result));
  635. EXPECT_EQ(browser_result.size(), 6U);
  636. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  637. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  638. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  639. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  640. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  641. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  642. // API client header
  643. std::vector<std::string> api_result;
  644. EXPECT_TRUE(detail::parse_accept_header(
  645. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  646. api_result));
  647. EXPECT_EQ(api_result.size(), 3U);
  648. EXPECT_EQ(api_result[0], "application/json");
  649. EXPECT_EQ(api_result[1], "application/xml");
  650. EXPECT_EQ(api_result[2], "text/plain");
  651. }
  652. TEST(ParseAcceptHeaderTest, SpecialCases) {
  653. // Quality value with 3 decimal places
  654. std::vector<std::string> decimal_result;
  655. EXPECT_TRUE(detail::parse_accept_header(
  656. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  657. EXPECT_EQ(decimal_result.size(), 2U);
  658. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  659. EXPECT_EQ(decimal_result[1], "text/html");
  660. // Zero quality (should still be included but with lowest priority)
  661. std::vector<std::string> zero_q_result;
  662. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  663. zero_q_result));
  664. EXPECT_EQ(zero_q_result.size(), 2U);
  665. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  666. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  667. // No spaces around commas
  668. std::vector<std::string> no_space_result;
  669. EXPECT_TRUE(detail::parse_accept_header(
  670. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  671. no_space_result));
  672. EXPECT_EQ(no_space_result.size(), 3U);
  673. EXPECT_EQ(no_space_result[0], "text/html");
  674. EXPECT_EQ(no_space_result[1], "application/json");
  675. EXPECT_EQ(no_space_result[2], "text/plain");
  676. }
  677. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  678. // Quality values always use '.' as the decimal separator, so parsing must
  679. // not depend on the process locale. An embedding application may have
  680. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  681. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  682. std::string saved = cur ? cur : "C";
  683. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  684. "fr_FR.UTF-8"};
  685. bool switched = false;
  686. for (const auto loc : comma_locales) {
  687. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  688. std::localeconv()->decimal_point[0] == ',') {
  689. switched = true;
  690. break;
  691. }
  692. }
  693. if (!switched) {
  694. std::setlocale(LC_NUMERIC, saved.c_str());
  695. GTEST_SKIP() << "no comma-decimal locale available on this host";
  696. }
  697. // The higher-weighted type appears later in the list, so a correct parse
  698. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  699. // sensitive parse reads both weights as 0 and leaves the original order.
  700. std::vector<std::string> result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "application/json;q=0.1,text/html;q=0.9", result));
  703. ASSERT_EQ(result.size(), 2U);
  704. EXPECT_EQ(result[0], "text/html");
  705. EXPECT_EQ(result[1], "application/json");
  706. std::setlocale(LC_NUMERIC, saved.c_str());
  707. }
  708. TEST(ParseAcceptHeaderTest, InvalidCases) {
  709. std::vector<std::string> result;
  710. // Invalid quality value (> 1.0)
  711. EXPECT_FALSE(
  712. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  713. // Invalid quality value (< 0.0)
  714. EXPECT_FALSE(
  715. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  716. // Invalid quality value (not a number)
  717. EXPECT_FALSE(detail::parse_accept_header(
  718. "text/html;q=invalid,application/json", result));
  719. // Empty quality value
  720. EXPECT_FALSE(
  721. detail::parse_accept_header("text/html;q=,application/json", result));
  722. // Invalid media type format (no slash and not wildcard)
  723. EXPECT_FALSE(
  724. detail::parse_accept_header("invalidtype,application/json", result));
  725. // Empty media type
  726. result.clear();
  727. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  728. // Only commas
  729. result.clear();
  730. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  731. // Valid cases should still work
  732. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  733. EXPECT_EQ(result.size(), 1U);
  734. EXPECT_EQ(result[0], "*/*");
  735. EXPECT_TRUE(detail::parse_accept_header("*", result));
  736. EXPECT_EQ(result.size(), 1U);
  737. EXPECT_EQ(result[0], "*");
  738. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  739. EXPECT_EQ(result.size(), 1U);
  740. EXPECT_EQ(result[0], "text/*");
  741. }
  742. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  743. Server svr;
  744. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  745. EXPECT_EQ(req.accept_content_types.size(), 3U);
  746. EXPECT_EQ(req.accept_content_types[0], "application/json");
  747. EXPECT_EQ(req.accept_content_types[1], "text/html");
  748. EXPECT_EQ(req.accept_content_types[2], "*/*");
  749. res.set_content("ok", "text/plain");
  750. });
  751. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  752. EXPECT_TRUE(false);
  753. res.set_content("bad request", "text/plain");
  754. });
  755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  756. auto se = detail::scope_exit([&] {
  757. svr.stop();
  758. listen_thread.join();
  759. ASSERT_FALSE(svr.is_running());
  760. });
  761. svr.wait_until_ready();
  762. Client cli("localhost", PORT);
  763. {
  764. auto res =
  765. cli.Get("/accept_ok",
  766. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  767. ASSERT_TRUE(res);
  768. EXPECT_EQ(StatusCode::OK_200, res->status);
  769. }
  770. {
  771. auto res = cli.Get("/accept_bad_request",
  772. {{"Accept", "text/html;q=abc,application/json"}});
  773. ASSERT_TRUE(res);
  774. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  775. }
  776. }
  777. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  778. Server svr;
  779. svr.Get("/", [](const Request & /*req*/, Response &res) {
  780. res.set_content("ok", "text/plain");
  781. });
  782. std::atomic<int> start_count{0};
  783. std::atomic<bool> running_when_called{false};
  784. svr.set_start_handler([&]() {
  785. running_when_called = svr.is_running();
  786. start_count++;
  787. });
  788. auto port = svr.bind_to_any_port(HOST);
  789. std::thread t([&]() { svr.listen_after_bind(); });
  790. auto se = detail::scope_exit([&] {
  791. svr.stop();
  792. t.join();
  793. ASSERT_FALSE(svr.is_running());
  794. });
  795. svr.wait_until_ready();
  796. // A successful request proves the accept loop is running, which the start
  797. // handler precedes; so by now the handler must have run exactly once.
  798. Client cli(HOST, port);
  799. cli.set_connection_timeout(std::chrono::seconds(5));
  800. auto res = cli.Get("/");
  801. ASSERT_TRUE(res);
  802. EXPECT_EQ(StatusCode::OK_200, res->status);
  803. EXPECT_EQ(1, start_count.load());
  804. EXPECT_TRUE(running_when_called.load());
  805. }
  806. TEST(DivideTest, DivideStringTests) {
  807. auto divide = [](const std::string &str, char d) {
  808. std::string lhs;
  809. std::string rhs;
  810. detail::divide(str, d,
  811. [&](const char *lhs_data, std::size_t lhs_size,
  812. const char *rhs_data, std::size_t rhs_size) {
  813. lhs.assign(lhs_data, lhs_size);
  814. rhs.assign(rhs_data, rhs_size);
  815. });
  816. return std::make_pair(std::move(lhs), std::move(rhs));
  817. };
  818. {
  819. const auto res = divide("", '=');
  820. EXPECT_EQ(res.first, "");
  821. EXPECT_EQ(res.second, "");
  822. }
  823. {
  824. const auto res = divide("=", '=');
  825. EXPECT_EQ(res.first, "");
  826. EXPECT_EQ(res.second, "");
  827. }
  828. {
  829. const auto res = divide(" ", '=');
  830. EXPECT_EQ(res.first, " ");
  831. EXPECT_EQ(res.second, "");
  832. }
  833. {
  834. const auto res = divide("a", '=');
  835. EXPECT_EQ(res.first, "a");
  836. EXPECT_EQ(res.second, "");
  837. }
  838. {
  839. const auto res = divide("a=", '=');
  840. EXPECT_EQ(res.first, "a");
  841. EXPECT_EQ(res.second, "");
  842. }
  843. {
  844. const auto res = divide("=b", '=');
  845. EXPECT_EQ(res.first, "");
  846. EXPECT_EQ(res.second, "b");
  847. }
  848. {
  849. const auto res = divide("a=b", '=');
  850. EXPECT_EQ(res.first, "a");
  851. EXPECT_EQ(res.second, "b");
  852. }
  853. {
  854. const auto res = divide("a=b=", '=');
  855. EXPECT_EQ(res.first, "a");
  856. EXPECT_EQ(res.second, "b=");
  857. }
  858. {
  859. const auto res = divide("a=b=c", '=');
  860. EXPECT_EQ(res.first, "a");
  861. EXPECT_EQ(res.second, "b=c");
  862. }
  863. }
  864. TEST(SplitTest, ParseQueryString) {
  865. string s = "key1=val1&key2=val2&key3=val3";
  866. Params dic;
  867. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  868. [&](const char *b, const char *e) {
  869. string key, val;
  870. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  871. if (key.empty()) {
  872. key.assign(b2, e2);
  873. } else {
  874. val.assign(b2, e2);
  875. }
  876. });
  877. dic.emplace(key, val);
  878. });
  879. EXPECT_EQ("val1", dic.find("key1")->second);
  880. EXPECT_EQ("val2", dic.find("key2")->second);
  881. EXPECT_EQ("val3", dic.find("key3")->second);
  882. }
  883. TEST(SplitTest, ParseInvalidQueryTests) {
  884. {
  885. string s = " ";
  886. Params dict;
  887. detail::parse_query_text(s, dict);
  888. EXPECT_TRUE(dict.empty());
  889. }
  890. {
  891. string s = " = =";
  892. Params dict;
  893. detail::parse_query_text(s, dict);
  894. EXPECT_TRUE(dict.empty());
  895. }
  896. }
  897. TEST(ParseQueryTest, ParseQueryString) {
  898. {
  899. std::string s = "key1=val1&key2=val2&key3=val3";
  900. Params dic;
  901. detail::parse_query_text(s, dic);
  902. EXPECT_EQ("val1", dic.find("key1")->second);
  903. EXPECT_EQ("val2", dic.find("key2")->second);
  904. EXPECT_EQ("val3", dic.find("key3")->second);
  905. }
  906. {
  907. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  908. Params dic;
  909. detail::parse_query_text(s, dic);
  910. EXPECT_EQ("", dic.find("key1")->second);
  911. EXPECT_EQ("val1", dic.find("key2")->second);
  912. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  913. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  914. }
  915. }
  916. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  917. Params dic;
  918. EXPECT_EQ(detail::params_to_query_str(dic), "");
  919. dic.emplace("key1", "val1");
  920. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  921. dic.emplace("key2", "val2");
  922. dic.emplace("key3", "val3");
  923. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  924. }
  925. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  926. string content_type = "multipart/form-data; boundary=something";
  927. string boundary;
  928. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  929. EXPECT_TRUE(ret);
  930. EXPECT_EQ(boundary, "something");
  931. }
  932. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  933. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  934. string boundary;
  935. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  936. EXPECT_TRUE(ret);
  937. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  938. }
  939. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  940. string content_type =
  941. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  942. string boundary;
  943. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  944. EXPECT_TRUE(ret);
  945. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  946. }
  947. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  948. string content_type =
  949. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  950. string boundary;
  951. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  952. EXPECT_TRUE(ret);
  953. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  954. }
  955. TEST(GetHeaderValueTest, DefaultValue) {
  956. Headers headers = {{"Dummy", "Dummy"}};
  957. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  958. EXPECT_STREQ("text/plain", val);
  959. }
  960. TEST(GetHeaderValueTest, DefaultValueInt) {
  961. Headers headers = {{"Dummy", "Dummy"}};
  962. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  963. EXPECT_EQ(100ull, val);
  964. }
  965. TEST(GetHeaderValueTest, RegularValue) {
  966. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  967. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  968. EXPECT_STREQ("text/html", val);
  969. }
  970. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  971. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  972. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  973. EXPECT_STREQ("text/html", val);
  974. }
  975. TEST(GetHeaderValueTest, SetContent) {
  976. Response res;
  977. res.set_content("html", "text/html");
  978. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  979. res.set_content("text", "text/plain");
  980. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  981. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  982. }
  983. TEST(GetHeaderValueTest, RegularValueInt) {
  984. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  985. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  986. EXPECT_EQ(100ull, val);
  987. }
  988. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  989. Headers headers = {{"Content-Length", "x"}};
  990. auto is_invalid_value = false;
  991. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  992. is_invalid_value);
  993. EXPECT_EQ(0ull, val);
  994. EXPECT_TRUE(is_invalid_value);
  995. }
  996. TEST(GetHeaderValueTest, Range) {
  997. {
  998. Headers headers = {make_range_header({{1, -1}})};
  999. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1000. EXPECT_STREQ("bytes=1-", val);
  1001. }
  1002. {
  1003. Headers headers = {make_range_header({{-1, 1}})};
  1004. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1005. EXPECT_STREQ("bytes=-1", val);
  1006. }
  1007. {
  1008. Headers headers = {make_range_header({{1, 10}})};
  1009. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1010. EXPECT_STREQ("bytes=1-10", val);
  1011. }
  1012. {
  1013. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1014. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1015. EXPECT_STREQ("bytes=1-10, 100-", val);
  1016. }
  1017. {
  1018. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1019. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1020. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1021. }
  1022. {
  1023. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1024. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1025. EXPECT_STREQ("bytes=0-0, -1", val);
  1026. }
  1027. }
  1028. TEST(ParseHeaderValueTest, Range) {
  1029. {
  1030. Ranges ranges;
  1031. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1032. EXPECT_TRUE(ret);
  1033. EXPECT_EQ(1u, ranges.size());
  1034. EXPECT_EQ(1u, ranges[0].first);
  1035. EXPECT_EQ(-1, ranges[0].second);
  1036. }
  1037. {
  1038. Ranges ranges;
  1039. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1040. EXPECT_TRUE(ret);
  1041. EXPECT_EQ(1u, ranges.size());
  1042. EXPECT_EQ(-1, ranges[0].first);
  1043. EXPECT_EQ(1u, ranges[0].second);
  1044. }
  1045. {
  1046. Ranges ranges;
  1047. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1048. EXPECT_TRUE(ret);
  1049. EXPECT_EQ(1u, ranges.size());
  1050. EXPECT_EQ(1u, ranges[0].first);
  1051. EXPECT_EQ(10u, ranges[0].second);
  1052. }
  1053. {
  1054. Ranges ranges;
  1055. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1056. EXPECT_FALSE(ret);
  1057. }
  1058. {
  1059. Ranges ranges;
  1060. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1061. EXPECT_TRUE(ret);
  1062. EXPECT_EQ(2u, ranges.size());
  1063. EXPECT_EQ(1u, ranges[0].first);
  1064. EXPECT_EQ(10u, ranges[0].second);
  1065. EXPECT_EQ(100u, ranges[1].first);
  1066. EXPECT_EQ(-1, ranges[1].second);
  1067. }
  1068. {
  1069. Ranges ranges;
  1070. auto ret =
  1071. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1072. EXPECT_TRUE(ret);
  1073. EXPECT_EQ(3u, ranges.size());
  1074. EXPECT_EQ(1u, ranges[0].first);
  1075. EXPECT_EQ(10u, ranges[0].second);
  1076. EXPECT_EQ(100u, ranges[1].first);
  1077. EXPECT_EQ(200u, ranges[1].second);
  1078. EXPECT_EQ(300u, ranges[2].first);
  1079. EXPECT_EQ(400u, ranges[2].second);
  1080. }
  1081. {
  1082. Ranges ranges;
  1083. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1084. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1085. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1086. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1087. EXPECT_FALSE(detail::parse_range_header("bytes= ", 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=a-b", ranges));
  1092. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1093. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1094. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1095. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1096. EXPECT_TRUE(ranges.empty());
  1097. }
  1098. }
  1099. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1100. Request req;
  1101. req.set_header("Accept-Encoding", "gzip");
  1102. Response res;
  1103. res.set_header("Content-Type", "text/plain");
  1104. auto ret = detail::encoding_type(req, res);
  1105. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1106. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1107. #else
  1108. EXPECT_TRUE(ret == detail::EncodingType::None);
  1109. #endif
  1110. }
  1111. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1112. Request req;
  1113. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1114. Response res;
  1115. res.set_header("Content-Type", "text/plain");
  1116. auto ret = detail::encoding_type(req, res);
  1117. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1118. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1119. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1120. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1121. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1122. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1123. #else
  1124. EXPECT_TRUE(ret == detail::EncodingType::None);
  1125. #endif
  1126. }
  1127. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1128. Request req;
  1129. req.set_header("Accept-Encoding",
  1130. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1131. Response res;
  1132. res.set_header("Content-Type", "text/plain");
  1133. auto ret = detail::encoding_type(req, res);
  1134. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1136. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1137. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1138. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1139. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1140. #else
  1141. EXPECT_TRUE(ret == detail::EncodingType::None);
  1142. #endif
  1143. }
  1144. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1145. // All supported encodings rejected with q=0 should return None
  1146. Request req;
  1147. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1148. Response res;
  1149. res.set_header("Content-Type", "text/plain");
  1150. auto ret = detail::encoding_type(req, res);
  1151. EXPECT_TRUE(ret == detail::EncodingType::None);
  1152. }
  1153. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1154. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1155. Request req;
  1156. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1157. Response res;
  1158. res.set_header("Content-Type", "text/plain");
  1159. auto ret = detail::encoding_type(req, res);
  1160. EXPECT_TRUE(ret == detail::EncodingType::None);
  1161. }
  1162. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1163. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1164. Request req;
  1165. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1166. Response res;
  1167. res.set_header("Content-Type", "text/plain");
  1168. auto ret = detail::encoding_type(req, res);
  1169. EXPECT_TRUE(ret == detail::EncodingType::None);
  1170. }
  1171. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1172. // RFC 7231: Accept-Encoding values are case-insensitive
  1173. Request req;
  1174. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1175. Response res;
  1176. res.set_header("Content-Type", "text/plain");
  1177. auto ret = detail::encoding_type(req, res);
  1178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1179. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1180. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1182. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1184. #else
  1185. EXPECT_TRUE(ret == detail::EncodingType::None);
  1186. #endif
  1187. }
  1188. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1189. // q value should determine priority, not hardcoded order
  1190. Request req;
  1191. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1192. Response res;
  1193. res.set_header("Content-Type", "text/plain");
  1194. auto ret = detail::encoding_type(req, res);
  1195. // gzip has highest q=1.0, so it should be selected even though
  1196. // br and zstd are also supported
  1197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1198. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1199. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1200. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1201. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1202. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1203. #else
  1204. EXPECT_TRUE(ret == detail::EncodingType::None);
  1205. #endif
  1206. }
  1207. TEST(BufferStreamTest, read) {
  1208. detail::BufferStream strm1;
  1209. Stream &strm = strm1;
  1210. EXPECT_EQ(5, strm.write("hello"));
  1211. char buf[512];
  1212. EXPECT_EQ(2, strm.read(buf, 2));
  1213. EXPECT_EQ('h', buf[0]);
  1214. EXPECT_EQ('e', buf[1]);
  1215. EXPECT_EQ(2, strm.read(buf, 2));
  1216. EXPECT_EQ('l', buf[0]);
  1217. EXPECT_EQ('l', buf[1]);
  1218. EXPECT_EQ(1, strm.read(buf, 1));
  1219. EXPECT_EQ('o', buf[0]);
  1220. EXPECT_EQ(0, strm.read(buf, 1));
  1221. }
  1222. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1223. auto host = "www.httpwatch.com";
  1224. auto ip = hosted_at(host);
  1225. EXPECT_EQ("23.96.13.243", ip);
  1226. std::vector<std::string> addrs;
  1227. hosted_at(host, addrs);
  1228. EXPECT_EQ(1u, addrs.size());
  1229. }
  1230. #if 0 // It depends on each test environment...
  1231. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1232. auto host = "www.youtube.com";
  1233. std::vector<std::string> addrs;
  1234. hosted_at(host, addrs);
  1235. EXPECT_EQ(20u, addrs.size());
  1236. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1237. EXPECT_TRUE(it != addrs.end());
  1238. }
  1239. #endif
  1240. class ChunkedEncodingTest : public ::testing::Test {
  1241. protected:
  1242. ChunkedEncodingTest()
  1243. : cli_(HOST, PORT)
  1244. #ifdef CPPHTTPLIB_SSL_ENABLED
  1245. ,
  1246. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1247. #endif
  1248. {
  1249. cli_.set_connection_timeout(2);
  1250. #ifdef CPPHTTPLIB_SSL_ENABLED
  1251. cli_.enable_server_certificate_verification(false);
  1252. #endif
  1253. }
  1254. virtual void SetUp() {
  1255. read_file("./image.jpg", image_data_);
  1256. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1257. res.set_content("Hello World!", "text/plain");
  1258. });
  1259. svr_.Get(
  1260. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1261. res.set_chunked_content_provider(
  1262. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1263. size_t remaining = image_data_.size() - offset;
  1264. if (remaining == 0) {
  1265. sink.done();
  1266. } else {
  1267. constexpr size_t CHUNK_SIZE = 1024;
  1268. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1269. sink.write(&image_data_[offset], send_size);
  1270. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1271. }
  1272. return true;
  1273. });
  1274. });
  1275. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1276. svr_.wait_until_ready();
  1277. }
  1278. virtual void TearDown() {
  1279. svr_.stop();
  1280. if (!request_threads_.empty()) {
  1281. std::this_thread::sleep_for(std::chrono::seconds(1));
  1282. for (auto &t : request_threads_) {
  1283. t.join();
  1284. }
  1285. }
  1286. t_.join();
  1287. }
  1288. #ifdef CPPHTTPLIB_SSL_ENABLED
  1289. SSLClient cli_;
  1290. SSLServer svr_;
  1291. #else
  1292. Client cli_;
  1293. Server svr_;
  1294. #endif
  1295. thread t_;
  1296. std::vector<thread> request_threads_;
  1297. std::string image_data_;
  1298. };
  1299. TEST_F(ChunkedEncodingTest, NormalGet) {
  1300. auto res = cli_.Get("/chunked");
  1301. ASSERT_TRUE(res);
  1302. std::string out;
  1303. read_file("./image.jpg", out);
  1304. EXPECT_EQ(StatusCode::OK_200, res->status);
  1305. EXPECT_EQ(out, res->body);
  1306. }
  1307. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1308. std::string body;
  1309. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1310. body.append(data, data_length);
  1311. return true;
  1312. });
  1313. ASSERT_TRUE(res);
  1314. std::string out;
  1315. read_file("./image.jpg", out);
  1316. EXPECT_EQ(StatusCode::OK_200, res->status);
  1317. EXPECT_EQ(out, body);
  1318. }
  1319. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1320. std::string body;
  1321. auto res = cli_.Get(
  1322. "/chunked",
  1323. [&](const Response &response) {
  1324. EXPECT_EQ(StatusCode::OK_200, response.status);
  1325. return true;
  1326. },
  1327. [&](const char *data, size_t data_length) {
  1328. body.append(data, data_length);
  1329. return true;
  1330. });
  1331. ASSERT_TRUE(res);
  1332. std::string out;
  1333. read_file("./image.jpg", out);
  1334. EXPECT_EQ(StatusCode::OK_200, res->status);
  1335. EXPECT_EQ(out, body);
  1336. }
  1337. TEST(RangeTest, FromHTTPBin_Online) {
  1338. auto host = "httpbingo.org";
  1339. auto path = std::string{"/range/32"};
  1340. #ifdef CPPHTTPLIB_SSL_ENABLED
  1341. auto port = 443;
  1342. SSLClient cli(host, port);
  1343. #else
  1344. auto port = 80;
  1345. Client cli(host, port);
  1346. #endif
  1347. cli.set_connection_timeout(5);
  1348. {
  1349. auto res = cli.Get(path);
  1350. ASSERT_TRUE(res);
  1351. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1352. EXPECT_EQ(StatusCode::OK_200, res->status);
  1353. }
  1354. {
  1355. Headers headers = {make_range_header({{1, -1}})};
  1356. auto res = cli.Get(path, headers);
  1357. ASSERT_TRUE(res);
  1358. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1360. }
  1361. {
  1362. Headers headers = {make_range_header({{1, 10}})};
  1363. auto res = cli.Get(path, headers);
  1364. ASSERT_TRUE(res);
  1365. EXPECT_EQ("bcdefghijk", res->body);
  1366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1367. }
  1368. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1369. // entire resource, while the original httpbin returned 200. Both are
  1370. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1371. {
  1372. Headers headers = {make_range_header({{0, 31}})};
  1373. auto res = cli.Get(path, headers);
  1374. ASSERT_TRUE(res);
  1375. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1376. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1377. res->status == StatusCode::PartialContent_206);
  1378. }
  1379. {
  1380. Headers headers = {make_range_header({{0, -1}})};
  1381. auto res = cli.Get(path, headers);
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1384. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1385. res->status == StatusCode::PartialContent_206);
  1386. }
  1387. // go-httpbin returns 206 with clamped range for over-range requests,
  1388. // while the original httpbin returned 416. Both behaviors are observed
  1389. // in real servers, so we only verify the request succeeds.
  1390. {
  1391. Headers headers = {make_range_header({{0, 32}})};
  1392. auto res = cli.Get(path, headers);
  1393. ASSERT_TRUE(res);
  1394. }
  1395. }
  1396. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1397. auto host = "unresolvableaddress.local";
  1398. auto path = std::string{"/"};
  1399. #ifdef CPPHTTPLIB_SSL_ENABLED
  1400. auto port = 443;
  1401. SSLClient cli(host, port);
  1402. #else
  1403. auto port = 80;
  1404. Client cli(host, port);
  1405. #endif
  1406. cli.set_connection_timeout(1);
  1407. {
  1408. auto res = cli.Get(path);
  1409. ASSERT_FALSE(res);
  1410. }
  1411. std::this_thread::sleep_for(std::chrono::seconds(8));
  1412. }
  1413. #if defined(__linux__) && defined(__GLIBC__) && \
  1414. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1415. // Forward declaration: in split builds split.py strips `inline` and moves the
  1416. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1417. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1418. // against the symbol in both header-only and split builds.
  1419. namespace httplib {
  1420. namespace detail {
  1421. int getaddrinfo_with_timeout(const char *node, const char *service,
  1422. const struct addrinfo *hints,
  1423. struct addrinfo **res, time_t timeout_sec);
  1424. } // namespace detail
  1425. } // namespace httplib
  1426. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1427. //
  1428. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1429. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1430. // gai_suspend() call hits the connection timeout the function calls
  1431. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1432. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1433. // still alive and still references the now-destroyed stack frame.
  1434. //
  1435. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1436. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1437. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1438. // and runs them in a container.
  1439. namespace {
  1440. bool should_run_issue_2431_tests() {
  1441. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1442. return v && *v && std::string(v) != "0";
  1443. }
  1444. std::string unique_unresolvable_host(int n) {
  1445. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1446. // glibc still asks the configured nameserver — which is exactly the path
  1447. // we want to exercise. A unique label per call avoids the resolver cache.
  1448. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1449. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1450. std::to_string(n) + ".invalid";
  1451. }
  1452. } // namespace
  1453. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1454. if (!should_run_issue_2431_tests()) {
  1455. GTEST_SKIP()
  1456. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1457. }
  1458. for (int i = 0; i < 8; ++i) {
  1459. struct addrinfo hints;
  1460. memset(&hints, 0, sizeof(hints));
  1461. hints.ai_family = AF_UNSPEC;
  1462. hints.ai_socktype = SOCK_STREAM;
  1463. auto host = unique_unresolvable_host(i);
  1464. struct addrinfo *result = nullptr;
  1465. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1466. &result, /*timeout_sec=*/1);
  1467. if (rc == 0 && result) { freeaddrinfo(result); }
  1468. }
  1469. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1470. // stack region they still believe holds their gaicb.
  1471. std::this_thread::sleep_for(std::chrono::seconds(3));
  1472. }
  1473. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1474. if (!should_run_issue_2431_tests()) {
  1475. GTEST_SKIP()
  1476. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1477. }
  1478. std::atomic<bool> stop{false};
  1479. std::vector<std::thread> threads;
  1480. for (int t = 0; t < 8; ++t) {
  1481. threads.emplace_back([t, &stop] {
  1482. int i = 0;
  1483. while (!stop.load(std::memory_order_relaxed)) {
  1484. struct addrinfo hints;
  1485. memset(&hints, 0, sizeof(hints));
  1486. hints.ai_family = AF_UNSPEC;
  1487. hints.ai_socktype = SOCK_STREAM;
  1488. auto host = unique_unresolvable_host(t * 100000 + i++);
  1489. struct addrinfo *result = nullptr;
  1490. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1491. &result, /*timeout_sec=*/1);
  1492. if (rc == 0 && result) { freeaddrinfo(result); }
  1493. }
  1494. });
  1495. }
  1496. std::this_thread::sleep_for(std::chrono::seconds(8));
  1497. stop.store(true, std::memory_order_relaxed);
  1498. for (auto &th : threads) {
  1499. th.join();
  1500. }
  1501. std::this_thread::sleep_for(std::chrono::seconds(3));
  1502. }
  1503. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1504. if (!should_run_issue_2431_tests()) {
  1505. GTEST_SKIP()
  1506. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1507. }
  1508. std::atomic<bool> stop{false};
  1509. std::vector<std::thread> threads;
  1510. for (int t = 0; t < 8; ++t) {
  1511. threads.emplace_back([t, &stop] {
  1512. int i = 0;
  1513. while (!stop.load(std::memory_order_relaxed)) {
  1514. auto host = unique_unresolvable_host(t * 100000 + i++);
  1515. Client cli(host, 80);
  1516. cli.set_connection_timeout(1, 0);
  1517. cli.set_read_timeout(1, 0);
  1518. cli.set_write_timeout(1, 0);
  1519. (void)cli.Get("/");
  1520. }
  1521. });
  1522. }
  1523. std::this_thread::sleep_for(std::chrono::seconds(8));
  1524. stop.store(true, std::memory_order_relaxed);
  1525. for (auto &th : threads) {
  1526. th.join();
  1527. }
  1528. std::this_thread::sleep_for(std::chrono::seconds(3));
  1529. }
  1530. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1531. TEST(ConnectionErrorTest, InvalidHost) {
  1532. auto host = "-abcde.com";
  1533. #ifdef CPPHTTPLIB_SSL_ENABLED
  1534. auto port = 443;
  1535. SSLClient cli(host, port);
  1536. #else
  1537. auto port = 80;
  1538. Client cli(host, port);
  1539. #endif
  1540. cli.set_connection_timeout(std::chrono::seconds(2));
  1541. auto res = cli.Get("/");
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Connection, res.error());
  1544. }
  1545. TEST(ConnectionErrorTest, InvalidHost2) {
  1546. auto host = "httpcan.org/";
  1547. #ifdef CPPHTTPLIB_SSL_ENABLED
  1548. SSLClient cli(host);
  1549. #else
  1550. Client cli(host);
  1551. #endif
  1552. cli.set_connection_timeout(std::chrono::seconds(2));
  1553. auto res = cli.Get("/");
  1554. ASSERT_TRUE(!res);
  1555. EXPECT_EQ(Error::Connection, res.error());
  1556. }
  1557. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1558. auto host = "httpcan.org/";
  1559. #ifdef CPPHTTPLIB_SSL_ENABLED
  1560. SSLClient cli(host);
  1561. #else
  1562. Client cli(host);
  1563. #endif
  1564. cli.set_connection_timeout(std::chrono::seconds(2));
  1565. auto res = cli.Get("/");
  1566. ASSERT_TRUE(!res);
  1567. stringstream s;
  1568. s << "error code: " << res.error();
  1569. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1570. }
  1571. TEST(ConnectionErrorTest, InvalidPort) {
  1572. auto host = "localhost";
  1573. auto port = 44380;
  1574. #ifdef CPPHTTPLIB_SSL_ENABLED
  1575. SSLClient cli(host, port);
  1576. #else
  1577. Client cli(host, port);
  1578. #endif
  1579. cli.set_connection_timeout(std::chrono::seconds(2));
  1580. auto res = cli.Get("/");
  1581. ASSERT_TRUE(!res);
  1582. EXPECT_TRUE(Error::Connection == res.error() ||
  1583. Error::ConnectionTimeout == res.error());
  1584. }
  1585. TEST(ConnectionErrorTest, Timeout_Online) {
  1586. auto host = "google.com";
  1587. #ifdef CPPHTTPLIB_SSL_ENABLED
  1588. auto port = 44380;
  1589. SSLClient cli(host, port);
  1590. #else
  1591. auto port = 8080;
  1592. Client cli(host, port);
  1593. #endif
  1594. cli.set_connection_timeout(std::chrono::seconds(2));
  1595. // only probe one address type so that the error reason
  1596. // correlates to the timed-out IPv4, not the unsupported
  1597. // IPv6 connection attempt
  1598. cli.set_address_family(AF_INET);
  1599. auto res = cli.Get("/");
  1600. ASSERT_TRUE(!res);
  1601. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1602. }
  1603. TEST(CancelTest, NoCancel_Online) {
  1604. auto host = "httpbingo.org";
  1605. auto path = std::string{"/range/32"};
  1606. #ifdef CPPHTTPLIB_SSL_ENABLED
  1607. auto port = 443;
  1608. SSLClient cli(host, port);
  1609. #else
  1610. auto port = 80;
  1611. Client cli(host, port);
  1612. #endif
  1613. cli.set_connection_timeout(std::chrono::seconds(5));
  1614. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1615. ASSERT_TRUE(res);
  1616. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1617. EXPECT_EQ(StatusCode::OK_200, res->status);
  1618. }
  1619. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1620. // Use /bytes with a large payload so that the DownloadProgress callback
  1621. // (which only fires for Content-Length responses) is invoked before the
  1622. // entire body is received, giving cancellation a chance to fire.
  1623. auto host = "httpbingo.org";
  1624. auto path = std::string{"/bytes/524288"};
  1625. #ifdef CPPHTTPLIB_SSL_ENABLED
  1626. auto port = 443;
  1627. SSLClient cli(host, port);
  1628. #else
  1629. auto port = 80;
  1630. Client cli(host, port);
  1631. #endif
  1632. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1633. cli.set_connection_timeout(std::chrono::seconds(5));
  1634. ASSERT_TRUE(!res);
  1635. EXPECT_EQ(Error::Canceled, res.error());
  1636. }
  1637. TEST(CancelTest, WithCancelLargePayload_Online) {
  1638. auto host = "httpbingo.org";
  1639. auto path = std::string{"/bytes/524288"};
  1640. #ifdef CPPHTTPLIB_SSL_ENABLED
  1641. auto port = 443;
  1642. SSLClient cli(host, port);
  1643. #else
  1644. auto port = 80;
  1645. Client cli(host, port);
  1646. #endif
  1647. cli.set_connection_timeout(std::chrono::seconds(5));
  1648. uint32_t count = 0;
  1649. auto res =
  1650. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1651. ASSERT_TRUE(!res);
  1652. EXPECT_EQ(Error::Canceled, res.error());
  1653. }
  1654. TEST(CancelTest, NoCancelPost) {
  1655. Server svr;
  1656. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1657. res.set_content("Hello World!", "text/plain");
  1658. });
  1659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1660. auto se = detail::scope_exit([&] {
  1661. svr.stop();
  1662. thread.join();
  1663. ASSERT_FALSE(svr.is_running());
  1664. });
  1665. svr.wait_until_ready();
  1666. Client cli(HOST, PORT);
  1667. cli.set_connection_timeout(std::chrono::seconds(5));
  1668. auto res =
  1669. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1670. "application/json", [](uint64_t, uint64_t) { return true; });
  1671. ASSERT_TRUE(res);
  1672. EXPECT_EQ("Hello World!", res->body);
  1673. EXPECT_EQ(StatusCode::OK_200, res->status);
  1674. }
  1675. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1676. Server svr;
  1677. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1678. res.set_content("Hello World!", "text/plain");
  1679. });
  1680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1681. auto se = detail::scope_exit([&] {
  1682. svr.stop();
  1683. thread.join();
  1684. ASSERT_FALSE(svr.is_running());
  1685. });
  1686. svr.wait_until_ready();
  1687. Client cli(HOST, PORT);
  1688. cli.set_connection_timeout(std::chrono::seconds(5));
  1689. auto res =
  1690. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1691. "application/json", [](uint64_t, uint64_t) { return false; });
  1692. ASSERT_TRUE(!res);
  1693. EXPECT_EQ(Error::Canceled, res.error());
  1694. }
  1695. TEST(CancelTest, WithCancelLargePayloadPost) {
  1696. Server svr;
  1697. svr.set_payload_max_length(200 * 1024 * 1024);
  1698. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1699. res.set_content(LARGE_DATA, "text/plain");
  1700. });
  1701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1702. auto se = detail::scope_exit([&] {
  1703. svr.stop();
  1704. thread.join();
  1705. ASSERT_FALSE(svr.is_running());
  1706. });
  1707. svr.wait_until_ready();
  1708. Client cli(HOST, PORT);
  1709. cli.set_payload_max_length(200 * 1024 * 1024);
  1710. cli.set_connection_timeout(std::chrono::seconds(5));
  1711. auto res =
  1712. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1713. "application/json", [](uint64_t, uint64_t) { return false; });
  1714. ASSERT_TRUE(!res);
  1715. EXPECT_EQ(Error::Canceled, res.error());
  1716. }
  1717. TEST(CancelTest, NoCancelPut) {
  1718. Server svr;
  1719. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1720. res.set_content("Hello World!", "text/plain");
  1721. });
  1722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. thread.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. Client cli(HOST, PORT);
  1730. cli.set_connection_timeout(std::chrono::seconds(5));
  1731. auto res =
  1732. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1733. "application/json", [](uint64_t, uint64_t) { return true; });
  1734. ASSERT_TRUE(res);
  1735. EXPECT_EQ("Hello World!", res->body);
  1736. EXPECT_EQ(StatusCode::OK_200, res->status);
  1737. }
  1738. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1739. Server svr;
  1740. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1741. res.set_content("Hello World!", "text/plain");
  1742. });
  1743. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1744. auto se = detail::scope_exit([&] {
  1745. svr.stop();
  1746. thread.join();
  1747. ASSERT_FALSE(svr.is_running());
  1748. });
  1749. svr.wait_until_ready();
  1750. Client cli(HOST, PORT);
  1751. cli.set_connection_timeout(std::chrono::seconds(5));
  1752. auto res =
  1753. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1754. "application/json", [](uint64_t, uint64_t) { return false; });
  1755. ASSERT_TRUE(!res);
  1756. EXPECT_EQ(Error::Canceled, res.error());
  1757. }
  1758. TEST(CancelTest, WithCancelLargePayloadPut) {
  1759. Server svr;
  1760. svr.set_payload_max_length(200 * 1024 * 1024);
  1761. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1762. res.set_content(LARGE_DATA, "text/plain");
  1763. });
  1764. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1765. auto se = detail::scope_exit([&] {
  1766. svr.stop();
  1767. thread.join();
  1768. ASSERT_FALSE(svr.is_running());
  1769. });
  1770. svr.wait_until_ready();
  1771. Client cli(HOST, PORT);
  1772. cli.set_payload_max_length(200 * 1024 * 1024);
  1773. cli.set_connection_timeout(std::chrono::seconds(5));
  1774. auto res =
  1775. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1776. "application/json", [](uint64_t, uint64_t) { return false; });
  1777. ASSERT_TRUE(!res);
  1778. EXPECT_EQ(Error::Canceled, res.error());
  1779. }
  1780. TEST(CancelTest, NoCancelPatch) {
  1781. Server svr;
  1782. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1783. res.set_content("Hello World!", "text/plain");
  1784. });
  1785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1786. auto se = detail::scope_exit([&] {
  1787. svr.stop();
  1788. thread.join();
  1789. ASSERT_FALSE(svr.is_running());
  1790. });
  1791. svr.wait_until_ready();
  1792. Client cli(HOST, PORT);
  1793. cli.set_connection_timeout(std::chrono::seconds(5));
  1794. auto res =
  1795. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1796. "application/json", [](uint64_t, uint64_t) { return true; });
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ("Hello World!", res->body);
  1799. EXPECT_EQ(StatusCode::OK_200, res->status);
  1800. }
  1801. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1802. Server svr;
  1803. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1804. res.set_content("Hello World!", "text/plain");
  1805. });
  1806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1807. auto se = detail::scope_exit([&] {
  1808. svr.stop();
  1809. thread.join();
  1810. ASSERT_FALSE(svr.is_running());
  1811. });
  1812. svr.wait_until_ready();
  1813. Client cli(HOST, PORT);
  1814. cli.set_connection_timeout(std::chrono::seconds(5));
  1815. auto res =
  1816. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1817. "application/json", [](uint64_t, uint64_t) { return false; });
  1818. ASSERT_TRUE(!res);
  1819. EXPECT_EQ(Error::Canceled, res.error());
  1820. }
  1821. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1822. Server svr;
  1823. svr.set_payload_max_length(200 * 1024 * 1024);
  1824. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1825. res.set_content(LARGE_DATA, "text/plain");
  1826. });
  1827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1828. auto se = detail::scope_exit([&] {
  1829. svr.stop();
  1830. thread.join();
  1831. ASSERT_FALSE(svr.is_running());
  1832. });
  1833. svr.wait_until_ready();
  1834. Client cli(HOST, PORT);
  1835. cli.set_payload_max_length(200 * 1024 * 1024);
  1836. cli.set_connection_timeout(std::chrono::seconds(5));
  1837. auto res =
  1838. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1839. "application/json", [](uint64_t, uint64_t) { return false; });
  1840. ASSERT_TRUE(!res);
  1841. EXPECT_EQ(Error::Canceled, res.error());
  1842. }
  1843. TEST(CancelTest, NoCancelDelete) {
  1844. Server svr;
  1845. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1846. res.set_content("Hello World!", "text/plain");
  1847. });
  1848. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1849. auto se = detail::scope_exit([&] {
  1850. svr.stop();
  1851. thread.join();
  1852. ASSERT_FALSE(svr.is_running());
  1853. });
  1854. svr.wait_until_ready();
  1855. Client cli(HOST, PORT);
  1856. cli.set_connection_timeout(std::chrono::seconds(5));
  1857. auto res =
  1858. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1859. "application/json", [](uint64_t, uint64_t) { return true; });
  1860. ASSERT_TRUE(res);
  1861. EXPECT_EQ("Hello World!", res->body);
  1862. EXPECT_EQ(StatusCode::OK_200, res->status);
  1863. }
  1864. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1865. Server svr;
  1866. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1867. res.set_content("Hello World!", "text/plain");
  1868. });
  1869. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1870. auto se = detail::scope_exit([&] {
  1871. svr.stop();
  1872. thread.join();
  1873. ASSERT_FALSE(svr.is_running());
  1874. });
  1875. svr.wait_until_ready();
  1876. Client cli(HOST, PORT);
  1877. cli.set_connection_timeout(std::chrono::seconds(5));
  1878. auto res =
  1879. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1880. "application/json", [](uint64_t, uint64_t) { return false; });
  1881. ASSERT_TRUE(!res);
  1882. EXPECT_EQ(Error::Canceled, res.error());
  1883. }
  1884. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1885. Server svr;
  1886. svr.set_payload_max_length(200 * 1024 * 1024);
  1887. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1888. res.set_content(LARGE_DATA, "text/plain");
  1889. });
  1890. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1891. auto se = detail::scope_exit([&] {
  1892. svr.stop();
  1893. thread.join();
  1894. ASSERT_FALSE(svr.is_running());
  1895. });
  1896. svr.wait_until_ready();
  1897. Client cli(HOST, PORT);
  1898. cli.set_payload_max_length(200 * 1024 * 1024);
  1899. cli.set_connection_timeout(std::chrono::seconds(5));
  1900. auto res =
  1901. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1902. "application/json", [](uint64_t, uint64_t) { return false; });
  1903. ASSERT_TRUE(!res);
  1904. EXPECT_EQ(Error::Canceled, res.error());
  1905. }
  1906. static std::string remove_whitespace(const std::string &input) {
  1907. std::string output;
  1908. output.reserve(input.size());
  1909. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1910. [](unsigned char c) { return !std::isspace(c); });
  1911. return output;
  1912. }
  1913. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1914. auto host = "httpbingo.org";
  1915. auto path = std::string{"/basic-auth/hello/world"};
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. auto port = 443;
  1918. SSLClient cli(host, port);
  1919. #else
  1920. auto port = 80;
  1921. Client cli(host, port);
  1922. #endif
  1923. {
  1924. auto res = cli.Get(path);
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1927. }
  1928. {
  1929. auto res =
  1930. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1931. ASSERT_TRUE(res);
  1932. auto body = remove_whitespace(res->body);
  1933. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1934. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1935. EXPECT_EQ(StatusCode::OK_200, res->status);
  1936. }
  1937. {
  1938. cli.set_basic_auth("hello", "world");
  1939. auto res = cli.Get(path);
  1940. ASSERT_TRUE(res);
  1941. auto body = remove_whitespace(res->body);
  1942. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1943. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. }
  1946. {
  1947. cli.set_basic_auth("hello", "bad");
  1948. auto res = cli.Get(path);
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1951. }
  1952. {
  1953. cli.set_basic_auth("bad", "world");
  1954. auto res = cli.Get(path);
  1955. ASSERT_TRUE(res);
  1956. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1957. }
  1958. }
  1959. #ifdef CPPHTTPLIB_SSL_ENABLED
  1960. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1961. auto host = "httpbingo.org";
  1962. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1963. auto paths = std::vector<std::string>{
  1964. "/digest-auth/auth/hello/world/MD5",
  1965. "/digest-auth/auth/hello/world/SHA-256",
  1966. };
  1967. auto port = 443;
  1968. SSLClient cli(host, port);
  1969. {
  1970. auto res = cli.Get(unauth_path);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1973. }
  1974. {
  1975. cli.set_digest_auth("hello", "world");
  1976. for (const auto &path : paths) {
  1977. auto res = cli.Get(path.c_str());
  1978. ASSERT_TRUE(res);
  1979. auto body = remove_whitespace(res->body);
  1980. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1981. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1982. EXPECT_EQ(StatusCode::OK_200, res->status);
  1983. }
  1984. cli.set_digest_auth("hello", "bad");
  1985. for (const auto &path : paths) {
  1986. auto res = cli.Get(path.c_str());
  1987. ASSERT_TRUE(res);
  1988. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1989. }
  1990. }
  1991. }
  1992. #endif
  1993. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1994. auto host = "google.com";
  1995. auto another_host = "example.com";
  1996. auto wrong_ip = "0.0.0.0";
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. SSLClient cli(host);
  1999. #else
  2000. Client cli(host);
  2001. #endif
  2002. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2003. auto res = cli.Get("/");
  2004. ASSERT_TRUE(res);
  2005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2006. }
  2007. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2008. auto host = "google.com";
  2009. auto wrong_ip = "0.0.0.0";
  2010. #ifdef CPPHTTPLIB_SSL_ENABLED
  2011. SSLClient cli(host);
  2012. #else
  2013. Client cli(host);
  2014. #endif
  2015. cli.set_hostname_addr_map({{host, wrong_ip}});
  2016. auto res = cli.Get("/");
  2017. ASSERT_TRUE(!res);
  2018. EXPECT_EQ(Error::Connection, res.error());
  2019. }
  2020. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2021. auto host = "httpbingo.org";
  2022. auto path = std::string{"/absolute-redirect/3"};
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. SSLClient cli(host);
  2025. #else
  2026. Client cli(host);
  2027. #endif
  2028. cli.set_follow_location(true);
  2029. auto res = cli.Get(path);
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::OK_200, res->status);
  2032. }
  2033. TEST(RedirectTest, Redirect_Online) {
  2034. auto host = "httpbingo.org";
  2035. auto path = std::string{"/redirect/3"};
  2036. #ifdef CPPHTTPLIB_SSL_ENABLED
  2037. SSLClient cli(host);
  2038. #else
  2039. Client cli(host);
  2040. #endif
  2041. cli.set_follow_location(true);
  2042. auto res = cli.Get(path);
  2043. ASSERT_TRUE(res);
  2044. EXPECT_EQ(StatusCode::OK_200, res->status);
  2045. }
  2046. TEST(RelativeRedirectTest, Redirect_Online) {
  2047. auto host = "httpbingo.org";
  2048. auto path = std::string{"/relative-redirect/3"};
  2049. #ifdef CPPHTTPLIB_SSL_ENABLED
  2050. SSLClient cli(host);
  2051. #else
  2052. Client cli(host);
  2053. #endif
  2054. cli.set_follow_location(true);
  2055. auto res = cli.Get(path);
  2056. ASSERT_TRUE(res);
  2057. EXPECT_EQ(StatusCode::OK_200, res->status);
  2058. }
  2059. TEST(TooManyRedirectTest, Redirect_Online) {
  2060. auto host = "httpbingo.org";
  2061. auto path = std::string{"/redirect/21"};
  2062. #ifdef CPPHTTPLIB_SSL_ENABLED
  2063. SSLClient cli(host);
  2064. #else
  2065. Client cli(host);
  2066. #endif
  2067. cli.set_follow_location(true);
  2068. auto res = cli.Get(path);
  2069. ASSERT_TRUE(!res);
  2070. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2071. }
  2072. #ifdef CPPHTTPLIB_SSL_ENABLED
  2073. TEST(YahooRedirectTest, Redirect_Online) {
  2074. Client cli("yahoo.com");
  2075. auto res = cli.Get("/");
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2078. cli.set_follow_location(true);
  2079. res = cli.Get("/");
  2080. ASSERT_TRUE(res);
  2081. EXPECT_EQ(StatusCode::OK_200, res->status);
  2082. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2083. }
  2084. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2085. #define REDIR_HOST "httpbingo.org"
  2086. #define REDIR_PATH "/redirect-to"
  2087. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2088. SSLClient cli(REDIR_HOST);
  2089. cli.set_follow_location(true);
  2090. auto res =
  2091. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2092. ASSERT_TRUE(res);
  2093. EXPECT_EQ(StatusCode::OK_200, res->status);
  2094. }
  2095. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2096. SSLClient cli(REDIR_HOST);
  2097. cli.set_follow_location(true);
  2098. Params params;
  2099. params.emplace("url", "http://example.com");
  2100. params.emplace("status_code", "302");
  2101. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. }
  2105. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2106. SSLClient cli(REDIR_HOST);
  2107. cli.set_follow_location(true);
  2108. Params params;
  2109. params.emplace("url", "http://example.com");
  2110. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2111. ASSERT_TRUE(res);
  2112. EXPECT_EQ(StatusCode::OK_200, res->status);
  2113. }
  2114. TEST(UrlWithSpace, Redirect_Online) {
  2115. SSLClient cli("edge.forgecdn.net");
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(StatusCode::OK_200, res->status);
  2120. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2121. }
  2122. #endif
  2123. #if !defined(_WIN32) && !defined(_WIN64)
  2124. TEST(ReceiveSignals, Signal) {
  2125. auto setupSignalHandlers = []() {
  2126. struct sigaction act;
  2127. sigemptyset(&act.sa_mask);
  2128. act.sa_flags = SA_SIGINFO;
  2129. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2130. switch (sig) {
  2131. case SIGINT:
  2132. default: break;
  2133. }
  2134. };
  2135. ::sigaction(SIGINT, &act, nullptr);
  2136. };
  2137. Server svr;
  2138. int port = 0;
  2139. auto thread = std::thread([&]() {
  2140. setupSignalHandlers();
  2141. port = svr.bind_to_any_port(HOST);
  2142. svr.listen_after_bind();
  2143. });
  2144. auto se = detail::scope_exit([&] {
  2145. svr.stop();
  2146. thread.join();
  2147. ASSERT_FALSE(svr.is_running());
  2148. });
  2149. svr.wait_until_ready();
  2150. ASSERT_TRUE(svr.is_running());
  2151. pthread_kill(thread.native_handle(), SIGINT);
  2152. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2153. ASSERT_TRUE(svr.is_running());
  2154. }
  2155. #endif
  2156. TEST(RedirectToDifferentPort, Redirect) {
  2157. Server svr1;
  2158. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2159. res.set_content("Hello World!", "text/plain");
  2160. });
  2161. int svr1_port = 0;
  2162. auto thread1 = std::thread([&]() {
  2163. svr1_port = svr1.bind_to_any_port(HOST);
  2164. svr1.listen_after_bind();
  2165. });
  2166. Server svr2;
  2167. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2168. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2169. });
  2170. int svr2_port = 0;
  2171. auto thread2 = std::thread([&]() {
  2172. svr2_port = svr2.bind_to_any_port(HOST);
  2173. svr2.listen_after_bind();
  2174. });
  2175. auto se = detail::scope_exit([&] {
  2176. svr2.stop();
  2177. thread2.join();
  2178. svr1.stop();
  2179. thread1.join();
  2180. ASSERT_FALSE(svr2.is_running());
  2181. ASSERT_FALSE(svr1.is_running());
  2182. });
  2183. svr1.wait_until_ready();
  2184. svr2.wait_until_ready();
  2185. Client cli("localhost", svr2_port);
  2186. cli.set_follow_location(true);
  2187. auto res = cli.Get("/2");
  2188. ASSERT_TRUE(res);
  2189. EXPECT_EQ(StatusCode::OK_200, res->status);
  2190. EXPECT_EQ("Hello World!", res->body);
  2191. }
  2192. static void
  2193. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2194. Server svr1;
  2195. std::string captured_authorization;
  2196. svr1.Get("/target", [&](const Request &req, Response &res) {
  2197. captured_authorization = req.get_header_value("Authorization");
  2198. res.set_content("OK", "text/plain");
  2199. });
  2200. int svr1_port = 0;
  2201. auto thread1 = std::thread([&]() {
  2202. svr1_port = svr1.bind_to_any_port(HOST);
  2203. svr1.listen_after_bind();
  2204. });
  2205. Server svr2;
  2206. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2207. res.set_redirect(
  2208. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2209. });
  2210. int svr2_port = 0;
  2211. auto thread2 = std::thread([&]() {
  2212. svr2_port = svr2.bind_to_any_port(HOST);
  2213. svr2.listen_after_bind();
  2214. });
  2215. auto se = detail::scope_exit([&] {
  2216. svr2.stop();
  2217. thread2.join();
  2218. svr1.stop();
  2219. thread1.join();
  2220. ASSERT_FALSE(svr2.is_running());
  2221. ASSERT_FALSE(svr1.is_running());
  2222. });
  2223. svr1.wait_until_ready();
  2224. svr2.wait_until_ready();
  2225. Client cli("localhost", svr2_port);
  2226. cli.set_follow_location(true);
  2227. set_auth(cli);
  2228. auto res = cli.Get("/redir");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::OK_200, res->status);
  2231. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2232. EXPECT_TRUE(captured_authorization.empty());
  2233. }
  2234. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2235. TestDoNotForwardCredentialsOnRedirect(
  2236. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2237. }
  2238. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2239. TestDoNotForwardCredentialsOnRedirect(
  2240. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2241. }
  2242. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2243. Server svr;
  2244. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2245. // Port number that overflows int — should not crash
  2246. res.set_redirect("http://localhost:99999999999999999999/target");
  2247. });
  2248. auto port = svr.bind_to_any_port(HOST);
  2249. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. Client cli(HOST, port);
  2257. cli.set_follow_location(true);
  2258. auto res = cli.Get("/redir");
  2259. // Should fail gracefully, not crash (no valid response due to bad port)
  2260. EXPECT_FALSE(res);
  2261. }
  2262. TEST(RedirectFromPageWithContent, Redirect) {
  2263. Server svr;
  2264. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("___", "text/plain");
  2266. res.set_redirect("/2");
  2267. });
  2268. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2269. res.set_content("Hello World!", "text/plain");
  2270. });
  2271. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2272. auto se = detail::scope_exit([&] {
  2273. svr.stop();
  2274. th.join();
  2275. ASSERT_FALSE(svr.is_running());
  2276. });
  2277. svr.wait_until_ready();
  2278. {
  2279. Client cli("localhost", PORT);
  2280. cli.set_follow_location(true);
  2281. std::string body;
  2282. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2283. body.append(data, data_length);
  2284. return true;
  2285. });
  2286. ASSERT_TRUE(res);
  2287. EXPECT_EQ(StatusCode::OK_200, res->status);
  2288. EXPECT_EQ("Hello World!", body);
  2289. }
  2290. {
  2291. Client cli("localhost", PORT);
  2292. std::string body;
  2293. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2294. body.append(data, data_length);
  2295. return true;
  2296. });
  2297. ASSERT_TRUE(res);
  2298. EXPECT_EQ(StatusCode::Found_302, res->status);
  2299. EXPECT_EQ("___", body);
  2300. }
  2301. }
  2302. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2303. Server svr;
  2304. auto port_str = std::to_string(PORT);
  2305. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2306. auto expected_host = "[::1]:" + port_str;
  2307. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("___", "text/plain");
  2309. // res.set_redirect("/2");
  2310. res.set_redirect(redirect_url);
  2311. });
  2312. svr.Get("/2", [&](const Request &req, Response &res) {
  2313. auto host_header = req.headers.find("Host");
  2314. ASSERT_TRUE(host_header != req.headers.end());
  2315. EXPECT_EQ(expected_host, host_header->second);
  2316. res.set_content("Hello World!", "text/plain");
  2317. });
  2318. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2319. auto se = detail::scope_exit([&] {
  2320. svr.stop();
  2321. th.join();
  2322. ASSERT_FALSE(svr.is_running());
  2323. });
  2324. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2325. // actually starts anything, so the condition !svr.is_running() will
  2326. // always remain true, and the loop never stops.
  2327. // This basically counts how many milliseconds have passed since the
  2328. // call to svr.listen(), and if after 5 seconds nothing started yet
  2329. // aborts the test.
  2330. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2331. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2332. ASSERT_LT(milliseconds, 5000U);
  2333. }
  2334. {
  2335. Client cli("::1", PORT);
  2336. cli.set_follow_location(true);
  2337. std::string body;
  2338. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2339. body.append(data, data_length);
  2340. return true;
  2341. });
  2342. ASSERT_TRUE(res);
  2343. EXPECT_EQ(StatusCode::OK_200, res->status);
  2344. EXPECT_EQ("Hello World!", body);
  2345. }
  2346. {
  2347. Client cli("::1", PORT);
  2348. std::string body;
  2349. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2350. body.append(data, data_length);
  2351. return true;
  2352. });
  2353. ASSERT_TRUE(res);
  2354. EXPECT_EQ(StatusCode::Found_302, res->status);
  2355. EXPECT_EQ("___", body);
  2356. }
  2357. }
  2358. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2359. Server svr;
  2360. svr.Get("/foo", [](const Request &req, Response &res) {
  2361. auto a = req.params.find("a");
  2362. if (a != req.params.end()) {
  2363. res.set_content((*a).second, "text/plain");
  2364. res.status = StatusCode::OK_200;
  2365. } else {
  2366. res.status = StatusCode::BadRequest_400;
  2367. }
  2368. });
  2369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2370. auto se = detail::scope_exit([&] {
  2371. svr.stop();
  2372. thread.join();
  2373. ASSERT_FALSE(svr.is_running());
  2374. });
  2375. svr.wait_until_ready();
  2376. {
  2377. Client cli(HOST, PORT);
  2378. cli.set_path_encode(false);
  2379. auto res = cli.Get("/foo?a=explicitly+encoded");
  2380. ASSERT_TRUE(res);
  2381. EXPECT_EQ(StatusCode::OK_200, res->status);
  2382. // This expects it back with a space, as the `+` won't have been
  2383. // url-encoded, and server-side the params get decoded turning `+`
  2384. // into spaces.
  2385. EXPECT_EQ("explicitly encoded", res->body);
  2386. }
  2387. }
  2388. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2389. Server svr;
  2390. svr.Get("/", [](const Request &req, Response &) {
  2391. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2392. });
  2393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2394. auto se = detail::scope_exit([&] {
  2395. svr.stop();
  2396. thread.join();
  2397. ASSERT_FALSE(svr.is_running());
  2398. });
  2399. svr.wait_until_ready();
  2400. {
  2401. Client cli(HOST, PORT);
  2402. cli.set_path_encode(false);
  2403. auto res = cli.Get("/?something=%0A");
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(StatusCode::OK_200, res->status);
  2406. }
  2407. }
  2408. TEST(BindServerTest, BindDualStack) {
  2409. Server svr;
  2410. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. {
  2421. Client cli("127.0.0.1", PORT);
  2422. auto res = cli.Get("/1");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::OK_200, res->status);
  2425. EXPECT_EQ("Hello World!", res->body);
  2426. }
  2427. {
  2428. Client cli("::1", PORT);
  2429. auto res = cli.Get("/1");
  2430. ASSERT_TRUE(res);
  2431. EXPECT_EQ(StatusCode::OK_200, res->status);
  2432. EXPECT_EQ("Hello World!", res->body);
  2433. }
  2434. }
  2435. TEST(BindServerTest, BindAndListenSeparately) {
  2436. Server svr;
  2437. int port = svr.bind_to_any_port("0.0.0.0");
  2438. ASSERT_TRUE(svr.is_valid());
  2439. ASSERT_TRUE(port > 0);
  2440. svr.stop();
  2441. }
  2442. #ifdef CPPHTTPLIB_SSL_ENABLED
  2443. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2445. CLIENT_CA_CERT_DIR);
  2446. int port = svr.bind_to_any_port("0.0.0.0");
  2447. ASSERT_TRUE(svr.is_valid());
  2448. ASSERT_TRUE(port > 0);
  2449. svr.stop();
  2450. }
  2451. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2452. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2453. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2454. int port = svr.bind_to_any_port("0.0.0.0");
  2455. ASSERT_TRUE(svr.is_valid());
  2456. ASSERT_TRUE(port > 0);
  2457. svr.stop();
  2458. }
  2459. TEST(BindServerTest, UpdateCertsPem) {
  2460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2461. int port = svr.bind_to_any_port("0.0.0.0");
  2462. ASSERT_TRUE(svr.is_valid());
  2463. ASSERT_TRUE(port > 0);
  2464. // Read PEM files
  2465. std::string cert_pem, key_pem, ca_pem;
  2466. read_file(SERVER_CERT_FILE, cert_pem);
  2467. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2468. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2469. // Update server certificates using PEM API
  2470. ASSERT_TRUE(
  2471. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2472. ASSERT_TRUE(svr.is_valid());
  2473. svr.stop();
  2474. }
  2475. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2476. // Start server with client CA (enables client auth)
  2477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2478. ASSERT_TRUE(svr.is_valid());
  2479. bool handler_called = false;
  2480. svr.Get("/test", [&](const Request &req, Response &res) {
  2481. handler_called = true;
  2482. // Verify client certificate is present
  2483. auto cert = req.peer_cert();
  2484. EXPECT_TRUE(static_cast<bool>(cert));
  2485. res.set_content("ok", "text/plain");
  2486. });
  2487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. t.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. // Read PEM files
  2495. std::string cert_pem, key_pem, ca_pem;
  2496. read_file(SERVER_CERT_FILE, cert_pem);
  2497. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2498. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2499. // Update server certificates and client CA using PEM API while server running
  2500. ASSERT_TRUE(
  2501. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2502. // Connect with client certificate
  2503. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2504. cli.enable_server_certificate_verification(false);
  2505. cli.set_connection_timeout(30);
  2506. auto res = cli.Get("/test");
  2507. ASSERT_TRUE(res);
  2508. ASSERT_EQ(StatusCode::OK_200, res->status);
  2509. ASSERT_TRUE(handler_called);
  2510. EXPECT_EQ("ok", res->body);
  2511. }
  2512. #endif
  2513. TEST(ErrorHandlerTest, ContentLength) {
  2514. Server svr;
  2515. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2516. res.status = StatusCode::OK_200;
  2517. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2518. "text/html"); // <= Content-Length still 13
  2519. });
  2520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2521. res.set_content("Hello World!\n", "text/plain");
  2522. res.status = 524;
  2523. });
  2524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2525. auto se = detail::scope_exit([&] {
  2526. svr.stop();
  2527. thread.join();
  2528. ASSERT_FALSE(svr.is_running());
  2529. });
  2530. svr.wait_until_ready();
  2531. {
  2532. Client cli(HOST, PORT);
  2533. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2534. ASSERT_TRUE(res);
  2535. EXPECT_EQ(StatusCode::OK_200, res->status);
  2536. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2537. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2538. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2539. }
  2540. }
  2541. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2542. TEST(ExceptionTest, WithoutExceptionHandler) {
  2543. Server svr;
  2544. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2545. throw std::runtime_error("exception...");
  2546. });
  2547. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2548. throw std::runtime_error("exception\r\n...");
  2549. });
  2550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2551. auto se = detail::scope_exit([&] {
  2552. svr.stop();
  2553. listen_thread.join();
  2554. ASSERT_FALSE(svr.is_running());
  2555. });
  2556. svr.wait_until_ready();
  2557. Client cli("localhost", PORT);
  2558. {
  2559. auto res = cli.Get("/exception");
  2560. ASSERT_TRUE(res);
  2561. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2562. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2563. }
  2564. {
  2565. auto res = cli.Get("/unknown");
  2566. ASSERT_TRUE(res);
  2567. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2568. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2569. }
  2570. }
  2571. TEST(ExceptionTest, WithExceptionHandler) {
  2572. Server svr;
  2573. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2574. std::exception_ptr ep) {
  2575. EXPECT_FALSE(ep == nullptr);
  2576. try {
  2577. std::rethrow_exception(ep);
  2578. } catch (std::exception &e) {
  2579. EXPECT_EQ("abc", std::string(e.what()));
  2580. } catch (...) {}
  2581. res.status = StatusCode::InternalServerError_500;
  2582. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2583. "text/html"); // <= Content-Length still 13 at this point
  2584. });
  2585. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2586. res.set_content("Hello World!\n", "text/plain");
  2587. throw std::runtime_error("abc");
  2588. });
  2589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2590. auto se = detail::scope_exit([&] {
  2591. svr.stop();
  2592. thread.join();
  2593. ASSERT_FALSE(svr.is_running());
  2594. });
  2595. svr.wait_until_ready();
  2596. for (size_t i = 0; i < 10; i++) {
  2597. Client cli(HOST, PORT);
  2598. for (size_t j = 0; j < 100; j++) {
  2599. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2600. ASSERT_TRUE(res);
  2601. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2602. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2603. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2604. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2605. }
  2606. cli.set_keep_alive(true);
  2607. for (size_t j = 0; j < 100; j++) {
  2608. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2611. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2612. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2613. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2614. }
  2615. }
  2616. }
  2617. TEST(ExceptionTest, AndErrorHandler) {
  2618. Server svr;
  2619. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2620. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2621. });
  2622. svr.set_exception_handler(
  2623. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2624. EXPECT_FALSE(ep == nullptr);
  2625. try {
  2626. std::rethrow_exception(ep);
  2627. } catch (std::exception &e) {
  2628. res.set_content(e.what(), "text/html");
  2629. } catch (...) {}
  2630. res.status = StatusCode::InternalServerError_500;
  2631. });
  2632. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2633. throw std::runtime_error("EXCEPTION");
  2634. });
  2635. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2636. res.set_content("ERROR", "text/html");
  2637. res.status = StatusCode::InternalServerError_500;
  2638. });
  2639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2640. auto se = detail::scope_exit([&] {
  2641. svr.stop();
  2642. thread.join();
  2643. ASSERT_FALSE(svr.is_running());
  2644. });
  2645. svr.wait_until_ready();
  2646. Client cli(HOST, PORT);
  2647. {
  2648. auto res = cli.Get("/exception");
  2649. ASSERT_TRUE(res);
  2650. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2651. EXPECT_EQ("EXCEPTION", res->body);
  2652. }
  2653. {
  2654. auto res = cli.Get("/error");
  2655. ASSERT_TRUE(res);
  2656. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2657. EXPECT_EQ("ERROR", res->body);
  2658. }
  2659. {
  2660. auto res = cli.Get("/invalid");
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2663. EXPECT_EQ("NOT_FOUND", res->body);
  2664. }
  2665. }
  2666. #endif
  2667. TEST(NoContentTest, ContentLength) {
  2668. Server svr;
  2669. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2670. res.status = StatusCode::NoContent_204;
  2671. });
  2672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2673. auto se = detail::scope_exit([&] {
  2674. svr.stop();
  2675. thread.join();
  2676. ASSERT_FALSE(svr.is_running());
  2677. });
  2678. svr.wait_until_ready();
  2679. {
  2680. Client cli(HOST, PORT);
  2681. auto res = cli.Get("/hi");
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2684. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2685. }
  2686. }
  2687. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2688. #ifdef CPPHTTPLIB_SSL_ENABLED
  2689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2690. ASSERT_TRUE(svr.is_valid());
  2691. #else
  2692. Server svr;
  2693. #endif
  2694. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2695. if (req.path == "/routing_handler") {
  2696. res.set_header("PRE_ROUTING", "on");
  2697. res.set_content("Routing Handler", "text/plain");
  2698. return httplib::Server::HandlerResponse::Handled;
  2699. }
  2700. return httplib::Server::HandlerResponse::Unhandled;
  2701. });
  2702. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2703. res.set_content("Error", "text/html");
  2704. });
  2705. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2706. if (req.path == "/routing_handler") {
  2707. res.set_header("POST_ROUTING", "on");
  2708. }
  2709. });
  2710. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!\n", "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. {
  2721. #ifdef CPPHTTPLIB_SSL_ENABLED
  2722. SSLClient cli(HOST, PORT);
  2723. cli.enable_server_certificate_verification(false);
  2724. #else
  2725. Client cli(HOST, PORT);
  2726. #endif
  2727. auto res = cli.Get("/routing_handler");
  2728. ASSERT_TRUE(res);
  2729. EXPECT_EQ(StatusCode::OK_200, res->status);
  2730. EXPECT_EQ("Routing Handler", res->body);
  2731. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2732. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2733. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2734. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2735. }
  2736. {
  2737. #ifdef CPPHTTPLIB_SSL_ENABLED
  2738. SSLClient cli(HOST, PORT);
  2739. cli.enable_server_certificate_verification(false);
  2740. #else
  2741. Client cli(HOST, PORT);
  2742. #endif
  2743. auto res = cli.Get("/hi");
  2744. ASSERT_TRUE(res);
  2745. EXPECT_EQ(StatusCode::OK_200, res->status);
  2746. EXPECT_EQ("Hello World!\n", res->body);
  2747. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2748. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2749. }
  2750. {
  2751. #ifdef CPPHTTPLIB_SSL_ENABLED
  2752. SSLClient cli(HOST, PORT);
  2753. cli.enable_server_certificate_verification(false);
  2754. #else
  2755. Client cli(HOST, PORT);
  2756. #endif
  2757. auto res = cli.Get("/aaa");
  2758. ASSERT_TRUE(res);
  2759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2760. EXPECT_EQ("Error", res->body);
  2761. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2762. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2763. }
  2764. }
  2765. TEST(RequestHandlerTest, PreRequestHandler) {
  2766. auto route_path = "/user/:user";
  2767. Server svr;
  2768. svr.Get("/hi", [](const Request &, Response &res) {
  2769. res.set_content("hi", "text/plain");
  2770. });
  2771. svr.Get(route_path, [](const Request &req, Response &res) {
  2772. res.set_content(req.path_params.at("user"), "text/plain");
  2773. });
  2774. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2775. if (req.matched_route == route_path) {
  2776. auto user = req.path_params.at("user");
  2777. if (user != "john") {
  2778. res.status = StatusCode::Forbidden_403;
  2779. res.set_content("error", "text/html");
  2780. return Server::HandlerResponse::Handled;
  2781. }
  2782. }
  2783. return Server::HandlerResponse::Unhandled;
  2784. });
  2785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2786. auto se = detail::scope_exit([&] {
  2787. svr.stop();
  2788. thread.join();
  2789. ASSERT_FALSE(svr.is_running());
  2790. });
  2791. svr.wait_until_ready();
  2792. Client cli(HOST, PORT);
  2793. {
  2794. auto res = cli.Get("/hi");
  2795. ASSERT_TRUE(res);
  2796. EXPECT_EQ(StatusCode::OK_200, res->status);
  2797. EXPECT_EQ("hi", res->body);
  2798. }
  2799. {
  2800. auto res = cli.Get("/user/john");
  2801. ASSERT_TRUE(res);
  2802. EXPECT_EQ(StatusCode::OK_200, res->status);
  2803. EXPECT_EQ("john", res->body);
  2804. }
  2805. {
  2806. auto res = cli.Get("/user/invalid-user");
  2807. ASSERT_TRUE(res);
  2808. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2809. EXPECT_EQ("error", res->body);
  2810. }
  2811. }
  2812. // The pre-request handler must run before the request body is read, so a
  2813. // rejected request never forces the server to buffer a (potentially large)
  2814. // body. Here the posted body is larger than the payload limit: if the body
  2815. // were read first the server would answer 413, but because the pre-request
  2816. // handler runs first it answers 403 and the body is never read.
  2817. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2818. Server svr;
  2819. svr.set_payload_max_length(8);
  2820. auto handler_ran = false;
  2821. svr.Post("/reject", [&](const Request &req, Response &res) {
  2822. handler_ran = true;
  2823. res.set_content(req.body, "text/plain");
  2824. });
  2825. svr.Post("/accept", [](const Request &req, Response &res) {
  2826. res.set_content(req.body, "text/plain");
  2827. });
  2828. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2829. if (req.matched_route == "/reject") {
  2830. res.status = StatusCode::Forbidden_403;
  2831. res.set_content("denied", "text/plain");
  2832. return Server::HandlerResponse::Handled;
  2833. }
  2834. return Server::HandlerResponse::Unhandled;
  2835. });
  2836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. thread.join();
  2840. ASSERT_FALSE(svr.is_running());
  2841. });
  2842. svr.wait_until_ready();
  2843. Client cli(HOST, PORT);
  2844. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2845. // rejects with 403 before the body is read, so 413 is never reached.
  2846. {
  2847. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2848. ASSERT_TRUE(res);
  2849. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2850. EXPECT_EQ("denied", res->body);
  2851. EXPECT_FALSE(handler_ran);
  2852. }
  2853. // An approved route still reads the body and enforces the payload limit.
  2854. {
  2855. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2856. ASSERT_TRUE(res);
  2857. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2858. }
  2859. }
  2860. TEST(UserDataTest, BasicOperations) {
  2861. httplib::UserData ud;
  2862. // Initially empty
  2863. EXPECT_FALSE(ud.has("key"));
  2864. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2865. // set and get
  2866. ud.set("key", 42);
  2867. EXPECT_TRUE(ud.has("key"));
  2868. auto *p = ud.get<int>("key");
  2869. ASSERT_NE(nullptr, p);
  2870. EXPECT_EQ(42, *p);
  2871. // Type mismatch → nullptr
  2872. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2873. // Overwrite with different type
  2874. ud.set("key", std::string("hello"));
  2875. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2876. auto *s = ud.get<std::string>("key");
  2877. ASSERT_NE(nullptr, s);
  2878. EXPECT_EQ("hello", *s);
  2879. // erase
  2880. ud.erase("key");
  2881. EXPECT_FALSE(ud.has("key"));
  2882. // clear
  2883. ud.set("a", 1);
  2884. ud.set("b", 2);
  2885. ud.clear();
  2886. EXPECT_FALSE(ud.has("a"));
  2887. EXPECT_FALSE(ud.has("b"));
  2888. }
  2889. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2890. struct AuthCtx {
  2891. std::string user_id;
  2892. };
  2893. Server svr;
  2894. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2895. res.user_data.set("auth", AuthCtx{"alice"});
  2896. return Server::HandlerResponse::Unhandled;
  2897. });
  2898. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2899. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2900. ASSERT_NE(nullptr, ctx);
  2901. res.set_content("Hello " + ctx->user_id, "text/plain");
  2902. });
  2903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2904. auto se = detail::scope_exit([&] {
  2905. svr.stop();
  2906. thread.join();
  2907. ASSERT_FALSE(svr.is_running());
  2908. });
  2909. svr.wait_until_ready();
  2910. Client cli(HOST, PORT);
  2911. auto res = cli.Get("/me");
  2912. ASSERT_TRUE(res);
  2913. EXPECT_EQ(StatusCode::OK_200, res->status);
  2914. EXPECT_EQ("Hello alice", res->body);
  2915. }
  2916. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2917. struct RoleCtx {
  2918. std::string role;
  2919. };
  2920. Server svr;
  2921. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2922. res.user_data.set("role", RoleCtx{"admin"});
  2923. return Server::HandlerResponse::Unhandled;
  2924. });
  2925. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2926. auto *ctx = res.user_data.get<RoleCtx>("role");
  2927. ASSERT_NE(nullptr, ctx);
  2928. res.set_content(ctx->role, "text/plain");
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. auto res = cli.Get("/role");
  2939. ASSERT_TRUE(res);
  2940. EXPECT_EQ(StatusCode::OK_200, res->status);
  2941. EXPECT_EQ("admin", res->body);
  2942. }
  2943. TEST(InvalidFormatTest, StatusCode) {
  2944. Server svr;
  2945. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2946. res.set_content("Hello World!\n", "text/plain");
  2947. res.status = 9999; // Status should be a three-digit code...
  2948. });
  2949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2950. auto se = detail::scope_exit([&] {
  2951. svr.stop();
  2952. thread.join();
  2953. ASSERT_FALSE(svr.is_running());
  2954. });
  2955. svr.wait_until_ready();
  2956. {
  2957. Client cli(HOST, PORT);
  2958. auto res = cli.Get("/hi");
  2959. ASSERT_FALSE(res);
  2960. }
  2961. }
  2962. TEST(URLFragmentTest, WithFragment) {
  2963. Server svr;
  2964. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2965. EXPECT_TRUE(req.target == "/hi");
  2966. });
  2967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2968. auto se = detail::scope_exit([&] {
  2969. svr.stop();
  2970. thread.join();
  2971. ASSERT_FALSE(svr.is_running());
  2972. });
  2973. svr.wait_until_ready();
  2974. {
  2975. Client cli(HOST, PORT);
  2976. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2977. EXPECT_TRUE(res);
  2978. EXPECT_EQ(StatusCode::OK_200, res->status);
  2979. res = cli.Get("/hi%23key1=val1=key2=val2");
  2980. EXPECT_TRUE(res);
  2981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2982. }
  2983. }
  2984. TEST(HeaderWriter, SetHeaderWriter) {
  2985. Server svr;
  2986. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2987. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2988. return detail::write_headers(strm, hdrs);
  2989. });
  2990. svr.Get("/hi", [](const Request &req, Response &res) {
  2991. auto it = req.headers.find("CustomClientHeader");
  2992. EXPECT_TRUE(it != req.headers.end());
  2993. EXPECT_EQ(it->second, "CustomClientValue");
  2994. res.set_content("Hello World!\n", "text/plain");
  2995. });
  2996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. {
  3004. Client cli(HOST, PORT);
  3005. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3006. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3007. return detail::write_headers(strm, hdrs);
  3008. });
  3009. auto res = cli.Get("/hi");
  3010. EXPECT_TRUE(res);
  3011. EXPECT_EQ(StatusCode::OK_200, res->status);
  3012. auto it = res->headers.find("CustomServerHeader");
  3013. EXPECT_TRUE(it != res->headers.end());
  3014. EXPECT_EQ(it->second, "CustomServerValue");
  3015. }
  3016. }
  3017. class ServerTest : public ::testing::Test {
  3018. protected:
  3019. ServerTest()
  3020. : cli_(HOST, PORT)
  3021. #ifdef CPPHTTPLIB_SSL_ENABLED
  3022. ,
  3023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3024. #endif
  3025. {
  3026. #ifdef CPPHTTPLIB_SSL_ENABLED
  3027. cli_.enable_server_certificate_verification(false);
  3028. #endif
  3029. // Allow LARGE_DATA (100MB) responses
  3030. cli_.set_payload_max_length(200 * 1024 * 1024);
  3031. }
  3032. virtual void SetUp() {
  3033. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3034. svr_.set_payload_max_length(200 * 1024 * 1024);
  3035. svr_.set_mount_point("/", "./www");
  3036. svr_.set_mount_point("/mount", "./www2");
  3037. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3038. svr_.Get("/hi",
  3039. [&](const Request & /*req*/, Response &res) {
  3040. res.set_content("Hello World!", "text/plain");
  3041. })
  3042. .Get("/file_content",
  3043. [&](const Request & /*req*/, Response &res) {
  3044. res.set_file_content("./www/dir/test.html");
  3045. })
  3046. .Get("/file_content_with_content_type",
  3047. [&](const Request & /*req*/, Response &res) {
  3048. res.set_file_content("./www/file", "text/plain");
  3049. })
  3050. .Get("/invalid_file_content",
  3051. [&](const Request & /*req*/, Response &res) {
  3052. res.set_file_content("./www/dir/invalid_file_path");
  3053. })
  3054. .Get("/http_response_splitting",
  3055. [&](const Request & /*req*/, Response &res) {
  3056. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3057. EXPECT_EQ(0U, res.headers.size());
  3058. EXPECT_FALSE(res.has_header("a"));
  3059. res.set_header("a", "1\nSet-Cookie: a=1");
  3060. EXPECT_EQ(0U, res.headers.size());
  3061. EXPECT_FALSE(res.has_header("a"));
  3062. res.set_header("a", "1\rSet-Cookie: a=1");
  3063. EXPECT_EQ(0U, res.headers.size());
  3064. EXPECT_FALSE(res.has_header("a"));
  3065. res.set_header("a\r\nb", "0");
  3066. EXPECT_EQ(0U, res.headers.size());
  3067. EXPECT_FALSE(res.has_header("a"));
  3068. res.set_header("a\rb", "0");
  3069. EXPECT_EQ(0U, res.headers.size());
  3070. EXPECT_FALSE(res.has_header("a"));
  3071. res.set_header("a\nb", "0");
  3072. EXPECT_EQ(0U, res.headers.size());
  3073. EXPECT_FALSE(res.has_header("a"));
  3074. res.set_redirect("1\r\nSet-Cookie: a=1");
  3075. EXPECT_EQ(0U, res.headers.size());
  3076. EXPECT_FALSE(res.has_header("Location"));
  3077. })
  3078. .Get("/slow",
  3079. [&](const Request & /*req*/, Response &res) {
  3080. std::this_thread::sleep_for(std::chrono::seconds(4));
  3081. res.set_content("slow", "text/plain");
  3082. })
  3083. #if 0
  3084. .Post("/slowpost",
  3085. [&](const Request & /*req*/, Response &res) {
  3086. std::this_thread::sleep_for(std::chrono::seconds(2));
  3087. res.set_content("slow", "text/plain");
  3088. })
  3089. #endif
  3090. .Get("/remote_addr",
  3091. [&](const Request &req, Response &res) {
  3092. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3093. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3094. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3095. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3096. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3097. #endif
  3098. res.set_content(req.remote_addr, "text/plain");
  3099. })
  3100. .Get("/local_addr",
  3101. [&](const Request &req, Response &res) {
  3102. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3103. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3104. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3105. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3106. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3107. #endif
  3108. auto local_addr = req.local_addr;
  3109. auto local_port = std::to_string(req.local_port);
  3110. res.set_content(local_addr.append(":").append(local_port),
  3111. "text/plain");
  3112. })
  3113. .Get("/endwith%",
  3114. [&](const Request & /*req*/, Response &res) {
  3115. res.set_content("Hello World!", "text/plain");
  3116. })
  3117. .Get("/a\\+\\+b",
  3118. [&](const Request &req, Response &res) {
  3119. ASSERT_TRUE(req.has_param("a +b"));
  3120. auto val = req.get_param_value("a +b");
  3121. res.set_content(val, "text/plain");
  3122. })
  3123. .Get("/", [&](const Request & /*req*/,
  3124. Response &res) { res.set_redirect("/hi"); })
  3125. .Post("/1",
  3126. [](const Request & /*req*/, Response &res) {
  3127. res.set_redirect("/2", StatusCode::SeeOther_303);
  3128. })
  3129. .Get("/2",
  3130. [](const Request & /*req*/, Response &res) {
  3131. res.set_content("redirected.", "text/plain");
  3132. res.status = StatusCode::OK_200;
  3133. })
  3134. .Post("/person",
  3135. [&](const Request &req, Response &res) {
  3136. if (req.has_param("name") && req.has_param("note")) {
  3137. persons_[req.get_param_value("name")] =
  3138. req.get_param_value("note");
  3139. } else {
  3140. res.status = StatusCode::BadRequest_400;
  3141. }
  3142. })
  3143. .Put("/person",
  3144. [&](const Request &req, Response &res) {
  3145. if (req.has_param("name") && req.has_param("note")) {
  3146. persons_[req.get_param_value("name")] =
  3147. req.get_param_value("note");
  3148. } else {
  3149. res.status = StatusCode::BadRequest_400;
  3150. }
  3151. })
  3152. .Get("/person/(.*)",
  3153. [&](const Request &req, Response &res) {
  3154. string name = req.matches[1];
  3155. if (persons_.find(name) != persons_.end()) {
  3156. auto note = persons_[name];
  3157. res.set_content(note, "text/plain");
  3158. } else {
  3159. res.status = StatusCode::NotFound_404;
  3160. }
  3161. })
  3162. .Delete("/person",
  3163. [&](const Request &req, Response &res) {
  3164. if (req.has_param("name")) {
  3165. string name = req.get_param_value("name");
  3166. if (persons_.find(name) != persons_.end()) {
  3167. persons_.erase(name);
  3168. res.set_content("DELETED", "text/plain");
  3169. } else {
  3170. res.status = StatusCode::NotFound_404;
  3171. }
  3172. } else {
  3173. res.status = StatusCode::BadRequest_400;
  3174. }
  3175. })
  3176. .Post("/x-www-form-urlencoded-json",
  3177. [&](const Request &req, Response &res) {
  3178. auto json = req.get_param_value("json");
  3179. ASSERT_EQ(JSON_DATA, json);
  3180. res.set_content(json, "appliation/json");
  3181. res.status = StatusCode::OK_200;
  3182. })
  3183. .Get("/streamed-chunked",
  3184. [&](const Request & /*req*/, Response &res) {
  3185. res.set_chunked_content_provider(
  3186. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3187. sink.os << "123";
  3188. sink.os << "456";
  3189. sink.os << "789";
  3190. sink.done();
  3191. return true;
  3192. });
  3193. })
  3194. .Get("/streamed-chunked-with-prohibited-trailer",
  3195. [&](const Request & /*req*/, Response &res) {
  3196. auto i = new int(0);
  3197. // Declare both a prohibited trailer (Content-Length) and an
  3198. // allowed one
  3199. res.set_header("Trailer", "Content-Length, X-Allowed");
  3200. res.set_chunked_content_provider(
  3201. "text/plain",
  3202. [i](size_t /*offset*/, DataSink &sink) {
  3203. switch (*i) {
  3204. case 0: sink.os << "123"; break;
  3205. case 1: sink.os << "456"; break;
  3206. case 2: sink.os << "789"; break;
  3207. case 3: {
  3208. sink.done_with_trailer(
  3209. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3210. } break;
  3211. }
  3212. (*i)++;
  3213. return true;
  3214. },
  3215. [i](bool success) {
  3216. EXPECT_TRUE(success);
  3217. delete i;
  3218. });
  3219. })
  3220. .Get("/streamed-chunked2",
  3221. [&](const Request & /*req*/, Response &res) {
  3222. auto i = new int(0);
  3223. res.set_chunked_content_provider(
  3224. "text/plain",
  3225. [i](size_t /*offset*/, DataSink &sink) {
  3226. switch (*i) {
  3227. case 0: sink.os << "123"; break;
  3228. case 1: sink.os << "456"; break;
  3229. case 2: sink.os << "789"; break;
  3230. case 3: sink.done(); break;
  3231. }
  3232. (*i)++;
  3233. return true;
  3234. },
  3235. [i](bool success) {
  3236. EXPECT_TRUE(success);
  3237. delete i;
  3238. });
  3239. })
  3240. .Get("/streamed-chunked-with-trailer",
  3241. [&](const Request & /*req*/, Response &res) {
  3242. auto i = new int(0);
  3243. res.set_header("Trailer", "Dummy1, Dummy2");
  3244. res.set_chunked_content_provider(
  3245. "text/plain",
  3246. [i](size_t /*offset*/, DataSink &sink) {
  3247. switch (*i) {
  3248. case 0: sink.os << "123"; break;
  3249. case 1: sink.os << "456"; break;
  3250. case 2: sink.os << "789"; break;
  3251. case 3: {
  3252. sink.done_with_trailer(
  3253. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3254. } break;
  3255. }
  3256. (*i)++;
  3257. return true;
  3258. },
  3259. [i](bool success) {
  3260. EXPECT_TRUE(success);
  3261. delete i;
  3262. });
  3263. })
  3264. .Get("/streamed",
  3265. [&](const Request & /*req*/, Response &res) {
  3266. res.set_content_provider(
  3267. 6, "text/plain",
  3268. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3269. sink.os << (offset < 3 ? "a" : "b");
  3270. return true;
  3271. });
  3272. })
  3273. .Get("/streamed-without-length",
  3274. [&](const Request & /*req*/, Response &res) {
  3275. auto data = new std::string("abcdefg");
  3276. res.set_content_provider(
  3277. "text/plain",
  3278. [data](size_t offset, DataSink &sink) {
  3279. if (offset < data->size()) {
  3280. sink.os << data->substr(offset);
  3281. }
  3282. sink.done();
  3283. return true;
  3284. },
  3285. [data](bool success) {
  3286. EXPECT_TRUE(success);
  3287. delete data;
  3288. });
  3289. })
  3290. .Get("/streamed-with-range",
  3291. [&](const Request &req, Response &res) {
  3292. auto data = new std::string("abcdefg");
  3293. res.set_content_provider(
  3294. data->size(), "text/plain",
  3295. [data](size_t offset, size_t length, DataSink &sink) {
  3296. size_t DATA_CHUNK_SIZE = 4;
  3297. const auto &d = *data;
  3298. auto out_len =
  3299. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3300. auto ret =
  3301. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3302. EXPECT_TRUE(ret);
  3303. return true;
  3304. },
  3305. [data, &req](bool success) {
  3306. EXPECT_EQ(success, !req.has_param("error"));
  3307. delete data;
  3308. });
  3309. })
  3310. .Get("/streamed-cancel",
  3311. [&](const Request & /*req*/, Response &res) {
  3312. res.set_content_provider(
  3313. size_t(-1), "text/plain",
  3314. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3315. sink.os << "data_chunk";
  3316. return true;
  3317. });
  3318. })
  3319. .Get("/regex-with-delimiter",
  3320. [&](const Request &req, Response & /*res*/) {
  3321. ASSERT_TRUE(req.has_param("key"));
  3322. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3323. })
  3324. .Get("/with-range",
  3325. [&](const Request & /*req*/, Response &res) {
  3326. res.set_content("abcdefg", "text/plain");
  3327. })
  3328. .Get("/test-start-time",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_NE(req.start_time_,
  3331. std::chrono::steady_clock::time_point::min());
  3332. })
  3333. .Get("/with-range-customized-response",
  3334. [&](const Request & /*req*/, Response &res) {
  3335. res.status = StatusCode::BadRequest_400;
  3336. res.set_content(JSON_DATA, "application/json");
  3337. })
  3338. .Post("/chunked",
  3339. [&](const Request &req, Response & /*res*/) {
  3340. EXPECT_EQ(req.body, "dechunked post body");
  3341. })
  3342. .Post("/large-chunked",
  3343. [&](const Request &req, Response & /*res*/) {
  3344. std::string expected(6 * 30 * 1024u, 'a');
  3345. EXPECT_EQ(req.body, expected);
  3346. })
  3347. .Post("/multipart",
  3348. [&](const Request &req, Response & /*res*/) {
  3349. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3350. req.form.get_field_count("text2") +
  3351. req.form.get_field_count("file3") +
  3352. req.form.get_field_count("file4"));
  3353. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3354. req.form.get_file_count("file2"));
  3355. ASSERT_TRUE(!req.form.has_file("???"));
  3356. ASSERT_TRUE(!req.form.has_field("???"));
  3357. ASSERT_TRUE(req.body.empty());
  3358. {
  3359. const auto &text = req.form.get_field("text1");
  3360. EXPECT_EQ("text default", text);
  3361. }
  3362. {
  3363. const auto &text = req.form.get_field("text2");
  3364. EXPECT_EQ("aωb", text);
  3365. }
  3366. {
  3367. const auto &file = req.form.get_file("file1");
  3368. EXPECT_EQ("hello.txt", file.filename);
  3369. EXPECT_EQ("text/plain", file.content_type);
  3370. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3371. }
  3372. {
  3373. const auto &file = req.form.get_file("file2");
  3374. EXPECT_EQ("world.json", file.filename);
  3375. EXPECT_EQ("application/json", file.content_type);
  3376. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3377. }
  3378. {
  3379. const auto &text = req.form.get_field("file3");
  3380. EXPECT_EQ(0u, text.size());
  3381. }
  3382. {
  3383. const auto &text = req.form.get_field("file4");
  3384. EXPECT_EQ(0u, text.size());
  3385. }
  3386. })
  3387. .Post("/multipart/multi_file_values",
  3388. [&](const Request &req, Response & /*res*/) {
  3389. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3390. req.form.get_field_count("multi_text1"));
  3391. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3392. ASSERT_TRUE(!req.form.has_file("???"));
  3393. ASSERT_TRUE(!req.form.has_field("???"));
  3394. ASSERT_TRUE(req.body.empty());
  3395. {
  3396. const auto &text = req.form.get_field("text");
  3397. EXPECT_EQ("default text", text);
  3398. }
  3399. {
  3400. const auto &text1_values = req.form.get_fields("multi_text1");
  3401. EXPECT_EQ(2u, text1_values.size());
  3402. EXPECT_EQ("aaaaa", text1_values[0]);
  3403. EXPECT_EQ("bbbbb", text1_values[1]);
  3404. }
  3405. {
  3406. const auto &file1_values = req.form.get_files("multi_file1");
  3407. EXPECT_EQ(2u, file1_values.size());
  3408. auto file1 = file1_values[0];
  3409. EXPECT_EQ(file1.filename, "hello.txt");
  3410. EXPECT_EQ(file1.content_type, "text/plain");
  3411. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3412. auto file2 = file1_values[1];
  3413. EXPECT_EQ(file2.filename, "world.json");
  3414. EXPECT_EQ(file2.content_type, "application/json");
  3415. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3416. }
  3417. })
  3418. .Post("/empty",
  3419. [&](const Request &req, Response &res) {
  3420. EXPECT_EQ(req.body, "");
  3421. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3422. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3423. res.set_content("empty", "text/plain");
  3424. })
  3425. .Post("/empty-no-content-type",
  3426. [&](const Request &req, Response &res) {
  3427. EXPECT_EQ(req.body, "");
  3428. EXPECT_FALSE(req.has_header("Content-Type"));
  3429. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3430. res.set_content("empty-no-content-type", "text/plain");
  3431. })
  3432. .Post("/path-only",
  3433. [&](const Request &req, Response &res) {
  3434. EXPECT_EQ(req.body, "");
  3435. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3436. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3437. res.set_content("path-only", "text/plain");
  3438. })
  3439. .Post("/path-headers-only",
  3440. [&](const Request &req, Response &res) {
  3441. EXPECT_EQ(req.body, "");
  3442. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3443. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3444. EXPECT_EQ("world", req.get_header_value("hello"));
  3445. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3446. res.set_content("path-headers-only", "text/plain");
  3447. })
  3448. .Post("/post-large",
  3449. [&](const Request &req, Response &res) {
  3450. EXPECT_EQ(req.body, LARGE_DATA);
  3451. res.set_content(req.body, "text/plain");
  3452. })
  3453. .Post("/post-loopback",
  3454. [&](const Request &, Response &res,
  3455. ContentReader const &content_reader) {
  3456. std::string body;
  3457. content_reader([&](const char *data, size_t data_length) {
  3458. body.append(data, data_length);
  3459. return true;
  3460. });
  3461. res.set_content(body, "text/plain");
  3462. })
  3463. .Put("/put-loopback",
  3464. [&](const Request &, Response &res,
  3465. ContentReader const &content_reader) {
  3466. std::string body;
  3467. content_reader([&](const char *data, size_t data_length) {
  3468. body.append(data, data_length);
  3469. return true;
  3470. });
  3471. res.set_content(body, "text/plain");
  3472. })
  3473. .Patch("/patch-loopback",
  3474. [&](const Request &, Response &res,
  3475. ContentReader const &content_reader) {
  3476. std::string body;
  3477. content_reader([&](const char *data, size_t data_length) {
  3478. body.append(data, data_length);
  3479. return true;
  3480. });
  3481. res.set_content(body, "text/plain");
  3482. })
  3483. .Put("/empty-no-content-type",
  3484. [&](const Request &req, Response &res) {
  3485. EXPECT_EQ(req.body, "");
  3486. EXPECT_FALSE(req.has_header("Content-Type"));
  3487. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3488. res.set_content("empty-no-content-type", "text/plain");
  3489. })
  3490. .Put("/put",
  3491. [&](const Request &req, Response &res) {
  3492. EXPECT_EQ(req.body, "PUT");
  3493. res.set_content(req.body, "text/plain");
  3494. })
  3495. .Put("/put-large",
  3496. [&](const Request &req, Response &res) {
  3497. EXPECT_EQ(req.body, LARGE_DATA);
  3498. res.set_content(req.body, "text/plain");
  3499. })
  3500. .Patch("/patch",
  3501. [&](const Request &req, Response &res) {
  3502. EXPECT_EQ(req.body, "PATCH");
  3503. res.set_content(req.body, "text/plain");
  3504. })
  3505. .Delete("/delete",
  3506. [&](const Request & /*req*/, Response &res) {
  3507. res.set_content("DELETE", "text/plain");
  3508. })
  3509. .Delete("/delete-body",
  3510. [&](const Request &req, Response &res) {
  3511. EXPECT_EQ(req.body, "content");
  3512. res.set_content(req.body, "text/plain");
  3513. })
  3514. .Options(R"(\*)",
  3515. [&](const Request & /*req*/, Response &res) {
  3516. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3517. })
  3518. .Get("/request-target",
  3519. [&](const Request &req, Response & /*res*/) {
  3520. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3521. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3522. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3523. })
  3524. .Get("/long-query-value",
  3525. [&](const Request &req, Response & /*res*/) {
  3526. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3527. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3528. })
  3529. .Get("/too-long-query-value",
  3530. [&](const Request &req, Response & /*res*/) {
  3531. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3532. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3533. })
  3534. .Get("/array-param",
  3535. [&](const Request &req, Response & /*res*/) {
  3536. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3537. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3538. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3539. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3540. })
  3541. .Get("/array-param-values",
  3542. [&](const Request &req, Response & /*res*/) {
  3543. auto values = req.get_param_values("array");
  3544. EXPECT_EQ(3u, values.size());
  3545. EXPECT_EQ("value1", values[0]);
  3546. EXPECT_EQ("value2", values[1]);
  3547. EXPECT_EQ("value3", values[2]);
  3548. auto empty = req.get_param_values("nonexistent");
  3549. EXPECT_TRUE(empty.empty());
  3550. })
  3551. .Post("/validate-no-multiple-headers",
  3552. [&](const Request &req, Response & /*res*/) {
  3553. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3554. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3555. })
  3556. .Post("/content_receiver",
  3557. [&](const Request &req, Response &res,
  3558. const ContentReader &content_reader) {
  3559. if (req.is_multipart_form_data()) {
  3560. std::vector<FormData> items;
  3561. content_reader(
  3562. [&](const FormData &file) {
  3563. items.push_back(file);
  3564. return true;
  3565. },
  3566. [&](const char *data, size_t data_length) {
  3567. items.back().content.append(data, data_length);
  3568. return true;
  3569. });
  3570. EXPECT_EQ(5u, items.size());
  3571. {
  3572. const auto &file = get_file_value(items, "text1");
  3573. EXPECT_TRUE(file.filename.empty());
  3574. EXPECT_EQ("text default", file.content);
  3575. }
  3576. {
  3577. const auto &file = get_file_value(items, "text2");
  3578. EXPECT_TRUE(file.filename.empty());
  3579. EXPECT_EQ("aωb", file.content);
  3580. }
  3581. {
  3582. const auto &file = get_file_value(items, "file1");
  3583. EXPECT_EQ("hello.txt", file.filename);
  3584. EXPECT_EQ("text/plain", file.content_type);
  3585. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3586. }
  3587. {
  3588. const auto &file = get_file_value(items, "file2");
  3589. EXPECT_EQ("world.json", file.filename);
  3590. EXPECT_EQ("application/json", file.content_type);
  3591. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3592. }
  3593. {
  3594. const auto &file = get_file_value(items, "file3");
  3595. EXPECT_TRUE(file.filename.empty());
  3596. EXPECT_EQ("application/octet-stream", file.content_type);
  3597. EXPECT_EQ(0u, file.content.size());
  3598. }
  3599. } else {
  3600. std::string body;
  3601. content_reader([&](const char *data, size_t data_length) {
  3602. EXPECT_EQ(7U, data_length);
  3603. body.append(data, data_length);
  3604. return true;
  3605. });
  3606. EXPECT_EQ(body, "content");
  3607. res.set_content(body, "text/plain");
  3608. }
  3609. })
  3610. .Put("/content_receiver",
  3611. [&](const Request & /*req*/, Response &res,
  3612. const ContentReader &content_reader) {
  3613. std::string body;
  3614. content_reader([&](const char *data, size_t data_length) {
  3615. body.append(data, data_length);
  3616. return true;
  3617. });
  3618. EXPECT_EQ(body, "content");
  3619. res.set_content(body, "text/plain");
  3620. })
  3621. .Patch("/content_receiver",
  3622. [&](const Request & /*req*/, Response &res,
  3623. const ContentReader &content_reader) {
  3624. std::string body;
  3625. content_reader([&](const char *data, size_t data_length) {
  3626. body.append(data, data_length);
  3627. return true;
  3628. });
  3629. EXPECT_EQ(body, "content");
  3630. res.set_content(body, "text/plain");
  3631. })
  3632. .Post("/query-string-and-body",
  3633. [&](const Request &req, Response & /*res*/) {
  3634. ASSERT_TRUE(req.has_param("key"));
  3635. EXPECT_EQ(req.get_param_value("key"), "value");
  3636. EXPECT_EQ(req.body, "content");
  3637. })
  3638. .Get("/last-request",
  3639. [&](const Request &req, Response & /*res*/) {
  3640. EXPECT_EQ("close", req.get_header_value("Connection"));
  3641. })
  3642. .Get(R"(/redirect/(\d+))",
  3643. [&](const Request &req, Response &res) {
  3644. auto num = std::stoi(req.matches[1]) + 1;
  3645. std::string url = "/redirect/" + std::to_string(num);
  3646. res.set_redirect(url);
  3647. })
  3648. .Post("/binary",
  3649. [&](const Request &req, Response &res) {
  3650. EXPECT_EQ(4U, req.body.size());
  3651. EXPECT_EQ("application/octet-stream",
  3652. req.get_header_value("Content-Type"));
  3653. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3654. res.set_content(req.body, "application/octet-stream");
  3655. })
  3656. .Put("/binary",
  3657. [&](const Request &req, Response &res) {
  3658. EXPECT_EQ(4U, req.body.size());
  3659. EXPECT_EQ("application/octet-stream",
  3660. req.get_header_value("Content-Type"));
  3661. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3662. res.set_content(req.body, "application/octet-stream");
  3663. })
  3664. .Patch("/binary",
  3665. [&](const Request &req, Response &res) {
  3666. EXPECT_EQ(4U, req.body.size());
  3667. EXPECT_EQ("application/octet-stream",
  3668. req.get_header_value("Content-Type"));
  3669. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3670. res.set_content(req.body, "application/octet-stream");
  3671. })
  3672. .Delete("/binary",
  3673. [&](const Request &req, Response &res) {
  3674. EXPECT_EQ(4U, req.body.size());
  3675. EXPECT_EQ("application/octet-stream",
  3676. req.get_header_value("Content-Type"));
  3677. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3678. res.set_content(req.body, "application/octet-stream");
  3679. })
  3680. .Get("/issue1772",
  3681. [&](const Request & /*req*/, Response &res) {
  3682. res.status = 401;
  3683. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3684. })
  3685. .Delete("/issue609",
  3686. [](const httplib::Request &, httplib::Response &res,
  3687. const httplib::ContentReader &) {
  3688. res.set_content("ok", "text/plain");
  3689. })
  3690. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3691. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3692. .Get("/compress",
  3693. [&](const Request & /*req*/, Response &res) {
  3694. res.set_content(
  3695. "12345678901234567890123456789012345678901234567890123456789"
  3696. "01234567890123456789012345678901234567890",
  3697. "text/plain");
  3698. })
  3699. .Get("/compress-with-charset",
  3700. [&](const Request & /*req*/, Response &res) {
  3701. res.set_content(
  3702. "12345678901234567890123456789012345678901234567890123456789"
  3703. "01234567890123456789012345678901234567890",
  3704. "application/json; charset=utf-8");
  3705. })
  3706. .Get("/nocompress",
  3707. [&](const Request & /*req*/, Response &res) {
  3708. res.set_content(
  3709. "12345678901234567890123456789012345678901234567890123456789"
  3710. "01234567890123456789012345678901234567890",
  3711. "application/octet-stream");
  3712. })
  3713. .Post("/compress-multipart",
  3714. [&](const Request &req, Response & /*res*/) {
  3715. EXPECT_EQ(2u, req.form.fields.size());
  3716. ASSERT_TRUE(!req.form.has_field("???"));
  3717. {
  3718. const auto &text = req.form.get_field("key1");
  3719. EXPECT_EQ("test", text);
  3720. }
  3721. {
  3722. const auto &text = req.form.get_field("key2");
  3723. EXPECT_EQ("--abcdefg123", text);
  3724. }
  3725. })
  3726. #endif
  3727. ;
  3728. persons_["john"] = "programmer";
  3729. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3730. svr_.wait_until_ready();
  3731. }
  3732. virtual void TearDown() {
  3733. svr_.stop();
  3734. if (!request_threads_.empty()) {
  3735. std::this_thread::sleep_for(std::chrono::seconds(1));
  3736. for (auto &t : request_threads_) {
  3737. t.join();
  3738. }
  3739. }
  3740. t_.join();
  3741. }
  3742. map<string, string> persons_;
  3743. #ifdef CPPHTTPLIB_SSL_ENABLED
  3744. SSLClient cli_;
  3745. SSLServer svr_;
  3746. #else
  3747. Client cli_;
  3748. Server svr_;
  3749. #endif
  3750. thread t_;
  3751. std::vector<thread> request_threads_;
  3752. };
  3753. TEST_F(ServerTest, GetMethod200) {
  3754. auto res = cli_.Get("/hi");
  3755. ASSERT_TRUE(res);
  3756. EXPECT_EQ("HTTP/1.1", res->version);
  3757. EXPECT_EQ(StatusCode::OK_200, res->status);
  3758. EXPECT_EQ("OK", res->reason);
  3759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3761. EXPECT_EQ("Hello World!", res->body);
  3762. }
  3763. TEST_F(ServerTest, GetEmptyFile) {
  3764. auto res = cli_.Get("/empty_file");
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3768. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3769. EXPECT_EQ("", res->body);
  3770. }
  3771. TEST_F(ServerTest, GetFileContent) {
  3772. auto res = cli_.Get("/file_content");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::OK_200, res->status);
  3775. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3776. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3777. EXPECT_EQ("test.html", res->body);
  3778. }
  3779. TEST_F(ServerTest, GetFileContentWithRange) {
  3780. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3781. ASSERT_TRUE(res);
  3782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3783. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3784. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3785. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3786. EXPECT_EQ("est", res->body);
  3787. }
  3788. TEST_F(ServerTest, GetFileContentWithContentType) {
  3789. auto res = cli_.Get("/file_content_with_content_type");
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3793. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3794. EXPECT_EQ("file\n", res->body);
  3795. }
  3796. TEST_F(ServerTest, GetInvalidFileContent) {
  3797. auto res = cli_.Get("/invalid_file_content");
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3800. }
  3801. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3802. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ("HTTP/1.1", res->version);
  3805. EXPECT_EQ(StatusCode::OK_200, res->status);
  3806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3807. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3808. EXPECT_EQ("Hello World!", res->body);
  3809. }
  3810. TEST_F(ServerTest, GetMethod302) {
  3811. auto res = cli_.Get("/");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::Found_302, res->status);
  3814. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3815. }
  3816. TEST_F(ServerTest, GetMethod302Redirect) {
  3817. cli_.set_follow_location(true);
  3818. auto res = cli_.Get("/");
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. EXPECT_EQ("Hello World!", res->body);
  3822. EXPECT_EQ("/hi", res->location);
  3823. }
  3824. TEST_F(ServerTest, GetMethod404) {
  3825. auto res = cli_.Get("/invalid");
  3826. ASSERT_TRUE(res);
  3827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3828. }
  3829. TEST_F(ServerTest, HeadMethod200) {
  3830. auto res = cli_.Head("/hi");
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3834. EXPECT_TRUE(res->body.empty());
  3835. }
  3836. TEST_F(ServerTest, HeadMethod200Static) {
  3837. auto res = cli_.Head("/mount/dir/index.html");
  3838. ASSERT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3841. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3842. EXPECT_TRUE(res->body.empty());
  3843. }
  3844. TEST_F(ServerTest, HeadMethod404) {
  3845. auto res = cli_.Head("/invalid");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3848. EXPECT_TRUE(res->body.empty());
  3849. }
  3850. TEST_F(ServerTest, GetMethodPersonJohn) {
  3851. auto res = cli_.Get("/person/john");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::OK_200, res->status);
  3854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3855. EXPECT_EQ("programmer", res->body);
  3856. }
  3857. TEST_F(ServerTest, PostMethod1) {
  3858. auto res = cli_.Get("/person/john1");
  3859. ASSERT_TRUE(res);
  3860. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3861. res = cli_.Post("/person", "name=john1&note=coder",
  3862. "application/x-www-form-urlencoded");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. res = cli_.Get("/person/john1");
  3866. ASSERT_TRUE(res);
  3867. ASSERT_EQ(StatusCode::OK_200, res->status);
  3868. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3869. ASSERT_EQ("coder", res->body);
  3870. }
  3871. TEST_F(ServerTest, PostMethod2) {
  3872. auto res = cli_.Get("/person/john2");
  3873. ASSERT_TRUE(res);
  3874. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3875. Params params;
  3876. params.emplace("name", "john2");
  3877. params.emplace("note", "coder");
  3878. res = cli_.Post("/person", params);
  3879. ASSERT_TRUE(res);
  3880. ASSERT_EQ(StatusCode::OK_200, res->status);
  3881. res = cli_.Get("/person/john2");
  3882. ASSERT_TRUE(res);
  3883. ASSERT_EQ(StatusCode::OK_200, res->status);
  3884. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3885. ASSERT_EQ("coder", res->body);
  3886. }
  3887. TEST_F(ServerTest, PutMethod3) {
  3888. auto res = cli_.Get("/person/john3");
  3889. ASSERT_TRUE(res);
  3890. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3891. Params params;
  3892. params.emplace("name", "john3");
  3893. params.emplace("note", "coder");
  3894. res = cli_.Put("/person", params);
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. res = cli_.Get("/person/john3");
  3898. ASSERT_TRUE(res);
  3899. ASSERT_EQ(StatusCode::OK_200, res->status);
  3900. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3901. ASSERT_EQ("coder", res->body);
  3902. }
  3903. TEST_F(ServerTest, DeleteMethod1) {
  3904. auto res = cli_.Get("/person/john4");
  3905. ASSERT_TRUE(res);
  3906. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3907. Params params;
  3908. params.emplace("name", "john4");
  3909. params.emplace("note", "coder");
  3910. res = cli_.Post("/person", params);
  3911. ASSERT_TRUE(res);
  3912. ASSERT_EQ(StatusCode::OK_200, res->status);
  3913. res = cli_.Get("/person/john4");
  3914. ASSERT_TRUE(res);
  3915. ASSERT_EQ(StatusCode::OK_200, res->status);
  3916. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3917. ASSERT_EQ("coder", res->body);
  3918. Params delete_params;
  3919. delete_params.emplace("name", "john4");
  3920. res = cli_.Delete("/person", delete_params);
  3921. ASSERT_TRUE(res);
  3922. ASSERT_EQ(StatusCode::OK_200, res->status);
  3923. ASSERT_EQ("DELETED", res->body);
  3924. res = cli_.Get("/person/john4");
  3925. ASSERT_TRUE(res);
  3926. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3927. }
  3928. TEST_F(ServerTest, DeleteMethod2) {
  3929. auto res = cli_.Get("/person/john5");
  3930. ASSERT_TRUE(res);
  3931. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3932. Params params;
  3933. params.emplace("name", "john5");
  3934. params.emplace("note", "developer");
  3935. res = cli_.Post("/person", params);
  3936. ASSERT_TRUE(res);
  3937. ASSERT_EQ(StatusCode::OK_200, res->status);
  3938. res = cli_.Get("/person/john5");
  3939. ASSERT_TRUE(res);
  3940. ASSERT_EQ(StatusCode::OK_200, res->status);
  3941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3942. ASSERT_EQ("developer", res->body);
  3943. Params delete_params;
  3944. delete_params.emplace("name", "john5");
  3945. Headers headers;
  3946. headers.emplace("Custom-Header", "test-value");
  3947. res = cli_.Delete("/person", headers, delete_params);
  3948. ASSERT_TRUE(res);
  3949. ASSERT_EQ(StatusCode::OK_200, res->status);
  3950. ASSERT_EQ("DELETED", res->body);
  3951. res = cli_.Get("/person/john5");
  3952. ASSERT_TRUE(res);
  3953. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3954. }
  3955. TEST_F(ServerTest, DeleteMethod3) {
  3956. auto res = cli_.Get("/person/john6");
  3957. ASSERT_TRUE(res);
  3958. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3959. Params params;
  3960. params.emplace("name", "john6");
  3961. params.emplace("note", "tester");
  3962. res = cli_.Post("/person", params);
  3963. ASSERT_TRUE(res);
  3964. ASSERT_EQ(StatusCode::OK_200, res->status);
  3965. res = cli_.Get("/person/john6");
  3966. ASSERT_TRUE(res);
  3967. ASSERT_EQ(StatusCode::OK_200, res->status);
  3968. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3969. ASSERT_EQ("tester", res->body);
  3970. Params delete_params;
  3971. delete_params.emplace("name", "john6");
  3972. Headers headers;
  3973. headers.emplace("Custom-Header", "test-value");
  3974. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3975. ASSERT_TRUE(res);
  3976. ASSERT_EQ(StatusCode::OK_200, res->status);
  3977. ASSERT_EQ("DELETED", res->body);
  3978. res = cli_.Get("/person/john6");
  3979. ASSERT_TRUE(res);
  3980. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3981. }
  3982. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3983. Params params;
  3984. params.emplace("json", JSON_DATA);
  3985. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3986. ASSERT_TRUE(res);
  3987. ASSERT_EQ(StatusCode::OK_200, res->status);
  3988. ASSERT_EQ(JSON_DATA, res->body);
  3989. }
  3990. TEST_F(ServerTest, PostEmptyContent) {
  3991. auto res = cli_.Post("/empty", "", "text/plain");
  3992. ASSERT_TRUE(res);
  3993. ASSERT_EQ(StatusCode::OK_200, res->status);
  3994. ASSERT_EQ("empty", res->body);
  3995. }
  3996. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3997. auto res = cli_.Post("/empty-no-content-type");
  3998. ASSERT_TRUE(res);
  3999. ASSERT_EQ(StatusCode::OK_200, res->status);
  4000. ASSERT_EQ("empty-no-content-type", res->body);
  4001. }
  4002. TEST_F(ServerTest, PostPathOnly) {
  4003. auto res = cli_.Post("/path-only");
  4004. ASSERT_TRUE(res);
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_EQ("path-only", res->body);
  4007. }
  4008. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4009. auto res = cli_.Post("/path-headers-only",
  4010. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4011. ASSERT_TRUE(res);
  4012. ASSERT_EQ(StatusCode::OK_200, res->status);
  4013. ASSERT_EQ("path-headers-only", res->body);
  4014. }
  4015. TEST_F(ServerTest, PostLarge) {
  4016. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. EXPECT_EQ(LARGE_DATA, res->body);
  4020. }
  4021. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4022. auto res = cli_.Put("/empty-no-content-type");
  4023. ASSERT_TRUE(res);
  4024. ASSERT_EQ(StatusCode::OK_200, res->status);
  4025. ASSERT_EQ("empty-no-content-type", res->body);
  4026. }
  4027. TEST_F(ServerTest, GetMethodDir) {
  4028. auto res = cli_.Get("/dir/");
  4029. ASSERT_TRUE(res);
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4032. auto body = R"(<html>
  4033. <head>
  4034. </head>
  4035. <body>
  4036. <a href="/dir/test.html">Test</a>
  4037. <a href="/hi">hi</a>
  4038. </body>
  4039. </html>
  4040. )";
  4041. EXPECT_EQ(body, res->body);
  4042. }
  4043. TEST_F(ServerTest, GetMethodDirTest) {
  4044. auto res = cli_.Get("/dir/test.html");
  4045. ASSERT_TRUE(res);
  4046. EXPECT_EQ(StatusCode::OK_200, res->status);
  4047. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4048. EXPECT_EQ("test.html", res->body);
  4049. }
  4050. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4051. auto res = cli_.Get("/dir/../dir/test.html");
  4052. ASSERT_TRUE(res);
  4053. EXPECT_EQ(StatusCode::OK_200, res->status);
  4054. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4055. EXPECT_EQ("test.html", res->body);
  4056. }
  4057. TEST_F(ServerTest, GetMethodInvalidPath) {
  4058. auto res = cli_.Get("/dir/../test.html");
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4061. }
  4062. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4063. auto res = cli_.Get("/../www/dir/test.html");
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4066. }
  4067. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4068. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4071. }
  4072. TEST_F(ServerTest, GetMethodDirMountTest) {
  4073. auto res = cli_.Get("/mount/dir/test.html");
  4074. ASSERT_TRUE(res);
  4075. EXPECT_EQ(StatusCode::OK_200, res->status);
  4076. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4077. EXPECT_EQ("test.html", res->body);
  4078. }
  4079. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4080. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::OK_200, res->status);
  4083. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4084. EXPECT_EQ("test.html", res->body);
  4085. }
  4086. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4087. auto res = cli_.Get("/mount/dir/../test.html");
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4090. }
  4091. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4092. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4093. ASSERT_TRUE(res);
  4094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4095. }
  4096. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4097. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4100. }
  4101. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4102. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4105. }
  4106. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4107. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4110. }
  4111. TEST_F(ServerTest, PostMethod303) {
  4112. auto res = cli_.Post("/1", "body", "text/plain");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4115. EXPECT_EQ("/2", res->get_header_value("Location"));
  4116. }
  4117. TEST_F(ServerTest, PostMethod303Redirect) {
  4118. cli_.set_follow_location(true);
  4119. auto res = cli_.Post("/1", "body", "text/plain");
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::OK_200, res->status);
  4122. EXPECT_EQ("redirected.", res->body);
  4123. EXPECT_EQ("/2", res->location);
  4124. }
  4125. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4126. auto res = cli_.Get("/dir/test.abcde");
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4130. EXPECT_EQ("abcde", res->body);
  4131. }
  4132. TEST_F(ServerTest, StaticFileRange) {
  4133. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4134. ASSERT_TRUE(res);
  4135. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4136. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4137. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ(true, res->has_header("Content-Range"));
  4139. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4140. EXPECT_EQ(std::string("cd"), res->body);
  4141. }
  4142. TEST_F(ServerTest, StaticFileRanges) {
  4143. auto res =
  4144. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4147. EXPECT_TRUE(
  4148. res->get_header_value("Content-Type")
  4149. .find(
  4150. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4151. 0);
  4152. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4153. }
  4154. TEST_F(ServerTest, StaticFileRangeHead) {
  4155. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4158. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4159. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4160. EXPECT_EQ(true, res->has_header("Content-Range"));
  4161. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4162. }
  4163. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4164. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4168. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4169. EXPECT_EQ(true, res->has_header("Content-Range"));
  4170. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4171. res->get_header_value("Content-Range"));
  4172. EXPECT_EQ("LAST\n", res->body);
  4173. }
  4174. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4175. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4179. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4180. EXPECT_EQ(true, res->has_header("Content-Range"));
  4181. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4182. }
  4183. TEST_F(ServerTest, StaticFileBigFile) {
  4184. auto res = cli_.Get("/dir/1MB.txt");
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4188. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4189. }
  4190. TEST_F(ServerTest, InvalidBaseDirMount) {
  4191. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4192. }
  4193. TEST_F(ServerTest, Binary) {
  4194. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4195. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4196. "application/octet-stream");
  4197. ASSERT_TRUE(res);
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ(4U, res->body.size());
  4200. res = cli_.Put("/binary", binary.data(), binary.size(),
  4201. "application/octet-stream");
  4202. ASSERT_TRUE(res);
  4203. ASSERT_EQ(StatusCode::OK_200, res->status);
  4204. ASSERT_EQ(4U, res->body.size());
  4205. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4206. "application/octet-stream");
  4207. ASSERT_TRUE(res);
  4208. ASSERT_EQ(StatusCode::OK_200, res->status);
  4209. ASSERT_EQ(4U, res->body.size());
  4210. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4211. "application/octet-stream");
  4212. ASSERT_TRUE(res);
  4213. ASSERT_EQ(StatusCode::OK_200, res->status);
  4214. ASSERT_EQ(4U, res->body.size());
  4215. }
  4216. TEST_F(ServerTest, BinaryString) {
  4217. auto binary = std::string("\x00\x01\x02\x03", 4);
  4218. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4219. ASSERT_TRUE(res);
  4220. ASSERT_EQ(StatusCode::OK_200, res->status);
  4221. ASSERT_EQ(4U, res->body.size());
  4222. res = cli_.Put("/binary", binary, "application/octet-stream");
  4223. ASSERT_TRUE(res);
  4224. ASSERT_EQ(StatusCode::OK_200, res->status);
  4225. ASSERT_EQ(4U, res->body.size());
  4226. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4227. ASSERT_TRUE(res);
  4228. ASSERT_EQ(StatusCode::OK_200, res->status);
  4229. ASSERT_EQ(4U, res->body.size());
  4230. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4231. ASSERT_TRUE(res);
  4232. ASSERT_EQ(StatusCode::OK_200, res->status);
  4233. ASSERT_EQ(4U, res->body.size());
  4234. }
  4235. TEST_F(ServerTest, EmptyRequest) {
  4236. auto res = cli_.Get("");
  4237. ASSERT_TRUE(!res);
  4238. EXPECT_EQ(Error::Connection, res.error());
  4239. }
  4240. TEST_F(ServerTest, LongRequest) {
  4241. std::string request;
  4242. for (size_t i = 0; i < 545; i++) {
  4243. request += "/TooLongRequest";
  4244. }
  4245. request += "OK";
  4246. auto res = cli_.Get(request.c_str());
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4249. }
  4250. TEST_F(ServerTest, TooLongRequest) {
  4251. std::string request;
  4252. for (size_t i = 0; i < 546; i++) {
  4253. request += "/TooLongRequest";
  4254. }
  4255. request += "_NG";
  4256. auto start = std::chrono::high_resolution_clock::now();
  4257. cli_.set_keep_alive(true);
  4258. auto res = cli_.Get(request.c_str());
  4259. auto end = std::chrono::high_resolution_clock::now();
  4260. auto elapsed =
  4261. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4262. .count();
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4265. EXPECT_LE(elapsed, 1000);
  4266. EXPECT_EQ("close", res->get_header_value("Connection"));
  4267. EXPECT_FALSE(cli_.is_socket_open());
  4268. }
  4269. TEST_F(ServerTest, AlmostTooLongRequest) {
  4270. // test for #2046 - URI length check shouldn't include other content on req
  4271. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4272. // leading /, space, HTTP/1.1)
  4273. std::string request =
  4274. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4275. auto res = cli_.Get(request.c_str());
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4278. }
  4279. TEST_F(ServerTest, LongHeader) {
  4280. Request req;
  4281. req.method = "GET";
  4282. req.path = "/hi";
  4283. std::string host_and_port;
  4284. host_and_port += HOST;
  4285. host_and_port += ":";
  4286. host_and_port += std::to_string(PORT);
  4287. req.headers.emplace("Host", host_and_port.c_str());
  4288. req.headers.emplace("Accept", "*/*");
  4289. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4290. req.headers.emplace(
  4291. "Header-Name",
  4292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  4322. auto error = Error::Success;
  4323. auto ret = cli_.send(req, *res, error);
  4324. ASSERT_TRUE(ret);
  4325. EXPECT_EQ(StatusCode::OK_200, res->status);
  4326. }
  4327. TEST_F(ServerTest, LongQueryValue) {
  4328. auto start = std::chrono::high_resolution_clock::now();
  4329. cli_.set_keep_alive(true);
  4330. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4331. auto end = std::chrono::high_resolution_clock::now();
  4332. auto elapsed =
  4333. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4334. .count();
  4335. ASSERT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4337. EXPECT_LE(elapsed, 1000);
  4338. EXPECT_EQ("close", res->get_header_value("Connection"));
  4339. EXPECT_FALSE(cli_.is_socket_open());
  4340. }
  4341. TEST_F(ServerTest, TooLongQueryValue) {
  4342. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4343. ASSERT_FALSE(res);
  4344. EXPECT_EQ(Error::Read, res.error());
  4345. }
  4346. TEST_F(ServerTest, TooLongHeader) {
  4347. Request req;
  4348. req.method = "GET";
  4349. req.path = "/hi";
  4350. std::string host_and_port;
  4351. host_and_port += HOST;
  4352. host_and_port += ":";
  4353. host_and_port += std::to_string(PORT);
  4354. req.headers.emplace("Host", host_and_port.c_str());
  4355. req.headers.emplace("Accept", "*/*");
  4356. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4357. req.headers.emplace(
  4358. "Header-Name",
  4359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  4389. auto error = Error::Success;
  4390. auto ret = cli_.send(req, *res, error);
  4391. ASSERT_TRUE(ret);
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. }
  4394. TEST_F(ServerTest, HeaderCountAtLimit) {
  4395. // Test with headers just under the 100 limit
  4396. httplib::Headers headers;
  4397. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4398. // This should keep us just under the 100 header limit
  4399. for (int i = 0; i < 95; i++) {
  4400. std::string name = "X-Test-Header-" + std::to_string(i);
  4401. std::string value = "value" + std::to_string(i);
  4402. headers.emplace(name, value);
  4403. }
  4404. // This should work fine as we're under the limit
  4405. auto res = cli_.Get("/hi", headers);
  4406. EXPECT_TRUE(res);
  4407. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4408. }
  4409. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4410. // Test with many headers to exceed the 100 limit
  4411. httplib::Headers headers;
  4412. // Add 150 headers to definitely exceed the 100 limit
  4413. for (int i = 0; i < 150; i++) {
  4414. std::string name = "X-Test-Header-" + std::to_string(i);
  4415. std::string value = "value" + std::to_string(i);
  4416. headers.emplace(name, value);
  4417. }
  4418. // This should fail due to exceeding header count limit
  4419. cli_.set_keep_alive(true);
  4420. auto res = cli_.Get("/hi", headers);
  4421. // The server should respond with 400 Bad Request
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4424. EXPECT_EQ("close", res->get_header_value("Connection"));
  4425. EXPECT_FALSE(cli_.is_socket_open());
  4426. }
  4427. TEST_F(ServerTest, PercentEncoding) {
  4428. auto res = cli_.Get("/e%6edwith%");
  4429. ASSERT_TRUE(res);
  4430. EXPECT_EQ(StatusCode::OK_200, res->status);
  4431. }
  4432. TEST_F(ServerTest, PercentEncodingUnicode) {
  4433. auto res = cli_.Get("/e%u006edwith%");
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. }
  4437. TEST_F(ServerTest, InvalidPercentEncoding) {
  4438. auto res = cli_.Get("/%endwith%");
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4441. }
  4442. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4443. auto res = cli_.Get("/%uendwith%");
  4444. ASSERT_TRUE(res);
  4445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4446. }
  4447. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4448. auto res = cli_.Get("/hello?aaa=bbb%");
  4449. ASSERT_TRUE(res);
  4450. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4451. }
  4452. TEST_F(ServerTest, PlusSignEncoding) {
  4453. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::OK_200, res->status);
  4456. EXPECT_EQ("a +b", res->body);
  4457. }
  4458. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4459. // This test simulates a potential DoS attack using many headers
  4460. // to verify our security fix prevents memory exhaustion
  4461. httplib::Headers attack_headers;
  4462. // Attempt to add many headers like an attacker would (200 headers to far
  4463. // exceed limit)
  4464. for (int i = 0; i < 200; i++) {
  4465. std::string name = "X-Attack-Header-" + std::to_string(i);
  4466. std::string value = "attack_payload_" + std::to_string(i);
  4467. attack_headers.emplace(name, value);
  4468. }
  4469. // Try to POST with excessive headers
  4470. cli_.set_keep_alive(true);
  4471. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4472. // Should either fail or return 400 Bad Request due to security limit
  4473. if (res) {
  4474. // If we get a response, it should be 400 Bad Request
  4475. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4476. EXPECT_EQ("close", res->get_header_value("Connection"));
  4477. }
  4478. EXPECT_FALSE(cli_.is_socket_open());
  4479. }
  4480. TEST_F(ServerTest, MultipartFormData) {
  4481. UploadFormDataItems items = {
  4482. {"text1", "text default", "", ""},
  4483. {"text2", "aωb", "", ""},
  4484. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4485. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4486. {"file3", "", "", "application/octet-stream"},
  4487. {"file4", "", "", " application/json tmp-string "}};
  4488. auto res = cli_.Post("/multipart", items);
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. }
  4492. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4493. UploadFormDataItems items = {
  4494. {"text", "default text", "", ""},
  4495. {"multi_text1", "aaaaa", "", ""},
  4496. {"multi_text1", "bbbbb", "", ""},
  4497. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4498. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4499. "application/json"},
  4500. };
  4501. auto res = cli_.Post("/multipart/multi_file_values", items);
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::OK_200, res->status);
  4504. }
  4505. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4506. auto res = cli_.Get("/hi");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4510. EXPECT_EQ("Hello World!", res->body);
  4511. }
  4512. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4513. Request req;
  4514. req.method = "POST";
  4515. req.path = "/chunked";
  4516. std::string host_and_port;
  4517. host_and_port += HOST;
  4518. host_and_port += ":";
  4519. host_and_port += std::to_string(PORT);
  4520. req.headers.emplace("Host", host_and_port.c_str());
  4521. req.headers.emplace("Accept", "*/*");
  4522. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4523. req.headers.emplace("Content-Type", "text/plain");
  4524. req.headers.emplace("Content-Length", "0");
  4525. req.headers.emplace(
  4526. "Transfer-Encoding",
  4527. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4528. // Client does not chunk, so make a chunked body manually.
  4529. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4530. auto res = std::make_shared<Response>();
  4531. auto error = Error::Success;
  4532. auto ret = cli_.send(req, *res, error);
  4533. ASSERT_TRUE(ret);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. }
  4536. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4537. // rather than treat them as valid lengths.
  4538. template <typename ClientT>
  4539. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4540. Request req;
  4541. req.method = "POST";
  4542. req.path = "/chunked";
  4543. std::string host_and_port;
  4544. host_and_port += HOST;
  4545. host_and_port += ":";
  4546. host_and_port += std::to_string(PORT);
  4547. req.headers.emplace("Host", host_and_port.c_str());
  4548. req.headers.emplace("Content-Length", "0");
  4549. req.headers.emplace("Transfer-Encoding", "chunked");
  4550. req.body = body;
  4551. auto res = std::make_shared<Response>();
  4552. auto error = Error::Success;
  4553. ASSERT_TRUE(cli.send(req, *res, error));
  4554. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4555. }
  4556. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4557. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4558. }
  4559. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4560. expect_chunked_body_rejected(
  4561. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4562. }
  4563. TEST_F(ServerTest, GetStreamed2) {
  4564. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4567. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4568. EXPECT_EQ(true, res->has_header("Content-Range"));
  4569. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4570. EXPECT_EQ(std::string("ab"), res->body);
  4571. }
  4572. TEST_F(ServerTest, GetStreamed) {
  4573. auto res = cli_.Get("/streamed");
  4574. ASSERT_TRUE(res);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4577. EXPECT_EQ(std::string("aaabbb"), res->body);
  4578. }
  4579. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4580. auto res =
  4581. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ(false, res->has_header("Content-Length"));
  4585. EXPECT_EQ(false, res->has_header("Content-Range"));
  4586. EXPECT_EQ(std::string("abcdefg"), res->body);
  4587. }
  4588. TEST_F(ServerTest, GetStreamedWithRange1) {
  4589. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4592. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4593. EXPECT_EQ(true, res->has_header("Content-Range"));
  4594. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4595. EXPECT_EQ(std::string("def"), res->body);
  4596. }
  4597. TEST_F(ServerTest, GetStreamedWithRange2) {
  4598. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4599. ASSERT_TRUE(res);
  4600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4601. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4602. EXPECT_EQ(true, res->has_header("Content-Range"));
  4603. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4604. EXPECT_EQ(std::string("bcdefg"), res->body);
  4605. }
  4606. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4607. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4610. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4611. EXPECT_EQ(true, res->has_header("Content-Range"));
  4612. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4613. EXPECT_EQ(std::string("efg"), res->body);
  4614. }
  4615. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4616. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4620. EXPECT_EQ(false, res->has_header("Content-Range"));
  4621. EXPECT_EQ(0U, res->body.size());
  4622. }
  4623. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4624. auto res = cli_.Get("/streamed-with-range",
  4625. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4626. "92233720368547758079223372036854775807"}});
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4629. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4630. EXPECT_EQ(false, res->has_header("Content-Range"));
  4631. EXPECT_EQ(0U, res->body.size());
  4632. }
  4633. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4634. auto res = cli_.Get(
  4635. "/with-range",
  4636. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4637. {"Accept-Encoding", ""}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4640. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4641. EXPECT_EQ(true, res->has_header("Content-Range"));
  4642. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4643. EXPECT_EQ(std::string("abcdefg"), res->body);
  4644. }
  4645. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4646. auto res = cli_.Get("/with-range", {
  4647. {"Range", "bytes=0-"},
  4648. {"Accept-Encoding", ""},
  4649. });
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4652. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4653. EXPECT_EQ(true, res->has_header("Content-Range"));
  4654. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4655. EXPECT_EQ(std::string("abcdefg"), res->body);
  4656. }
  4657. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4658. auto res =
  4659. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4660. ASSERT_TRUE(res);
  4661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4662. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4663. EXPECT_EQ(false, res->has_header("Content-Range"));
  4664. EXPECT_EQ(267U, res->body.size());
  4665. // Check that both range contents are present
  4666. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4667. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4668. // Check that Content-Range headers are present for both ranges
  4669. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4670. std::string::npos);
  4671. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4672. std::string::npos);
  4673. }
  4674. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4675. Ranges ranges;
  4676. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4677. ranges.emplace_back(0, -1);
  4678. }
  4679. auto res =
  4680. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4681. ASSERT_TRUE(res);
  4682. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4683. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4684. EXPECT_EQ(false, res->has_header("Content-Range"));
  4685. EXPECT_EQ(0U, res->body.size());
  4686. }
  4687. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4688. auto res =
  4689. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4692. EXPECT_EQ(5U, res->body.size());
  4693. // Check that overlapping ranges are coalesced into a single range
  4694. EXPECT_EQ("bcdef", res->body);
  4695. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4696. // Should be single range, not multipart
  4697. EXPECT_TRUE(res->has_header("Content-Range"));
  4698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4699. }
  4700. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4701. auto res =
  4702. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4705. EXPECT_EQ(268U, res->body.size());
  4706. // Check that both range contents are present
  4707. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4708. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4709. // Check that Content-Range headers are present for both ranges
  4710. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4711. std::string::npos);
  4712. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4713. std::string::npos);
  4714. }
  4715. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4716. auto res =
  4717. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_EQ(269U, res->body.size());
  4721. // Check that both duplicate range contents are present
  4722. size_t first_abc = res->body.find("abc\r\n");
  4723. EXPECT_TRUE(first_abc != std::string::npos);
  4724. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4725. EXPECT_TRUE(second_abc != std::string::npos);
  4726. // Check that Content-Range headers are present for both ranges
  4727. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4728. EXPECT_TRUE(first_range != std::string::npos);
  4729. size_t second_range =
  4730. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4731. EXPECT_TRUE(second_range != std::string::npos);
  4732. }
  4733. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4734. auto res = cli_.Get("/streamed-with-range?error",
  4735. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4738. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4739. EXPECT_EQ(false, res->has_header("Content-Range"));
  4740. EXPECT_EQ(0U, res->body.size());
  4741. }
  4742. TEST_F(ServerTest, GetStreamedEndless) {
  4743. uint64_t offset = 0;
  4744. auto res = cli_.Get("/streamed-cancel",
  4745. [&](const char * /*data*/, uint64_t data_length) {
  4746. if (offset < 100) {
  4747. offset += data_length;
  4748. return true;
  4749. }
  4750. return false;
  4751. });
  4752. ASSERT_TRUE(!res);
  4753. EXPECT_EQ(Error::Canceled, res.error());
  4754. }
  4755. TEST_F(ServerTest, ClientStop) {
  4756. std::atomic_size_t count{4};
  4757. std::vector<std::thread> threads;
  4758. for (auto i = count.load(); i != 0; --i) {
  4759. threads.emplace_back([&]() {
  4760. auto res = cli_.Get("/streamed-cancel",
  4761. [&](const char *, uint64_t) { return true; });
  4762. --count;
  4763. ASSERT_TRUE(!res);
  4764. EXPECT_TRUE(res.error() == Error::Canceled ||
  4765. res.error() == Error::Read || res.error() == Error::Write);
  4766. });
  4767. }
  4768. std::this_thread::sleep_for(std::chrono::seconds(2));
  4769. while (count != 0) {
  4770. cli_.stop();
  4771. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4772. }
  4773. for (auto &t : threads) {
  4774. t.join();
  4775. }
  4776. }
  4777. TEST_F(ServerTest, GetWithRange1) {
  4778. auto res = cli_.Get("/with-range", {
  4779. make_range_header({{3, 5}}),
  4780. {"Accept-Encoding", ""},
  4781. });
  4782. ASSERT_TRUE(res);
  4783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4784. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4785. EXPECT_EQ(true, res->has_header("Content-Range"));
  4786. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4787. EXPECT_EQ(std::string("def"), res->body);
  4788. }
  4789. TEST_F(ServerTest, GetWithRange2) {
  4790. auto res = cli_.Get("/with-range", {
  4791. make_range_header({{1, -1}}),
  4792. {"Accept-Encoding", ""},
  4793. });
  4794. ASSERT_TRUE(res);
  4795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4796. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4797. EXPECT_EQ(true, res->has_header("Content-Range"));
  4798. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4799. EXPECT_EQ(std::string("bcdefg"), res->body);
  4800. }
  4801. TEST_F(ServerTest, GetWithRange3) {
  4802. auto res = cli_.Get("/with-range", {
  4803. make_range_header({{0, 0}}),
  4804. {"Accept-Encoding", ""},
  4805. });
  4806. ASSERT_TRUE(res);
  4807. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4808. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4809. EXPECT_EQ(true, res->has_header("Content-Range"));
  4810. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4811. EXPECT_EQ(std::string("a"), res->body);
  4812. }
  4813. TEST_F(ServerTest, GetWithRange4) {
  4814. auto res = cli_.Get("/with-range", {
  4815. make_range_header({{-1, 2}}),
  4816. {"Accept-Encoding", ""},
  4817. });
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4820. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4821. EXPECT_EQ(true, res->has_header("Content-Range"));
  4822. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4823. EXPECT_EQ(std::string("fg"), res->body);
  4824. }
  4825. TEST_F(ServerTest, GetWithRange5) {
  4826. auto res = cli_.Get("/with-range", {
  4827. make_range_header({{0, 5}}),
  4828. {"Accept-Encoding", ""},
  4829. });
  4830. ASSERT_TRUE(res);
  4831. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4832. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4833. EXPECT_EQ(true, res->has_header("Content-Range"));
  4834. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4835. EXPECT_EQ(std::string("abcdef"), res->body);
  4836. }
  4837. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4838. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4841. }
  4842. TEST_F(ServerTest, GetWithRangeMultipart) {
  4843. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4846. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4847. EXPECT_EQ(false, res->has_header("Content-Range"));
  4848. EXPECT_EQ(267U, res->body.size());
  4849. }
  4850. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4851. auto res =
  4852. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4853. ASSERT_TRUE(res);
  4854. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4855. }
  4856. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4857. auto res = cli_.Get("/with-range-customized-response",
  4858. {{make_range_header({{1, 2}})}});
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4861. EXPECT_EQ(true, res->has_header("Content-Length"));
  4862. EXPECT_EQ(false, res->has_header("Content-Range"));
  4863. EXPECT_EQ(JSON_DATA, res->body);
  4864. }
  4865. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4866. auto res = cli_.Get("/with-range-customized-response",
  4867. {{make_range_header({{1, 2}, {4, 5}})}});
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4870. EXPECT_EQ(true, res->has_header("Content-Length"));
  4871. EXPECT_EQ(false, res->has_header("Content-Range"));
  4872. EXPECT_EQ(JSON_DATA, res->body);
  4873. }
  4874. TEST_F(ServerTest, Issue1772) {
  4875. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4878. }
  4879. TEST_F(ServerTest, Issue609) {
  4880. auto res = cli_.Delete("/issue609");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::OK_200, res->status);
  4883. EXPECT_EQ(std::string("ok"), res->body);
  4884. }
  4885. TEST_F(ServerTest, GetStreamedChunked) {
  4886. auto res = cli_.Get("/streamed-chunked");
  4887. ASSERT_TRUE(res);
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. EXPECT_EQ(std::string("123456789"), res->body);
  4890. }
  4891. TEST_F(ServerTest, GetStreamedChunked2) {
  4892. auto res = cli_.Get("/streamed-chunked2");
  4893. ASSERT_TRUE(res);
  4894. EXPECT_EQ(StatusCode::OK_200, res->status);
  4895. EXPECT_EQ(std::string("123456789"), res->body);
  4896. }
  4897. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4898. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4899. ASSERT_TRUE(res);
  4900. EXPECT_EQ(StatusCode::OK_200, res->status);
  4901. EXPECT_EQ(std::string("123456789"), res->body);
  4902. EXPECT_TRUE(res->has_header("Trailer"));
  4903. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4904. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4905. // Trailers are now stored separately from headers (security fix)
  4906. EXPECT_EQ(2U, res->trailers.size());
  4907. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4908. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4909. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4910. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4911. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4912. // Verify trailers are NOT in headers (security verification)
  4913. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4914. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4915. }
  4916. TEST_F(ServerTest, LargeChunkedPost) {
  4917. Request req;
  4918. req.method = "POST";
  4919. req.path = "/large-chunked";
  4920. std::string host_and_port;
  4921. host_and_port += HOST;
  4922. host_and_port += ":";
  4923. host_and_port += std::to_string(PORT);
  4924. req.headers.emplace("Host", host_and_port.c_str());
  4925. req.headers.emplace("Accept", "*/*");
  4926. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4927. req.headers.emplace("Content-Type", "text/plain");
  4928. req.headers.emplace("Content-Length", "0");
  4929. req.headers.emplace("Transfer-Encoding", "chunked");
  4930. std::string long_string(30 * 1024u, 'a');
  4931. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4932. // Attempt to make a large enough post to exceed OS buffers, to test that
  4933. // the server handles short reads if the full chunk data isn't available.
  4934. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4935. auto res = std::make_shared<Response>();
  4936. auto error = Error::Success;
  4937. auto ret = cli_.send(req, *res, error);
  4938. ASSERT_TRUE(ret);
  4939. EXPECT_EQ(StatusCode::OK_200, res->status);
  4940. }
  4941. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4942. auto res = cli_.Get("/remote_addr");
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4947. }
  4948. TEST_F(ServerTest, GetMethodLocalAddr) {
  4949. auto res = cli_.Get("/local_addr");
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ(StatusCode::OK_200, res->status);
  4952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4953. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4954. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4955. }
  4956. TEST_F(ServerTest, HTTPResponseSplitting) {
  4957. auto res = cli_.Get("/http_response_splitting");
  4958. ASSERT_TRUE(res);
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. }
  4961. TEST_F(ServerTest, SlowRequest) {
  4962. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4963. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4964. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4965. }
  4966. #if 0
  4967. TEST_F(ServerTest, SlowPost) {
  4968. char buffer[64 * 1024];
  4969. memset(buffer, 0x42, sizeof(buffer));
  4970. auto res = cli_.Post(
  4971. "/slowpost", 64 * 1024 * 1024,
  4972. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4973. auto ret = sink.write(buffer, sizeof(buffer));
  4974. EXPECT_TRUE(ret);
  4975. return true;
  4976. },
  4977. "text/plain");
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. }
  4981. TEST_F(ServerTest, SlowPostFail) {
  4982. char buffer[64 * 1024];
  4983. memset(buffer, 0x42, sizeof(buffer));
  4984. cli_.set_write_timeout(std::chrono::seconds(0));
  4985. auto res = cli_.Post(
  4986. "/slowpost", 64 * 1024 * 1024,
  4987. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4988. sink.write(buffer, sizeof(buffer));
  4989. return true;
  4990. },
  4991. "text/plain");
  4992. ASSERT_TRUE(!res);
  4993. EXPECT_EQ(Error::Write, res.error());
  4994. }
  4995. #endif
  4996. TEST_F(ServerTest, Put) {
  4997. auto res = cli_.Put("/put", "PUT", "text/plain");
  4998. ASSERT_TRUE(res);
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. EXPECT_EQ("PUT", res->body);
  5001. }
  5002. TEST_F(ServerTest, PutWithContentProvider) {
  5003. auto res = cli_.Put(
  5004. "/put", 3,
  5005. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5006. sink.os << "PUT";
  5007. return true;
  5008. },
  5009. "text/plain");
  5010. ASSERT_TRUE(res);
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. EXPECT_EQ("PUT", res->body);
  5013. }
  5014. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5015. auto res = cli_.Post(
  5016. "/post", 42,
  5017. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5018. return false;
  5019. },
  5020. "text/plain");
  5021. ASSERT_TRUE(!res);
  5022. EXPECT_EQ(Error::Canceled, res.error());
  5023. }
  5024. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5025. auto res = cli_.Put(
  5026. "/put",
  5027. [](size_t /*offset*/, DataSink &sink) {
  5028. sink.os << "PUT";
  5029. sink.done();
  5030. return true;
  5031. },
  5032. "text/plain");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("PUT", res->body);
  5036. }
  5037. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5038. auto res = cli_.Post(
  5039. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5040. "text/plain");
  5041. ASSERT_TRUE(!res);
  5042. EXPECT_EQ(Error::Canceled, res.error());
  5043. }
  5044. TEST_F(ServerTest, PostLoopBack) {
  5045. std::string body;
  5046. auto res = cli_.Post(
  5047. "/post-loopback", 9,
  5048. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5049. EXPECT_EQ(9u, length);
  5050. sink.write("123", 3);
  5051. sink.write("456", 3);
  5052. sink.write("789", 3);
  5053. return true;
  5054. },
  5055. "text/plain",
  5056. [&body](const char *data, size_t data_length) {
  5057. body.append(data, data_length);
  5058. return true;
  5059. });
  5060. ASSERT_TRUE(res);
  5061. EXPECT_EQ(StatusCode::OK_200, res->status);
  5062. EXPECT_EQ("123456789", body);
  5063. }
  5064. TEST_F(ServerTest, PutLoopBack) {
  5065. std::string body;
  5066. auto res = cli_.Put(
  5067. "/put-loopback", 9,
  5068. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5069. EXPECT_EQ(9u, length);
  5070. sink.write("123", 3);
  5071. sink.write("456", 3);
  5072. sink.write("789", 3);
  5073. return true;
  5074. },
  5075. "text/plain",
  5076. [&body](const char *data, size_t data_length) {
  5077. body.append(data, data_length);
  5078. return true;
  5079. });
  5080. ASSERT_TRUE(res);
  5081. EXPECT_EQ(StatusCode::OK_200, res->status);
  5082. EXPECT_EQ("123456789", body);
  5083. }
  5084. TEST_F(ServerTest, PatchLoopBack) {
  5085. std::string body;
  5086. auto res = cli_.Patch(
  5087. "/patch-loopback", 9,
  5088. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5089. EXPECT_EQ(9u, length);
  5090. sink.write("123", 3);
  5091. sink.write("456", 3);
  5092. sink.write("789", 3);
  5093. return true;
  5094. },
  5095. "text/plain",
  5096. [&body](const char *data, size_t data_length) {
  5097. body.append(data, data_length);
  5098. return true;
  5099. });
  5100. ASSERT_TRUE(res);
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("123456789", body);
  5103. }
  5104. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5105. std::string body;
  5106. auto res = cli_.Post(
  5107. "/post-loopback",
  5108. [](size_t /*offset*/, DataSink &sink) {
  5109. sink.write("123", 3);
  5110. sink.write("456", 3);
  5111. sink.write("789", 3);
  5112. sink.done();
  5113. return true;
  5114. },
  5115. "text/plain",
  5116. [&body](const char *data, size_t data_length) {
  5117. body.append(data, data_length);
  5118. return true;
  5119. });
  5120. ASSERT_TRUE(res);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("123456789", body);
  5123. }
  5124. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5125. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5126. cli_.set_compress(true);
  5127. auto res = cli_.Put(
  5128. "/put", 3,
  5129. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5130. sink.os << "PUT";
  5131. return true;
  5132. },
  5133. "text/plain");
  5134. ASSERT_TRUE(res);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("PUT", res->body);
  5137. }
  5138. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5139. cli_.set_compress(true);
  5140. auto res = cli_.Post(
  5141. "/post", 42,
  5142. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5143. return false;
  5144. },
  5145. "text/plain");
  5146. ASSERT_TRUE(!res);
  5147. EXPECT_EQ(Error::Canceled, res.error());
  5148. }
  5149. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5150. cli_.set_compress(true);
  5151. auto res = cli_.Put(
  5152. "/put",
  5153. [](size_t /*offset*/, DataSink &sink) {
  5154. sink.os << "PUT";
  5155. sink.done();
  5156. return true;
  5157. },
  5158. "text/plain");
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ(StatusCode::OK_200, res->status);
  5161. EXPECT_EQ("PUT", res->body);
  5162. }
  5163. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5164. cli_.set_compress(true);
  5165. auto res = cli_.Post(
  5166. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5167. "text/plain");
  5168. ASSERT_TRUE(!res);
  5169. EXPECT_EQ(Error::Canceled, res.error());
  5170. }
  5171. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5172. cli_.set_compress(true);
  5173. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5174. ASSERT_TRUE(res);
  5175. EXPECT_EQ(StatusCode::OK_200, res->status);
  5176. EXPECT_EQ(LARGE_DATA, res->body);
  5177. }
  5178. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5179. #ifdef CPPHTTPLIB_SSL_ENABLED
  5180. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5181. Client cli(s.c_str());
  5182. cli.enable_server_certificate_verification(false);
  5183. #else
  5184. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5185. Client cli(s.c_str());
  5186. #endif
  5187. cli.set_compress(true);
  5188. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5189. ASSERT_TRUE(res);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. EXPECT_EQ(LARGE_DATA, res->body);
  5192. // The compressed size should be less than a 10th of the original. May vary
  5193. // depending on the zlib library.
  5194. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5195. static_cast<uint64_t>(10 * 1024 * 1024));
  5196. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5197. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5198. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5199. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5200. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5201. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5202. #endif
  5203. }
  5204. TEST_F(ServerTest, PutContentWithDeflate) {
  5205. cli_.set_compress(false);
  5206. Headers headers;
  5207. headers.emplace("Content-Encoding", "deflate");
  5208. // PUT in deflate format:
  5209. auto res = cli_.Put("/put", headers,
  5210. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5211. ASSERT_TRUE(res);
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. EXPECT_EQ("PUT", res->body);
  5214. }
  5215. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5216. Headers headers;
  5217. headers.emplace("Accept-Encoding", "gzip, deflate");
  5218. auto res = cli_.Get("/streamed-chunked", headers);
  5219. ASSERT_TRUE(res);
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ(std::string("123456789"), res->body);
  5222. }
  5223. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "gzip, deflate");
  5226. auto res = cli_.Get("/streamed-chunked2", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. EXPECT_EQ(std::string("123456789"), res->body);
  5230. }
  5231. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5232. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5233. ASSERT_TRUE(res);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST(GzipDecompressor, ChunkedDecompression) {
  5237. std::string data;
  5238. for (size_t i = 0; i < 32 * 1024; ++i) {
  5239. data.push_back(static_cast<char>('a' + i % 26));
  5240. }
  5241. std::string compressed_data;
  5242. {
  5243. httplib::detail::gzip_compressor compressor;
  5244. bool result = compressor.compress(
  5245. data.data(), data.size(),
  5246. /*last=*/true,
  5247. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5248. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5249. compressed_data_size);
  5250. return true;
  5251. });
  5252. ASSERT_TRUE(result);
  5253. }
  5254. std::string decompressed_data;
  5255. {
  5256. httplib::detail::gzip_decompressor decompressor;
  5257. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5258. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5259. size_t chunk_size = 130;
  5260. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5261. chunk_begin += chunk_size) {
  5262. size_t current_chunk_size =
  5263. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5264. bool result = decompressor.decompress(
  5265. compressed_data.data() + chunk_begin, current_chunk_size,
  5266. [&](const char *decompressed_data_chunk,
  5267. size_t decompressed_data_chunk_size) {
  5268. decompressed_data.insert(decompressed_data.size(),
  5269. decompressed_data_chunk,
  5270. decompressed_data_chunk_size);
  5271. return true;
  5272. });
  5273. ASSERT_TRUE(result);
  5274. }
  5275. }
  5276. ASSERT_EQ(data, decompressed_data);
  5277. }
  5278. TEST(GzipDecompressor, DeflateDecompression) {
  5279. std::string original_text = "Raw deflate without gzip";
  5280. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5281. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5282. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5283. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5284. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5285. std::string decompressed_data;
  5286. {
  5287. httplib::detail::gzip_decompressor decompressor;
  5288. bool result = decompressor.decompress(
  5289. compressed_data.data(), compressed_data.size(),
  5290. [&](const char *decompressed_data_chunk,
  5291. size_t decompressed_data_chunk_size) {
  5292. decompressed_data.insert(decompressed_data.size(),
  5293. decompressed_data_chunk,
  5294. decompressed_data_chunk_size);
  5295. return true;
  5296. });
  5297. ASSERT_TRUE(result);
  5298. }
  5299. ASSERT_EQ(original_text, decompressed_data);
  5300. }
  5301. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5302. std::string original_text = "Raw deflate without gzip";
  5303. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5304. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5305. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5306. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5307. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5308. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5309. std::string decompressed_data;
  5310. {
  5311. httplib::detail::gzip_decompressor decompressor;
  5312. bool result = decompressor.decompress(
  5313. compressed_data.data(), compressed_data.size(),
  5314. [&](const char *decompressed_data_chunk,
  5315. size_t decompressed_data_chunk_size) {
  5316. decompressed_data.insert(decompressed_data.size(),
  5317. decompressed_data_chunk,
  5318. decompressed_data_chunk_size);
  5319. return true;
  5320. });
  5321. ASSERT_TRUE(result);
  5322. }
  5323. ASSERT_EQ(original_text, decompressed_data);
  5324. }
  5325. #endif
  5326. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5327. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "br");
  5330. auto res = cli_.Get("/streamed-chunked", headers);
  5331. ASSERT_TRUE(res);
  5332. EXPECT_EQ(StatusCode::OK_200, res->status);
  5333. EXPECT_EQ(std::string("123456789"), res->body);
  5334. }
  5335. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5336. Headers headers;
  5337. headers.emplace("Accept-Encoding", "br");
  5338. auto res = cli_.Get("/streamed-chunked2", headers);
  5339. ASSERT_TRUE(res);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. EXPECT_EQ(std::string("123456789"), res->body);
  5342. }
  5343. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5344. cli_.set_compress(true);
  5345. auto res = cli_.Put(
  5346. "/put", 3,
  5347. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5348. sink.os << "PUT";
  5349. return true;
  5350. },
  5351. "text/plain");
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ("PUT", res->body);
  5355. }
  5356. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5357. cli_.set_compress(true);
  5358. auto res = cli_.Put(
  5359. "/put",
  5360. [](size_t /*offset*/, DataSink &sink) {
  5361. sink.os << "PUT";
  5362. sink.done();
  5363. return true;
  5364. },
  5365. "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5371. cli_.set_compress(true);
  5372. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5373. ASSERT_TRUE(res);
  5374. EXPECT_EQ(StatusCode::OK_200, res->status);
  5375. EXPECT_EQ(LARGE_DATA, res->body);
  5376. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5377. }
  5378. #endif
  5379. TEST_F(ServerTest, Patch) {
  5380. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5381. ASSERT_TRUE(res);
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("PATCH", res->body);
  5384. }
  5385. TEST_F(ServerTest, Delete) {
  5386. auto res = cli_.Delete("/delete");
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. EXPECT_EQ("DELETE", res->body);
  5390. }
  5391. TEST_F(ServerTest, DeleteContentReceiver) {
  5392. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5393. ASSERT_TRUE(res);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("content", res->body);
  5396. }
  5397. TEST_F(ServerTest, Options) {
  5398. auto res = cli_.Options("*");
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5402. EXPECT_TRUE(res->body.empty());
  5403. }
  5404. TEST_F(ServerTest, URL) {
  5405. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, ArrayParam) {
  5410. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5411. ASSERT_TRUE(res);
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. }
  5414. TEST_F(ServerTest, ArrayParamValues) {
  5415. auto res =
  5416. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5417. ASSERT_TRUE(res);
  5418. EXPECT_EQ(StatusCode::OK_200, res->status);
  5419. }
  5420. TEST_F(ServerTest, NoMultipleHeaders) {
  5421. Headers headers = {{"Content-Length", "5"}};
  5422. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5423. "text/plain");
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. }
  5427. TEST_F(ServerTest, PostContentReceiver) {
  5428. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5429. ASSERT_TRUE(res);
  5430. ASSERT_EQ(StatusCode::OK_200, res->status);
  5431. ASSERT_EQ("content", res->body);
  5432. }
  5433. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5434. UploadFormDataItems items = {
  5435. {"text1", "text default", "", ""},
  5436. {"text2", "aωb", "", ""},
  5437. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5438. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5439. {"file3", "", "", "application/octet-stream"},
  5440. };
  5441. auto res = cli_.Post("/content_receiver", items);
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5446. UploadFormDataItems items = {
  5447. {"text1", "text default", "", ""},
  5448. {"text2", "aωb", "", ""},
  5449. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5450. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5451. {"file3", "", "", "application/octet-stream"},
  5452. };
  5453. auto boundary = std::string("+++++");
  5454. std::string body;
  5455. for (const auto &item : items) {
  5456. body += "--" + boundary + "\r\n";
  5457. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5458. if (!item.filename.empty()) {
  5459. body += "; filename=\"" + item.filename + "\"";
  5460. }
  5461. body += "\r\n";
  5462. if (!item.content_type.empty()) {
  5463. body += "Content-Type: " + item.content_type + "\r\n";
  5464. }
  5465. body += "\r\n";
  5466. body += item.content + "\r\n";
  5467. }
  5468. body += "--" + boundary + "--\r\n";
  5469. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5470. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5471. ASSERT_TRUE(res);
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. }
  5474. TEST_F(ServerTest, PostContentReceiverGzip) {
  5475. cli_.set_compress(true);
  5476. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5477. ASSERT_TRUE(res);
  5478. ASSERT_EQ(StatusCode::OK_200, res->status);
  5479. ASSERT_EQ("content", res->body);
  5480. }
  5481. TEST_F(ServerTest, PutContentReceiver) {
  5482. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5483. ASSERT_TRUE(res);
  5484. ASSERT_EQ(StatusCode::OK_200, res->status);
  5485. ASSERT_EQ("content", res->body);
  5486. }
  5487. TEST_F(ServerTest, PatchContentReceiver) {
  5488. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5489. ASSERT_TRUE(res);
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. ASSERT_EQ("content", res->body);
  5492. }
  5493. template <typename ClientType>
  5494. void TestWithHeadersAndContentReceiver(
  5495. ClientType &cli,
  5496. std::function<Result(ClientType &, const std::string &, const Headers &,
  5497. const std::string &, const std::string &,
  5498. ContentReceiver, DownloadProgress)>
  5499. request_func) {
  5500. Headers headers;
  5501. headers.emplace("X-Custom-Header", "test-value");
  5502. std::string received_body;
  5503. auto res = request_func(
  5504. cli, "/content_receiver", headers, "content", "application/json",
  5505. [&](const char *data, size_t data_length) {
  5506. received_body.append(data, data_length);
  5507. return true;
  5508. },
  5509. nullptr);
  5510. ASSERT_TRUE(res);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. EXPECT_EQ("content", received_body);
  5513. }
  5514. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5515. #ifdef CPPHTTPLIB_SSL_ENABLED
  5516. using ClientT = SSLClient;
  5517. #else
  5518. using ClientT = Client;
  5519. #endif
  5520. TestWithHeadersAndContentReceiver<ClientT>(
  5521. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5522. const std::string &body, const std::string &content_type,
  5523. ContentReceiver receiver, DownloadProgress progress) {
  5524. return cli.Post(path, headers, body, content_type, receiver, progress);
  5525. });
  5526. }
  5527. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5528. #ifdef CPPHTTPLIB_SSL_ENABLED
  5529. using ClientT = SSLClient;
  5530. #else
  5531. using ClientT = Client;
  5532. #endif
  5533. TestWithHeadersAndContentReceiver<ClientT>(
  5534. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5535. const std::string &body, const std::string &content_type,
  5536. ContentReceiver receiver, DownloadProgress progress) {
  5537. return cli.Put(path, headers, body, content_type, receiver, progress);
  5538. });
  5539. }
  5540. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5541. #ifdef CPPHTTPLIB_SSL_ENABLED
  5542. using ClientT = SSLClient;
  5543. #else
  5544. using ClientT = Client;
  5545. #endif
  5546. TestWithHeadersAndContentReceiver<ClientT>(
  5547. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5548. const std::string &body, const std::string &content_type,
  5549. ContentReceiver receiver, DownloadProgress progress) {
  5550. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5551. });
  5552. }
  5553. template <typename ClientType>
  5554. void TestWithHeadersAndContentReceiverWithProgress(
  5555. ClientType &cli,
  5556. std::function<Result(ClientType &, const std::string &, const Headers &,
  5557. const std::string &, const std::string &,
  5558. ContentReceiver, DownloadProgress)>
  5559. request_func) {
  5560. Headers headers;
  5561. headers.emplace("X-Test-Header", "progress-test");
  5562. std::string received_body;
  5563. auto progress_called = false;
  5564. auto res = request_func(
  5565. cli, "/content_receiver", headers, "content", "text/plain",
  5566. [&](const char *data, size_t data_length) {
  5567. received_body.append(data, data_length);
  5568. return true;
  5569. },
  5570. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5571. progress_called = true;
  5572. return true;
  5573. });
  5574. ASSERT_TRUE(res);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("content", received_body);
  5577. EXPECT_TRUE(progress_called);
  5578. }
  5579. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5580. #ifdef CPPHTTPLIB_SSL_ENABLED
  5581. using ClientT = SSLClient;
  5582. #else
  5583. using ClientT = Client;
  5584. #endif
  5585. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5586. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5587. const std::string &body, const std::string &content_type,
  5588. ContentReceiver receiver, DownloadProgress progress) {
  5589. return cli.Post(path, headers, body, content_type, receiver, progress);
  5590. });
  5591. }
  5592. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5593. #ifdef CPPHTTPLIB_SSL_ENABLED
  5594. using ClientT = SSLClient;
  5595. #else
  5596. using ClientT = Client;
  5597. #endif
  5598. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5599. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5600. const std::string &body, const std::string &content_type,
  5601. ContentReceiver receiver, DownloadProgress progress) {
  5602. return cli.Put(path, headers, body, content_type, receiver, progress);
  5603. });
  5604. }
  5605. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5606. #ifdef CPPHTTPLIB_SSL_ENABLED
  5607. using ClientT = SSLClient;
  5608. #else
  5609. using ClientT = Client;
  5610. #endif
  5611. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5612. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5613. const std::string &body, const std::string &content_type,
  5614. ContentReceiver receiver, DownloadProgress progress) {
  5615. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5616. });
  5617. }
  5618. template <typename ClientType>
  5619. void TestWithHeadersAndContentReceiverError(
  5620. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5621. const Headers &, const std::string &,
  5622. const std::string &, ContentReceiver)>
  5623. request_func) {
  5624. Headers headers;
  5625. headers.emplace("X-Error-Test", "true");
  5626. std::string received_body;
  5627. auto receiver_failed = false;
  5628. auto res =
  5629. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5630. [&](const char *data, size_t data_length) {
  5631. received_body.append(data, data_length);
  5632. receiver_failed = true;
  5633. return false;
  5634. });
  5635. ASSERT_FALSE(res);
  5636. EXPECT_TRUE(receiver_failed);
  5637. }
  5638. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5639. #ifdef CPPHTTPLIB_SSL_ENABLED
  5640. using ClientT = SSLClient;
  5641. #else
  5642. using ClientT = Client;
  5643. #endif
  5644. TestWithHeadersAndContentReceiverError<ClientT>(
  5645. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5646. const std::string &body, const std::string &content_type,
  5647. ContentReceiver receiver) {
  5648. return cli.Post(path, headers, body, content_type, receiver);
  5649. });
  5650. }
  5651. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5652. #ifdef CPPHTTPLIB_SSL_ENABLED
  5653. using ClientT = SSLClient;
  5654. #else
  5655. using ClientT = Client;
  5656. #endif
  5657. TestWithHeadersAndContentReceiverError<ClientT>(
  5658. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5659. const std::string &body, const std::string &content_type,
  5660. ContentReceiver receiver) {
  5661. return cli.Put(path, headers, body, content_type, receiver);
  5662. });
  5663. }
  5664. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5665. #ifdef CPPHTTPLIB_SSL_ENABLED
  5666. using ClientT = SSLClient;
  5667. #else
  5668. using ClientT = Client;
  5669. #endif
  5670. TestWithHeadersAndContentReceiverError<ClientT>(
  5671. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5672. const std::string &body, const std::string &content_type,
  5673. ContentReceiver receiver) {
  5674. return cli.Patch(path, headers, body, content_type, receiver);
  5675. });
  5676. }
  5677. TEST_F(ServerTest, PostQueryStringAndBody) {
  5678. auto res =
  5679. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5680. ASSERT_TRUE(res);
  5681. ASSERT_EQ(StatusCode::OK_200, res->status);
  5682. }
  5683. TEST_F(ServerTest, HTTP2Magic) {
  5684. Request req;
  5685. req.method = "PRI";
  5686. req.path = "*";
  5687. req.body = "SM";
  5688. auto res = std::make_shared<Response>();
  5689. auto error = Error::Success;
  5690. auto ret = cli_.send(req, *res, error);
  5691. ASSERT_TRUE(ret);
  5692. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5693. }
  5694. TEST_F(ServerTest, KeepAlive) {
  5695. auto res = cli_.Get("/hi");
  5696. ASSERT_TRUE(res);
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5699. EXPECT_EQ("Hello World!", res->body);
  5700. res = cli_.Get("/hi");
  5701. ASSERT_TRUE(res);
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("Hello World!", res->body);
  5705. res = cli_.Get("/hi");
  5706. ASSERT_TRUE(res);
  5707. EXPECT_EQ(StatusCode::OK_200, res->status);
  5708. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5709. EXPECT_EQ("Hello World!", res->body);
  5710. res = cli_.Get("/not-exist");
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5713. res = cli_.Post("/empty", "", "text/plain");
  5714. ASSERT_TRUE(res);
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5717. EXPECT_EQ("empty", res->body);
  5718. EXPECT_EQ("close", res->get_header_value("Connection"));
  5719. res = cli_.Post(
  5720. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5721. "text/plain");
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5725. EXPECT_EQ("empty", res->body);
  5726. cli_.set_keep_alive(false);
  5727. res = cli_.Get("/last-request");
  5728. ASSERT_TRUE(res);
  5729. EXPECT_EQ(StatusCode::OK_200, res->status);
  5730. EXPECT_EQ("close", res->get_header_value("Connection"));
  5731. }
  5732. TEST_F(ServerTest, TooManyRedirect) {
  5733. cli_.set_follow_location(true);
  5734. auto res = cli_.Get("/redirect/0");
  5735. ASSERT_TRUE(!res);
  5736. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5737. }
  5738. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5739. Request req;
  5740. req.method = "FOOBAR";
  5741. req.path = "/hi";
  5742. cli_.set_keep_alive(true);
  5743. auto res = cli_.send(req);
  5744. ASSERT_TRUE(res);
  5745. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5746. EXPECT_EQ("close", res->get_header_value("Connection"));
  5747. EXPECT_FALSE(cli_.is_socket_open());
  5748. }
  5749. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5750. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5751. TEST_F(ServerTest, Gzip) {
  5752. Headers headers;
  5753. headers.emplace("Accept-Encoding", "gzip, deflate");
  5754. auto res = cli_.Get("/compress", headers);
  5755. ASSERT_TRUE(res);
  5756. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5757. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5758. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5759. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5760. "7890123456789012345678901234567890",
  5761. res->body);
  5762. EXPECT_EQ(StatusCode::OK_200, res->status);
  5763. }
  5764. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5765. Headers headers;
  5766. headers.emplace("Accept-Encoding", "gzip, deflate");
  5767. auto res = cli_.Get("/compress-with-charset", headers);
  5768. ASSERT_TRUE(res);
  5769. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5770. EXPECT_EQ("application/json; charset=utf-8",
  5771. res->get_header_value("Content-Type"));
  5772. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5773. "7890123456789012345678901234567890",
  5774. res->body);
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. }
  5777. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5778. Headers headers;
  5779. headers.emplace("Accept-Encoding", "");
  5780. auto res = cli_.Get("/compress", headers);
  5781. ASSERT_TRUE(res);
  5782. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5783. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5784. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5785. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5786. "7890123456789012345678901234567890",
  5787. res->body);
  5788. EXPECT_EQ(StatusCode::OK_200, res->status);
  5789. }
  5790. TEST_F(ServerTest, GzipWithContentReceiver) {
  5791. Headers headers;
  5792. headers.emplace("Accept-Encoding", "gzip, deflate");
  5793. std::string body;
  5794. auto res = cli_.Get("/compress", headers,
  5795. [&](const char *data, uint64_t data_length) {
  5796. EXPECT_EQ(100U, data_length);
  5797. body.append(data, data_length);
  5798. return true;
  5799. });
  5800. ASSERT_TRUE(res);
  5801. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5803. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5804. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5805. "7890123456789012345678901234567890",
  5806. body);
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. }
  5809. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5810. Headers headers;
  5811. headers.emplace("Accept-Encoding", "gzip, deflate");
  5812. cli_.set_decompress(false);
  5813. auto res = cli_.Get("/compress", headers);
  5814. ASSERT_TRUE(res);
  5815. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5817. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5818. EXPECT_EQ(33U, res->body.size());
  5819. EXPECT_EQ(StatusCode::OK_200, res->status);
  5820. }
  5821. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5822. Headers headers;
  5823. headers.emplace("Accept-Encoding", "");
  5824. std::string body;
  5825. auto res = cli_.Get("/compress", headers,
  5826. [&](const char *data, uint64_t data_length) {
  5827. EXPECT_EQ(100U, data_length);
  5828. body.append(data, data_length);
  5829. return true;
  5830. });
  5831. ASSERT_TRUE(res);
  5832. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5834. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5835. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5836. "7890123456789012345678901234567890",
  5837. body);
  5838. EXPECT_EQ(StatusCode::OK_200, res->status);
  5839. }
  5840. TEST_F(ServerTest, NoGzip) {
  5841. Headers headers;
  5842. headers.emplace("Accept-Encoding", "gzip, deflate");
  5843. auto res = cli_.Get("/nocompress", headers);
  5844. ASSERT_TRUE(res);
  5845. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5846. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5847. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5848. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5849. "7890123456789012345678901234567890",
  5850. res->body);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. }
  5853. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "gzip, deflate");
  5856. std::string body;
  5857. auto res = cli_.Get("/nocompress", headers,
  5858. [&](const char *data, uint64_t data_length) {
  5859. EXPECT_EQ(100U, data_length);
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5865. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5866. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5867. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5868. "7890123456789012345678901234567890",
  5869. body);
  5870. EXPECT_EQ(StatusCode::OK_200, res->status);
  5871. }
  5872. TEST_F(ServerTest, MultipartFormDataGzip) {
  5873. UploadFormDataItems items = {
  5874. {"key1", "test", "", ""},
  5875. {"key2", "--abcdefg123", "", ""},
  5876. };
  5877. cli_.set_compress(true);
  5878. auto res = cli_.Post("/compress-multipart", items);
  5879. ASSERT_TRUE(res);
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. }
  5882. #endif
  5883. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5884. TEST_F(ServerTest, Brotli) {
  5885. Headers headers;
  5886. headers.emplace("Accept-Encoding", "br");
  5887. auto res = cli_.Get("/compress", headers);
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5890. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5891. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5893. "7890123456789012345678901234567890",
  5894. res->body);
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. }
  5897. #endif
  5898. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5899. TEST_F(ServerTest, Zstd) {
  5900. Headers headers;
  5901. headers.emplace("Accept-Encoding", "zstd");
  5902. auto res = cli_.Get("/compress", headers);
  5903. ASSERT_TRUE(res);
  5904. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5907. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5908. "7890123456789012345678901234567890",
  5909. res->body);
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. }
  5912. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5913. Headers headers;
  5914. headers.emplace("Accept-Encoding", "");
  5915. auto res = cli_.Get("/compress", headers);
  5916. ASSERT_TRUE(res);
  5917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5921. "7890123456789012345678901234567890",
  5922. res->body);
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. }
  5925. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5926. Headers headers;
  5927. headers.emplace("Accept-Encoding", "zstd");
  5928. std::string body;
  5929. auto res = cli_.Get("/compress", headers,
  5930. [&](const char *data, uint64_t data_length) {
  5931. EXPECT_EQ(100U, data_length);
  5932. body.append(data, data_length);
  5933. return true;
  5934. });
  5935. ASSERT_TRUE(res);
  5936. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5938. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5940. "7890123456789012345678901234567890",
  5941. body);
  5942. EXPECT_EQ(StatusCode::OK_200, res->status);
  5943. }
  5944. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5945. Headers headers;
  5946. headers.emplace("Accept-Encoding", "zstd");
  5947. cli_.set_decompress(false);
  5948. auto res = cli_.Get("/compress", headers);
  5949. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5950. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5951. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5952. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5953. ASSERT_TRUE(res);
  5954. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5956. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. ASSERT_EQ(26U, res->body.size());
  5959. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5960. 0);
  5961. }
  5962. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5963. Headers headers;
  5964. headers.emplace("Accept-Encoding", "");
  5965. std::string body;
  5966. auto res = cli_.Get("/compress", headers,
  5967. [&](const char *data, uint64_t data_length) {
  5968. EXPECT_EQ(100U, data_length);
  5969. body.append(data, data_length);
  5970. return true;
  5971. });
  5972. ASSERT_TRUE(res);
  5973. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5974. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5975. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5976. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5977. "7890123456789012345678901234567890",
  5978. body);
  5979. EXPECT_EQ(StatusCode::OK_200, res->status);
  5980. }
  5981. TEST_F(ServerTest, NoZstd) {
  5982. Headers headers;
  5983. headers.emplace("Accept-Encoding", "zstd");
  5984. auto res = cli_.Get("/nocompress", headers);
  5985. ASSERT_TRUE(res);
  5986. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5987. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5988. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5990. "7890123456789012345678901234567890",
  5991. res->body);
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. }
  5994. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5995. Headers headers;
  5996. headers.emplace("Accept-Encoding", "zstd");
  5997. std::string body;
  5998. auto res = cli_.Get("/nocompress", headers,
  5999. [&](const char *data, uint64_t data_length) {
  6000. EXPECT_EQ(100U, data_length);
  6001. body.append(data, data_length);
  6002. return true;
  6003. });
  6004. ASSERT_TRUE(res);
  6005. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6006. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6007. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6009. "7890123456789012345678901234567890",
  6010. body);
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. }
  6013. // TODO: How to enable zstd ??
  6014. TEST_F(ServerTest, MultipartFormDataZstd) {
  6015. UploadFormDataItems items = {
  6016. {"key1", "test", "", ""},
  6017. {"key2", "--abcdefg123", "", ""},
  6018. };
  6019. Headers headers;
  6020. headers.emplace("Accept-Encoding", "zstd");
  6021. cli_.set_compress(true);
  6022. auto res = cli_.Post("/compress-multipart", headers, items);
  6023. ASSERT_TRUE(res);
  6024. EXPECT_EQ(StatusCode::OK_200, res->status);
  6025. }
  6026. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6027. Headers headers;
  6028. headers.emplace("Accept-Encoding", "zstd");
  6029. cli_.set_compress(true);
  6030. auto res = cli_.Put(
  6031. "/put", headers, 3,
  6032. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6033. sink.os << "PUT";
  6034. return true;
  6035. },
  6036. "text/plain");
  6037. ASSERT_TRUE(res);
  6038. EXPECT_EQ(StatusCode::OK_200, res->status);
  6039. EXPECT_EQ("PUT", res->body);
  6040. }
  6041. // Pre-compression logging tests
  6042. TEST_F(ServerTest, PreCompressionLogging) {
  6043. // Test data for compression (matches the actual /compress endpoint content)
  6044. const std::string test_content =
  6045. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6046. "3456789012345678901234567890";
  6047. // Variables to capture logging data
  6048. std::string pre_compression_body;
  6049. std::string pre_compression_content_type;
  6050. std::string pre_compression_content_encoding;
  6051. std::string post_compression_body;
  6052. std::string post_compression_content_type;
  6053. std::string post_compression_content_encoding;
  6054. // Set up pre-compression logger
  6055. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6056. const Response &res) {
  6057. pre_compression_body = res.body;
  6058. pre_compression_content_type = res.get_header_value("Content-Type");
  6059. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6060. });
  6061. // Set up post-compression logger
  6062. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6063. post_compression_body = res.body;
  6064. post_compression_content_type = res.get_header_value("Content-Type");
  6065. post_compression_content_encoding =
  6066. res.get_header_value("Content-Encoding");
  6067. });
  6068. // Test with gzip compression
  6069. Headers headers;
  6070. headers.emplace("Accept-Encoding", "gzip");
  6071. auto res = cli_.Get("/compress", headers);
  6072. // Verify response was compressed
  6073. ASSERT_TRUE(res);
  6074. EXPECT_EQ(StatusCode::OK_200, res->status);
  6075. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6076. // Verify pre-compression logger captured uncompressed content
  6077. EXPECT_EQ(test_content, pre_compression_body);
  6078. EXPECT_EQ("text/plain", pre_compression_content_type);
  6079. EXPECT_TRUE(pre_compression_content_encoding
  6080. .empty()); // No encoding header before compression
  6081. // Verify post-compression logger captured compressed content
  6082. EXPECT_NE(test_content,
  6083. post_compression_body); // Should be different after compression
  6084. EXPECT_EQ("text/plain", post_compression_content_type);
  6085. EXPECT_EQ("gzip", post_compression_content_encoding);
  6086. // Verify compressed content is smaller
  6087. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6088. }
  6089. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6090. const std::string test_content =
  6091. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6092. "3456789012345678901234567890";
  6093. std::string pre_compression_body;
  6094. std::string post_compression_body;
  6095. svr_.set_pre_compression_logger(
  6096. [&](const Request & /*req*/, const Response &res) {
  6097. pre_compression_body = res.body;
  6098. });
  6099. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6100. post_compression_body = res.body;
  6101. });
  6102. Headers headers;
  6103. headers.emplace("Accept-Encoding", "br");
  6104. auto res = cli_.Get("/compress", headers);
  6105. ASSERT_TRUE(res);
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6108. // Verify pre-compression content is uncompressed
  6109. EXPECT_EQ(test_content, pre_compression_body);
  6110. // Verify post-compression content is compressed
  6111. EXPECT_NE(test_content, post_compression_body);
  6112. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6113. }
  6114. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6115. const std::string test_content =
  6116. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6117. "3456789012345678901234567890";
  6118. std::string pre_compression_body;
  6119. std::string post_compression_body;
  6120. svr_.set_pre_compression_logger(
  6121. [&](const Request & /*req*/, const Response &res) {
  6122. pre_compression_body = res.body;
  6123. });
  6124. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6125. post_compression_body = res.body;
  6126. });
  6127. // Request without compression (use /nocompress endpoint)
  6128. Headers headers;
  6129. auto res = cli_.Get("/nocompress", headers);
  6130. ASSERT_TRUE(res);
  6131. EXPECT_EQ(StatusCode::OK_200, res->status);
  6132. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6133. // Pre-compression logger should not be called when no compression is applied
  6134. EXPECT_TRUE(
  6135. pre_compression_body.empty()); // Pre-compression logger not called
  6136. EXPECT_EQ(
  6137. test_content,
  6138. post_compression_body); // Post-compression logger captures final content
  6139. }
  6140. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6141. const std::string test_content =
  6142. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6143. "3456789012345678901234567890";
  6144. std::string pre_compression_body;
  6145. bool pre_logger_called = false;
  6146. // Set only pre-compression logger
  6147. svr_.set_pre_compression_logger(
  6148. [&](const Request & /*req*/, const Response &res) {
  6149. pre_compression_body = res.body;
  6150. pre_logger_called = true;
  6151. });
  6152. Headers headers;
  6153. headers.emplace("Accept-Encoding", "gzip");
  6154. auto res = cli_.Get("/compress", headers);
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6158. // Verify pre-compression logger was called
  6159. EXPECT_TRUE(pre_logger_called);
  6160. EXPECT_EQ(test_content, pre_compression_body);
  6161. }
  6162. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6163. {
  6164. // Test with Expect: 100-continue header - success case
  6165. // Server returns 100 Continue, client sends body, server returns 200 OK
  6166. Request req;
  6167. req.method = "POST";
  6168. req.path = "/post-large";
  6169. req.set_header("Expect", "100-continue");
  6170. req.body = LARGE_DATA;
  6171. Response res;
  6172. auto error = Error::Success;
  6173. cli_.set_keep_alive(true);
  6174. auto ret = cli_.send(req, res, error);
  6175. EXPECT_TRUE(ret);
  6176. EXPECT_EQ(StatusCode::OK_200, res.status);
  6177. EXPECT_EQ(LARGE_DATA, res.body);
  6178. }
  6179. {
  6180. // Test with Expect: 100-continue header - error case
  6181. // Client should not send the body when server returns an error
  6182. Request req;
  6183. req.method = "POST";
  6184. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6185. req.set_header("Expect", "100-continue");
  6186. req.body = LARGE_DATA;
  6187. Response res;
  6188. auto error = Error::Success;
  6189. auto start = std::chrono::high_resolution_clock::now();
  6190. cli_.set_keep_alive(true);
  6191. auto ret = cli_.send(req, res, error);
  6192. auto end = std::chrono::high_resolution_clock::now();
  6193. auto elapsed =
  6194. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6195. .count();
  6196. // With Expect: 100-continue, request completes successfully but with error
  6197. EXPECT_TRUE(ret);
  6198. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6199. EXPECT_EQ("close", res.get_header_value("Connection"));
  6200. EXPECT_FALSE(cli_.is_socket_open());
  6201. EXPECT_LE(elapsed, 2000);
  6202. }
  6203. {
  6204. // Send an extra GET request to ensure error recovery without hanging
  6205. Request req;
  6206. req.method = "GET";
  6207. req.path = "/hi";
  6208. auto start = std::chrono::high_resolution_clock::now();
  6209. auto res = cli_.send(req);
  6210. auto end = std::chrono::high_resolution_clock::now();
  6211. auto elapsed =
  6212. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6213. .count();
  6214. ASSERT_TRUE(res);
  6215. EXPECT_EQ(StatusCode::OK_200, res->status);
  6216. EXPECT_EQ("Hello World!", res->body);
  6217. EXPECT_LE(elapsed, 500);
  6218. }
  6219. }
  6220. TEST(ZstdDecompressor, ChunkedDecompression) {
  6221. std::string data;
  6222. for (size_t i = 0; i < 32 * 1024; ++i) {
  6223. data.push_back(static_cast<char>('a' + i % 26));
  6224. }
  6225. std::string compressed_data;
  6226. {
  6227. httplib::detail::zstd_compressor compressor;
  6228. bool result = compressor.compress(
  6229. data.data(), data.size(),
  6230. /*last=*/true,
  6231. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6232. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6233. compressed_data_size);
  6234. return true;
  6235. });
  6236. ASSERT_TRUE(result);
  6237. }
  6238. std::string decompressed_data;
  6239. {
  6240. httplib::detail::zstd_decompressor decompressor;
  6241. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6242. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6243. size_t chunk_size = 130;
  6244. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6245. chunk_begin += chunk_size) {
  6246. size_t current_chunk_size =
  6247. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6248. bool result = decompressor.decompress(
  6249. compressed_data.data() + chunk_begin, current_chunk_size,
  6250. [&](const char *decompressed_data_chunk,
  6251. size_t decompressed_data_chunk_size) {
  6252. decompressed_data.insert(decompressed_data.size(),
  6253. decompressed_data_chunk,
  6254. decompressed_data_chunk_size);
  6255. return true;
  6256. });
  6257. ASSERT_TRUE(result);
  6258. }
  6259. }
  6260. ASSERT_EQ(data, decompressed_data);
  6261. }
  6262. TEST(ZstdDecompressor, Decompress) {
  6263. std::string original_text = "Compressed with ZSTD";
  6264. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6265. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6266. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6267. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6268. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6269. std::string decompressed_data;
  6270. {
  6271. httplib::detail::zstd_decompressor decompressor;
  6272. bool result = decompressor.decompress(
  6273. compressed_data.data(), compressed_data.size(),
  6274. [&](const char *decompressed_data_chunk,
  6275. size_t decompressed_data_chunk_size) {
  6276. decompressed_data.insert(decompressed_data.size(),
  6277. decompressed_data_chunk,
  6278. decompressed_data_chunk_size);
  6279. return true;
  6280. });
  6281. ASSERT_TRUE(result);
  6282. }
  6283. ASSERT_EQ(original_text, decompressed_data);
  6284. }
  6285. #endif
  6286. // Sends a raw request to a server listening at HOST:PORT.
  6287. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6288. std::string *resp = nullptr) {
  6289. auto error = Error::Success;
  6290. auto client_sock = detail::create_client_socket(
  6291. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6292. /*connection_timeout_sec=*/5, 0,
  6293. /*read_timeout_sec=*/5, 0,
  6294. /*write_timeout_sec=*/5, 0, std::string(), error);
  6295. if (client_sock == INVALID_SOCKET) { return false; }
  6296. auto ret = detail::process_client_socket(
  6297. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6298. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6299. if (req.size() !=
  6300. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6301. return false;
  6302. }
  6303. char buf[512];
  6304. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6305. while (line_reader.getline()) {
  6306. if (resp) { *resp += line_reader.ptr(); }
  6307. }
  6308. return true;
  6309. });
  6310. detail::close_socket(client_sock);
  6311. return ret;
  6312. }
  6313. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6314. Server svr;
  6315. std::string header_value;
  6316. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6317. header_value = req.get_header_value("foo");
  6318. res.set_content("ok", "text/plain");
  6319. });
  6320. thread t = thread([&] { svr.listen(HOST, PORT); });
  6321. auto se = detail::scope_exit([&] {
  6322. svr.stop();
  6323. t.join();
  6324. ASSERT_FALSE(svr.is_running());
  6325. });
  6326. svr.wait_until_ready();
  6327. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6328. // like characters are not treated the same - use vertical tab and escape.
  6329. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6330. "foo: \t \v bar \x1B\t \r\n"
  6331. "Connection: close\r\n"
  6332. "\r\n";
  6333. std::string res;
  6334. ASSERT_TRUE(send_request(5, req, &res));
  6335. EXPECT_EQ(header_value, "");
  6336. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6337. }
  6338. // Sends a raw request and verifies that there isn't a crash or exception.
  6339. static void test_raw_request(const std::string &req,
  6340. std::string *out = nullptr) {
  6341. Server svr;
  6342. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6343. res.set_content("ok", "text/plain");
  6344. });
  6345. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6346. res.set_content("ok", "text/plain");
  6347. });
  6348. svr.Get("/header_field_value_check",
  6349. [&](const Request & /*req*/, Response &res) {
  6350. res.set_content("ok", "text/plain");
  6351. });
  6352. // Server read timeout must be longer than the client read timeout for the
  6353. // bug to reproduce, probably to force the server to process a request
  6354. // without a trailing blank line.
  6355. const time_t client_read_timeout_sec = 1;
  6356. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6357. bool listen_thread_ok = false;
  6358. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6359. auto se = detail::scope_exit([&] {
  6360. svr.stop();
  6361. t.join();
  6362. ASSERT_FALSE(svr.is_running());
  6363. EXPECT_TRUE(listen_thread_ok);
  6364. });
  6365. svr.wait_until_ready();
  6366. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6367. }
  6368. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6369. // A certain header line causes an exception if the header property is parsed
  6370. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6371. test_raw_request(
  6372. "GET /hi HTTP/1.1\r\n"
  6373. " : "
  6374. " "
  6375. " ");
  6376. }
  6377. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6378. // A certain header line causes an exception if the header property *name* is
  6379. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6380. // greedy matcher and requires backtracking when there are a lot of ":"
  6381. // characters.
  6382. // This occurs with libc++ but not libstdc++.
  6383. test_raw_request(
  6384. "GET /hi HTTP/1.1\r\n"
  6385. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6386. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6387. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6388. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6389. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6390. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6391. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6392. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6393. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6394. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6395. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6396. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6397. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6398. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6399. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6400. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6401. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6402. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6403. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6404. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6405. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6406. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6407. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6408. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6409. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6410. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6411. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6412. "&&&%%%");
  6413. }
  6414. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6415. // Make sure this doesn't crash the server.
  6416. // In a previous version of the header line regex, the "\r" rendered the line
  6417. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6418. // a new position where the leading white space ended and the field value
  6419. // began.
  6420. // The crash occurs with libc++ but not libstdc++.
  6421. test_raw_request("GET /hi HTTP/1.1\r\n"
  6422. "a:" +
  6423. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6424. "\r\n"
  6425. "\r\n");
  6426. }
  6427. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6428. std::string out;
  6429. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6430. "Content-Type: text/plain\r\n"
  6431. "Transfer-Encoding: chunked\r\n"
  6432. "\r\n"
  6433. "nothex\r\n",
  6434. &out);
  6435. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6436. }
  6437. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6438. std::string out;
  6439. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6440. "Content-Type: text/plain\r\n"
  6441. "Transfer-Encoding: chunked\r\n"
  6442. "\r\n"
  6443. "3\r\n"
  6444. "xyz\r\n"
  6445. "NaN\r\n",
  6446. &out);
  6447. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6448. }
  6449. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6450. std::string out;
  6451. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6452. "Content-Type: text/plain\r\n"
  6453. "Transfer-Encoding: chunked\r\n"
  6454. "\r\n"
  6455. // Length is too large for 64 bits.
  6456. "1ffffffffffffffff\r\n"
  6457. "xyz\r\n",
  6458. &out);
  6459. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6460. }
  6461. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6462. test_raw_request("GET /hi HTTP/1.1\r\n"
  6463. "Content-Type: text/plain\r\n\r");
  6464. }
  6465. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6466. std::string out;
  6467. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6468. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6469. }
  6470. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6471. Server svr;
  6472. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6473. EXPECT_TRUE(!req.remote_addr.empty());
  6474. });
  6475. thread t = thread([&] { svr.listen(HOST, PORT); });
  6476. auto se = detail::scope_exit([&] {
  6477. svr.stop();
  6478. t.join();
  6479. ASSERT_FALSE(svr.is_running());
  6480. });
  6481. svr.wait_until_ready();
  6482. // Send an invalid request line to trigger Bad Request
  6483. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6484. std::string out;
  6485. ASSERT_TRUE(send_request(5, bad_req, &out));
  6486. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6487. }
  6488. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6489. std::string out;
  6490. std::string request(
  6491. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6492. test_raw_request(request, &out);
  6493. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6494. }
  6495. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6496. std::string out;
  6497. std::string request(
  6498. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6499. test_raw_request(request, &out);
  6500. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6501. }
  6502. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6503. std::string out;
  6504. std::string request(
  6505. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6506. test_raw_request(request, &out);
  6507. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6508. }
  6509. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6510. std::string out;
  6511. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6512. "Test: \r\n\r\n",
  6513. &out);
  6514. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6515. }
  6516. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6517. Server svr;
  6518. std::string x_custom;
  6519. std::string cookie;
  6520. std::string xff;
  6521. std::string x_unicode;
  6522. std::string x_iis;
  6523. svr.Get("/check", [&](const Request &req, Response &res) {
  6524. x_custom = req.get_header_value("X-Custom");
  6525. cookie = req.get_header_value("Cookie");
  6526. xff = req.get_header_value("X-Forwarded-For");
  6527. x_unicode = req.get_header_value("X-Unicode");
  6528. x_iis = req.get_header_value("X-IIS");
  6529. res.set_content("ok", "text/plain");
  6530. });
  6531. thread t = thread([&] { svr.listen(HOST, PORT); });
  6532. auto se = detail::scope_exit([&] {
  6533. svr.stop();
  6534. t.join();
  6535. ASSERT_FALSE(svr.is_running());
  6536. });
  6537. svr.wait_until_ready();
  6538. const std::string req = "GET /check HTTP/1.1\r\n"
  6539. "Host: localhost\r\n"
  6540. "X-Custom: a%0D%0AInjected: b\r\n"
  6541. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6542. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6543. "X-Unicode: %E3%81%82\r\n"
  6544. "X-IIS: %u00E9\r\n"
  6545. "Connection: close\r\n"
  6546. "\r\n";
  6547. std::string res;
  6548. ASSERT_TRUE(send_request(5, req, &res));
  6549. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6550. // Every value must be returned verbatim (wire form), with no decoding.
  6551. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6552. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6553. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6554. EXPECT_EQ("%E3%81%82", x_unicode);
  6555. EXPECT_EQ("%u00E9", x_iis);
  6556. }
  6557. // Applications that previously relied on automatic percent-decoding can
  6558. // reproduce the old behavior by explicitly calling decode_path_component()
  6559. // or, for RFC 3986 conformance, decode_uri_component().
  6560. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6561. Server svr;
  6562. std::string decoded;
  6563. svr.Get("/check", [&](const Request &req, Response &res) {
  6564. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6565. res.set_content("ok", "text/plain");
  6566. });
  6567. thread t = thread([&] { svr.listen(HOST, PORT); });
  6568. auto se = detail::scope_exit([&] {
  6569. svr.stop();
  6570. t.join();
  6571. ASSERT_FALSE(svr.is_running());
  6572. });
  6573. svr.wait_until_ready();
  6574. const std::string req = "GET /check HTTP/1.1\r\n"
  6575. "Host: localhost\r\n"
  6576. "X-Custom: hello%20world\r\n"
  6577. "Connection: close\r\n"
  6578. "\r\n";
  6579. std::string res;
  6580. ASSERT_TRUE(send_request(5, req, &res));
  6581. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6582. EXPECT_EQ("hello world", decoded);
  6583. }
  6584. // Regression test for #2033. Browsers send Referer values that include
  6585. // percent-encoded characters such as %0A inside the URL. Decoding the
  6586. // header value would either trip the post-decode CR/LF/NUL guard (the
  6587. // original bug, returning 400) or, after that guard was relaxed, silently
  6588. // store a literal LF — both unacceptable. The wire form must round-trip.
  6589. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6590. Server svr;
  6591. std::string referer;
  6592. svr.Get("/check", [&](const Request &req, Response &res) {
  6593. referer = req.get_header_value("Referer");
  6594. res.set_content("ok", "text/plain");
  6595. });
  6596. thread t = thread([&] { svr.listen(HOST, PORT); });
  6597. auto se = detail::scope_exit([&] {
  6598. svr.stop();
  6599. t.join();
  6600. ASSERT_FALSE(svr.is_running());
  6601. });
  6602. svr.wait_until_ready();
  6603. const std::string req = "GET /check HTTP/1.1\r\n"
  6604. "Host: localhost\r\n"
  6605. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6606. "Connection: close\r\n"
  6607. "\r\n";
  6608. std::string res;
  6609. ASSERT_TRUE(send_request(5, req, &res));
  6610. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6611. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6612. }
  6613. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6614. Server svr;
  6615. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6616. res.set_header("Cache-Control", "no-cache");
  6617. res.set_chunked_content_provider(
  6618. "text/event-stream", [](size_t offset, DataSink &sink) {
  6619. std::string s = "data:";
  6620. s += std::to_string(offset);
  6621. s += "\n\n";
  6622. auto ret = sink.write(s.data(), s.size());
  6623. EXPECT_TRUE(ret);
  6624. std::this_thread::sleep_for(std::chrono::seconds(1));
  6625. return true;
  6626. });
  6627. });
  6628. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6629. svr.wait_until_ready();
  6630. Client client(HOST, PORT);
  6631. const Headers headers = {{"Accept", "text/event-stream"}};
  6632. auto get_thread = std::thread([&client, &headers]() {
  6633. auto res = client.Get(
  6634. "/events", headers,
  6635. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6636. });
  6637. auto se = detail::scope_exit([&] {
  6638. svr.stop();
  6639. get_thread.join();
  6640. listen_thread.join();
  6641. ASSERT_FALSE(svr.is_running());
  6642. });
  6643. // Give GET time to get a few messages.
  6644. std::this_thread::sleep_for(std::chrono::seconds(2));
  6645. }
  6646. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6647. httplib::Server svr;
  6648. svr.Post("/hi",
  6649. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6650. res.status = StatusCode::OK_200;
  6651. });
  6652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6653. svr.wait_until_ready();
  6654. Client cli(HOST, PORT);
  6655. auto res = cli.Post("/hi", "data", "text/plain");
  6656. ASSERT_TRUE(res);
  6657. EXPECT_EQ(StatusCode::OK_200, res->status);
  6658. svr.stop();
  6659. thread.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. res = cli.Post("/hi", "data", "text/plain");
  6662. ASSERT_FALSE(res);
  6663. }
  6664. TEST(ServerStopTest, ListenFailure) {
  6665. Server svr;
  6666. auto t = thread([&]() {
  6667. auto ret = svr.listen("????", PORT);
  6668. EXPECT_FALSE(ret);
  6669. });
  6670. svr.wait_until_ready();
  6671. svr.stop();
  6672. t.join();
  6673. }
  6674. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6675. TEST(ServerStopTest, Decommision) {
  6676. Server svr;
  6677. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6678. for (int i = 0; i < 4; i++) {
  6679. auto is_even = !(i % 2);
  6680. std::thread t{[&] {
  6681. try {
  6682. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6683. if (is_even) {
  6684. throw std::runtime_error("Some thing that happens to go wrong.");
  6685. }
  6686. svr.listen(HOST, PORT);
  6687. } catch (...) { svr.decommission(); }
  6688. }};
  6689. svr.wait_until_ready();
  6690. // Server is up
  6691. {
  6692. Client cli(HOST, PORT);
  6693. auto res = cli.Get("/hi");
  6694. if (is_even) {
  6695. EXPECT_FALSE(res);
  6696. } else {
  6697. EXPECT_TRUE(res);
  6698. EXPECT_EQ("hi...", res->body);
  6699. }
  6700. }
  6701. svr.stop();
  6702. t.join();
  6703. // Server is down...
  6704. {
  6705. Client cli(HOST, PORT);
  6706. auto res = cli.Get("/hi");
  6707. EXPECT_FALSE(res);
  6708. }
  6709. }
  6710. }
  6711. #endif
  6712. // Helper function for string body upload progress tests
  6713. template <typename SetupHandler, typename ClientCall>
  6714. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6715. ClientCall &&client_call,
  6716. const string &body) {
  6717. Server svr;
  6718. setup_handler(svr);
  6719. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6720. auto se = detail::scope_exit([&] {
  6721. svr.stop();
  6722. t.join();
  6723. });
  6724. svr.wait_until_ready();
  6725. Client cli(HOST, PORT);
  6726. vector<uint64_t> progress_values;
  6727. bool progress_called = false;
  6728. auto res =
  6729. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6730. progress_values.push_back(current);
  6731. progress_called = true;
  6732. return true;
  6733. });
  6734. ASSERT_TRUE(res);
  6735. EXPECT_EQ(200, res->status);
  6736. EXPECT_TRUE(progress_called);
  6737. }
  6738. TEST(UploadProgressTest, PostStringBodyBasic) {
  6739. TestStringBodyUploadProgress(
  6740. [](Server &svr) {
  6741. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6742. res.set_content("received", "text/plain");
  6743. });
  6744. },
  6745. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6746. return cli.Post("/test", body, "text/plain", progress_callback);
  6747. },
  6748. "test data for upload progress");
  6749. }
  6750. TEST(UploadProgressTest, PutStringBodyBasic) {
  6751. TestStringBodyUploadProgress(
  6752. [](Server &svr) {
  6753. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6754. res.set_content("put received", "text/plain");
  6755. });
  6756. },
  6757. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6758. return cli.Put("/test", body, "text/plain", progress_callback);
  6759. },
  6760. "put test data for upload progress");
  6761. }
  6762. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6763. TestStringBodyUploadProgress(
  6764. [](Server &svr) {
  6765. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6766. res.set_content("patch received", "text/plain");
  6767. });
  6768. },
  6769. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6770. return cli.Patch("/test", body, "text/plain", progress_callback);
  6771. },
  6772. "patch test data for upload progress");
  6773. }
  6774. // Helper function for content provider upload progress tests
  6775. template <typename SetupHandler, typename ClientCall>
  6776. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6777. ClientCall &&client_call) {
  6778. Server svr;
  6779. setup_handler(svr);
  6780. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6781. auto se = detail::scope_exit([&] {
  6782. svr.stop();
  6783. t.join();
  6784. });
  6785. svr.wait_until_ready();
  6786. Client cli(HOST, PORT);
  6787. vector<uint64_t> progress_values;
  6788. auto res =
  6789. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6790. progress_values.push_back(current);
  6791. return true;
  6792. });
  6793. ASSERT_TRUE(res);
  6794. EXPECT_EQ(200, res->status);
  6795. EXPECT_FALSE(progress_values.empty());
  6796. }
  6797. TEST(UploadProgressTest, PostContentProviderProgress) {
  6798. TestContentProviderUploadProgress(
  6799. [](Server &svr) {
  6800. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6801. res.set_content("provider received", "text/plain");
  6802. });
  6803. },
  6804. [](Client &cli, UploadProgress progress_callback) {
  6805. return cli.Post(
  6806. "/test", 10,
  6807. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6808. sink.os << "test data";
  6809. return true;
  6810. },
  6811. "text/plain", progress_callback);
  6812. });
  6813. }
  6814. // Helper function for multipart upload progress tests
  6815. template <typename SetupHandler, typename ClientCall>
  6816. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6817. ClientCall &&client_call,
  6818. const string &endpoint) {
  6819. Server svr;
  6820. setup_handler(svr);
  6821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6822. auto se = detail::scope_exit([&] {
  6823. svr.stop();
  6824. t.join();
  6825. });
  6826. svr.wait_until_ready();
  6827. Client cli(HOST, PORT);
  6828. vector<uint64_t> progress_values;
  6829. UploadFormDataItems items = {
  6830. {"field1", "value1", "", ""},
  6831. {"field2", "longer value for progress tracking test", "", ""},
  6832. {"file1", "file content data for upload progress", "test.txt",
  6833. "text/plain"}};
  6834. auto res = client_call(cli, endpoint, items,
  6835. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6836. progress_values.push_back(current);
  6837. return true;
  6838. });
  6839. ASSERT_TRUE(res);
  6840. EXPECT_EQ(200, res->status);
  6841. EXPECT_FALSE(progress_values.empty());
  6842. }
  6843. TEST(UploadProgressTest, PostMultipartProgress) {
  6844. TestMultipartUploadProgress(
  6845. [](Server &svr) {
  6846. svr.Post("/multipart", [](const Request &req, Response &res) {
  6847. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6848. res.set_content("multipart received", "text/plain");
  6849. });
  6850. },
  6851. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6852. UploadProgress progress_callback) {
  6853. return cli.Post(endpoint, items, progress_callback);
  6854. },
  6855. "/multipart");
  6856. }
  6857. // Helper function for basic download progress tests
  6858. template <typename SetupHandler, typename ClientCall>
  6859. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6860. ClientCall &&client_call, const string &endpoint,
  6861. size_t expected_content_size) {
  6862. Server svr;
  6863. setup_handler(svr);
  6864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6865. auto se = detail::scope_exit([&] {
  6866. svr.stop();
  6867. t.join();
  6868. });
  6869. svr.wait_until_ready();
  6870. Client cli(HOST, PORT);
  6871. vector<uint64_t> progress_values;
  6872. auto res = client_call(cli, endpoint,
  6873. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6874. progress_values.push_back(current);
  6875. return true;
  6876. });
  6877. ASSERT_TRUE(res);
  6878. EXPECT_EQ(200, res->status);
  6879. EXPECT_FALSE(progress_values.empty());
  6880. EXPECT_EQ(expected_content_size, res->body.size());
  6881. }
  6882. TEST(DownloadProgressTest, GetBasic) {
  6883. TestBasicDownloadProgress(
  6884. [](Server &svr) {
  6885. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6886. string content(1000, 'D');
  6887. res.set_content(content, "text/plain");
  6888. });
  6889. },
  6890. [](Client &cli, const string &endpoint,
  6891. DownloadProgress progress_callback) {
  6892. return cli.Get(endpoint, progress_callback);
  6893. },
  6894. "/download", 1000u);
  6895. }
  6896. // Helper function for content receiver download progress tests
  6897. template <typename SetupHandler, typename ClientCall>
  6898. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6899. ClientCall &&client_call,
  6900. const string &endpoint,
  6901. size_t expected_content_size) {
  6902. Server svr;
  6903. setup_handler(svr);
  6904. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6905. auto se = detail::scope_exit([&] {
  6906. svr.stop();
  6907. t.join();
  6908. });
  6909. svr.wait_until_ready();
  6910. Client cli(HOST, PORT);
  6911. vector<uint64_t> progress_values;
  6912. string received_body;
  6913. auto res = client_call(
  6914. cli, endpoint,
  6915. [&](const char *data, size_t data_length) -> bool {
  6916. received_body.append(data, data_length);
  6917. return true;
  6918. },
  6919. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6920. progress_values.push_back(current);
  6921. return true;
  6922. });
  6923. ASSERT_TRUE(res);
  6924. EXPECT_EQ(200, res->status);
  6925. EXPECT_FALSE(progress_values.empty());
  6926. EXPECT_EQ(expected_content_size, received_body.size());
  6927. EXPECT_TRUE(res->body.empty());
  6928. }
  6929. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6930. TestContentReceiverDownloadProgress(
  6931. [](Server &svr) {
  6932. svr.Get("/download-receiver",
  6933. [](const Request & /*req*/, Response &res) {
  6934. string content(2000, 'R');
  6935. res.set_content(content, "text/plain");
  6936. });
  6937. },
  6938. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6939. DownloadProgress progress_callback) {
  6940. return cli.Get(endpoint, content_receiver, progress_callback);
  6941. },
  6942. "/download-receiver", 2000u);
  6943. }
  6944. TEST(StreamingTest, NoContentLengthStreaming) {
  6945. Server svr;
  6946. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6947. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6948. if (offset < 6) {
  6949. sink.os << (offset < 3 ? "a" : "b");
  6950. } else {
  6951. sink.done();
  6952. }
  6953. return true;
  6954. });
  6955. });
  6956. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6957. auto listen_se = detail::scope_exit([&] {
  6958. svr.stop();
  6959. listen_thread.join();
  6960. ASSERT_FALSE(svr.is_running());
  6961. });
  6962. svr.wait_until_ready();
  6963. Client client(HOST, PORT);
  6964. auto get_thread = std::thread([&client]() {
  6965. std::string s;
  6966. auto res =
  6967. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6968. s += std::string(data, len);
  6969. return true;
  6970. });
  6971. ASSERT_TRUE(res);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. EXPECT_EQ("aaabbb", s);
  6974. });
  6975. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6976. // Give GET time to get a few messages.
  6977. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6978. }
  6979. TEST(MountTest, Unmount) {
  6980. Server svr;
  6981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6982. auto se = detail::scope_exit([&] {
  6983. svr.stop();
  6984. listen_thread.join();
  6985. ASSERT_FALSE(svr.is_running());
  6986. });
  6987. svr.wait_until_ready();
  6988. Client cli("localhost", PORT);
  6989. svr.set_mount_point("/mount2", "./www2");
  6990. auto res = cli.Get("/");
  6991. ASSERT_TRUE(res);
  6992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6993. res = cli.Get("/mount2/dir/test.html");
  6994. ASSERT_TRUE(res);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. svr.set_mount_point("/", "./www");
  6997. res = cli.Get("/dir/");
  6998. ASSERT_TRUE(res);
  6999. EXPECT_EQ(StatusCode::OK_200, res->status);
  7000. svr.remove_mount_point("/");
  7001. res = cli.Get("/dir/");
  7002. ASSERT_TRUE(res);
  7003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7004. svr.remove_mount_point("/mount2");
  7005. res = cli.Get("/mount2/dir/test.html");
  7006. ASSERT_TRUE(res);
  7007. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7008. }
  7009. TEST(MountTest, Redicect) {
  7010. Server svr;
  7011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7012. auto se = detail::scope_exit([&] {
  7013. svr.stop();
  7014. listen_thread.join();
  7015. ASSERT_FALSE(svr.is_running());
  7016. });
  7017. svr.set_mount_point("/", "./www");
  7018. svr.wait_until_ready();
  7019. Client cli("localhost", PORT);
  7020. auto res = cli.Get("/dir/");
  7021. ASSERT_TRUE(res);
  7022. EXPECT_EQ(StatusCode::OK_200, res->status);
  7023. res = cli.Get("/dir");
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7026. res = cli.Get("/file");
  7027. ASSERT_TRUE(res);
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. res = cli.Get("/file/");
  7030. ASSERT_TRUE(res);
  7031. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7032. cli.set_follow_location(true);
  7033. res = cli.Get("/dir");
  7034. ASSERT_TRUE(res);
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST(MountTest, MultibytesPathName) {
  7038. Server svr;
  7039. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7040. auto se = detail::scope_exit([&] {
  7041. svr.stop();
  7042. listen_thread.join();
  7043. ASSERT_FALSE(svr.is_running());
  7044. });
  7045. svr.set_mount_point("/", "./www");
  7046. svr.wait_until_ready();
  7047. Client cli("localhost", PORT);
  7048. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7052. }
  7053. #ifdef _WIN32
  7054. // Issue #2435: mmap::open() must succeed even when another handle holds
  7055. // the file open for writing (e.g. an active log file).
  7056. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7057. const char *path = "mmap_concurrent_writer_test.txt";
  7058. const char *content = "hello";
  7059. {
  7060. std::ofstream f(path, std::ios::binary);
  7061. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7062. }
  7063. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7064. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7065. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7066. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7067. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7068. detail::mmap m(path);
  7069. ASSERT_TRUE(m.is_open());
  7070. EXPECT_EQ(strlen(content), m.size());
  7071. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7072. }
  7073. #endif
  7074. TEST(KeepAliveTest, ReadTimeout) {
  7075. Server svr;
  7076. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7077. std::this_thread::sleep_for(std::chrono::seconds(2));
  7078. res.set_content("a", "text/plain");
  7079. });
  7080. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7081. res.set_content("b", "text/plain");
  7082. });
  7083. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7084. auto se = detail::scope_exit([&] {
  7085. svr.stop();
  7086. listen_thread.join();
  7087. ASSERT_FALSE(svr.is_running());
  7088. });
  7089. svr.wait_until_ready();
  7090. Client cli("localhost", PORT);
  7091. cli.set_keep_alive(true);
  7092. cli.set_read_timeout(std::chrono::seconds(1));
  7093. auto resa = cli.Get("/a");
  7094. ASSERT_FALSE(resa);
  7095. EXPECT_EQ(Error::Read, resa.error());
  7096. auto resb = cli.Get("/b");
  7097. ASSERT_TRUE(resb);
  7098. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7099. EXPECT_EQ("b", resb->body);
  7100. }
  7101. TEST(KeepAliveTest, MaxCount) {
  7102. size_t keep_alive_max_count = 3;
  7103. Server svr;
  7104. svr.set_keep_alive_max_count(keep_alive_max_count);
  7105. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7106. res.set_content("Hello World!", "text/plain");
  7107. });
  7108. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7109. auto se = detail::scope_exit([&] {
  7110. svr.stop();
  7111. listen_thread.join();
  7112. ASSERT_FALSE(svr.is_running());
  7113. });
  7114. svr.wait_until_ready();
  7115. Client cli(HOST, PORT);
  7116. cli.set_keep_alive(true);
  7117. for (size_t i = 0; i < 5; i++) {
  7118. auto result = cli.Get("/hi");
  7119. ASSERT_TRUE(result);
  7120. EXPECT_EQ(StatusCode::OK_200, result->status);
  7121. if (i == keep_alive_max_count - 1) {
  7122. EXPECT_EQ("close", result->get_header_value("Connection"));
  7123. } else {
  7124. EXPECT_FALSE(result->has_header("Connection"));
  7125. }
  7126. }
  7127. }
  7128. TEST(KeepAliveTest, Issue1041) {
  7129. Server svr;
  7130. svr.set_keep_alive_timeout(3);
  7131. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7132. res.set_content("Hello World!", "text/plain");
  7133. });
  7134. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7135. auto se = detail::scope_exit([&] {
  7136. svr.stop();
  7137. listen_thread.join();
  7138. ASSERT_FALSE(svr.is_running());
  7139. });
  7140. svr.wait_until_ready();
  7141. Client cli(HOST, PORT);
  7142. cli.set_keep_alive(true);
  7143. auto result = cli.Get("/hi");
  7144. ASSERT_TRUE(result);
  7145. EXPECT_EQ(StatusCode::OK_200, result->status);
  7146. std::this_thread::sleep_for(std::chrono::seconds(5));
  7147. result = cli.Get("/hi");
  7148. ASSERT_TRUE(result);
  7149. EXPECT_EQ(StatusCode::OK_200, result->status);
  7150. }
  7151. TEST(KeepAliveTest, Issue1959) {
  7152. Server svr;
  7153. svr.set_keep_alive_timeout(5);
  7154. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7155. res.set_content("a", "text/plain");
  7156. });
  7157. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7158. auto se = detail::scope_exit([&] {
  7159. if (!svr.is_running()) return;
  7160. svr.stop();
  7161. listen_thread.join();
  7162. ASSERT_FALSE(svr.is_running());
  7163. });
  7164. svr.wait_until_ready();
  7165. Client cli("localhost", PORT);
  7166. cli.set_keep_alive(true);
  7167. using namespace std::chrono;
  7168. auto start = steady_clock::now();
  7169. cli.Get("/a");
  7170. svr.stop();
  7171. listen_thread.join();
  7172. auto end = steady_clock::now();
  7173. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7174. EXPECT_LT(elapsed, 5000);
  7175. }
  7176. #ifdef CPPHTTPLIB_SSL_ENABLED
  7177. TEST(KeepAliveTest, SSLClientReconnection) {
  7178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7179. ASSERT_TRUE(svr.is_valid());
  7180. svr.set_keep_alive_timeout(1);
  7181. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7182. res.set_content("Hello World!", "text/plain");
  7183. });
  7184. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7185. auto se = detail::scope_exit([&] {
  7186. svr.stop();
  7187. listen_thread.join();
  7188. ASSERT_FALSE(svr.is_running());
  7189. });
  7190. svr.wait_until_ready();
  7191. SSLClient cli(HOST, PORT);
  7192. cli.enable_server_certificate_verification(false);
  7193. cli.set_keep_alive(true);
  7194. auto result = cli.Get("/hi");
  7195. ASSERT_TRUE(result);
  7196. EXPECT_EQ(StatusCode::OK_200, result->status);
  7197. result = cli.Get("/hi");
  7198. ASSERT_TRUE(result);
  7199. EXPECT_EQ(StatusCode::OK_200, result->status);
  7200. std::this_thread::sleep_for(std::chrono::seconds(2));
  7201. // Recoonect
  7202. result = cli.Get("/hi");
  7203. ASSERT_TRUE(result);
  7204. EXPECT_EQ(StatusCode::OK_200, result->status);
  7205. result = cli.Get("/hi");
  7206. ASSERT_TRUE(result);
  7207. EXPECT_EQ(StatusCode::OK_200, result->status);
  7208. }
  7209. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7211. ASSERT_TRUE(svr.is_valid());
  7212. svr.set_keep_alive_timeout(1);
  7213. std::string content = "reconnect";
  7214. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7215. res.set_content("Hello World!", "text/plain");
  7216. });
  7217. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7218. auto se = detail::scope_exit([&] {
  7219. svr.stop();
  7220. listen_thread.join();
  7221. ASSERT_FALSE(svr.is_running());
  7222. });
  7223. svr.wait_until_ready();
  7224. SSLClient cli(HOST, PORT);
  7225. cli.enable_server_certificate_verification(false);
  7226. cli.set_keep_alive(true);
  7227. auto result = cli.Post(
  7228. "/hi", content.size(),
  7229. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7230. sink.write(content.c_str(), content.size());
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(result);
  7235. EXPECT_EQ(200, result->status);
  7236. std::this_thread::sleep_for(std::chrono::seconds(2));
  7237. // Recoonect
  7238. result = cli.Post(
  7239. "/hi", content.size(),
  7240. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7241. sink.write(content.c_str(), content.size());
  7242. return true;
  7243. },
  7244. "text/plain");
  7245. ASSERT_TRUE(result);
  7246. EXPECT_EQ(200, result->status);
  7247. result = cli.Post(
  7248. "/hi", content.size(),
  7249. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7250. sink.write(content.c_str(), content.size());
  7251. return true;
  7252. },
  7253. "text/plain");
  7254. ASSERT_TRUE(result);
  7255. EXPECT_EQ(200, result->status);
  7256. }
  7257. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7258. using namespace httplib::tls;
  7259. {
  7260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7261. ASSERT_TRUE(svr.is_valid());
  7262. svr.Get("/sni", [&](const Request &req, Response &res) {
  7263. std::string expected = req.sni();
  7264. EXPECT_EQ(expected, req.get_param_value("expected"));
  7265. res.set_content("ok", "text/plain");
  7266. });
  7267. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7268. auto se = detail::scope_exit([&] {
  7269. svr.stop();
  7270. listen_thread.join();
  7271. ASSERT_FALSE(svr.is_running());
  7272. });
  7273. svr.wait_until_ready();
  7274. {
  7275. SSLClient cli("localhost", PORT);
  7276. cli.enable_server_certificate_verification(false);
  7277. auto res = cli.Get("/sni?expected=localhost");
  7278. ASSERT_TRUE(res);
  7279. }
  7280. {
  7281. SSLClient cli("::1", PORT);
  7282. cli.enable_server_certificate_verification(false);
  7283. auto res = cli.Get("/sni?expected=");
  7284. // NOTE: This may fail if the server is listening on IPv4 only
  7285. // (e.g., when localhost resolves to 127.0.0.1 only)
  7286. if (res) {
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. } else {
  7289. EXPECT_EQ(Error::Connection, res.error());
  7290. }
  7291. }
  7292. }
  7293. }
  7294. #endif
  7295. TEST(ClientProblemDetectionTest, ContentProvider) {
  7296. Server svr;
  7297. size_t content_length = 1024 * 1024;
  7298. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7299. res.set_content_provider(
  7300. content_length, "text/plain",
  7301. [&](size_t offset, size_t length, DataSink &sink) {
  7302. auto out_len = std::min(length, static_cast<size_t>(1024));
  7303. std::string out(out_len, '@');
  7304. sink.write(out.data(), out_len);
  7305. return offset < 4096;
  7306. },
  7307. [](bool success) { ASSERT_FALSE(success); });
  7308. });
  7309. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7310. res.set_content_provider(
  7311. 0, "text/plain",
  7312. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7313. EXPECT_TRUE(false);
  7314. return true;
  7315. },
  7316. [](bool success) { ASSERT_FALSE(success); });
  7317. });
  7318. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7319. auto se = detail::scope_exit([&] {
  7320. svr.stop();
  7321. listen_thread.join();
  7322. ASSERT_FALSE(svr.is_running());
  7323. });
  7324. svr.wait_until_ready();
  7325. Client cli("localhost", PORT);
  7326. {
  7327. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7328. size_t /*data_length*/) { return false; });
  7329. ASSERT_FALSE(res);
  7330. }
  7331. {
  7332. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7333. size_t /*data_length*/) { return false; });
  7334. ASSERT_TRUE(res);
  7335. }
  7336. }
  7337. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7338. Server svr;
  7339. svr.set_error_handler([](Request const &, Response &res) -> void {
  7340. res.set_chunked_content_provider(
  7341. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7342. sink.os << "hello";
  7343. sink.os << "world";
  7344. sink.done();
  7345. return true;
  7346. });
  7347. });
  7348. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7349. auto se = detail::scope_exit([&] {
  7350. svr.stop();
  7351. listen_thread.join();
  7352. ASSERT_FALSE(svr.is_running());
  7353. });
  7354. svr.wait_until_ready();
  7355. Client cli("localhost", PORT);
  7356. auto res = cli.Get("/");
  7357. ASSERT_TRUE(res);
  7358. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7359. EXPECT_EQ("helloworld", res->body);
  7360. }
  7361. TEST(LongPollingTest, ClientCloseDetection) {
  7362. Server svr;
  7363. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7364. res.set_chunked_content_provider(
  7365. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7366. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7367. sink.os << "hello";
  7368. auto count = 10;
  7369. while (count > 0 && sink.is_writable()) {
  7370. this_thread::sleep_for(chrono::milliseconds(10));
  7371. count--;
  7372. }
  7373. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7374. return true;
  7375. });
  7376. });
  7377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7378. auto se = detail::scope_exit([&] {
  7379. svr.stop();
  7380. listen_thread.join();
  7381. ASSERT_FALSE(svr.is_running());
  7382. });
  7383. svr.wait_until_ready();
  7384. Client cli("localhost", PORT);
  7385. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7386. EXPECT_EQ("hello", string(data, data_length));
  7387. return false; // close the socket immediately.
  7388. });
  7389. ASSERT_FALSE(res);
  7390. }
  7391. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7392. Server svr;
  7393. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7394. res.set_chunked_content_provider(
  7395. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7396. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7397. sink.os << "hello";
  7398. EXPECT_TRUE(sink.os.good());
  7399. // Wait for the client to close the connection
  7400. auto count = 10;
  7401. while (count > 0 && sink.is_writable()) {
  7402. this_thread::sleep_for(chrono::milliseconds(10));
  7403. count--;
  7404. }
  7405. // After client disconnect, write repeatedly until the socket
  7406. // write actually fails (small writes may be absorbed by the
  7407. // kernel buffer)
  7408. std::string chunk(1024, 'x');
  7409. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7410. sink.os << chunk;
  7411. }
  7412. EXPECT_TRUE(sink.os.fail());
  7413. return true;
  7414. });
  7415. });
  7416. auto port = svr.bind_to_any_port("localhost");
  7417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7418. auto se = detail::scope_exit([&] {
  7419. svr.stop();
  7420. listen_thread.join();
  7421. ASSERT_FALSE(svr.is_running());
  7422. });
  7423. svr.wait_until_ready();
  7424. Client cli("localhost", port);
  7425. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7426. EXPECT_EQ("hello", string(data, data_length));
  7427. return false; // close the socket immediately.
  7428. });
  7429. ASSERT_FALSE(res);
  7430. }
  7431. TEST(GetWithParametersTest, GetWithParameters) {
  7432. Server svr;
  7433. svr.Get("/", [&](const Request &req, Response &) {
  7434. EXPECT_EQ("world", req.get_param_value("hello"));
  7435. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7436. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7437. });
  7438. svr.Get("/params", [&](const Request &req, Response &) {
  7439. EXPECT_EQ("world", req.get_param_value("hello"));
  7440. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7441. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7442. });
  7443. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7444. EXPECT_EQ("resource-id", req.matches[1]);
  7445. EXPECT_EQ("foo", req.get_param_value("param1"));
  7446. EXPECT_EQ("bar", req.get_param_value("param2"));
  7447. });
  7448. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7449. EXPECT_EQ("user-id", req.path_params.at("id"));
  7450. EXPECT_EQ("foo", req.get_param_value("param1"));
  7451. EXPECT_EQ("bar", req.get_param_value("param2"));
  7452. });
  7453. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7454. auto se = detail::scope_exit([&] {
  7455. svr.stop();
  7456. listen_thread.join();
  7457. ASSERT_FALSE(svr.is_running());
  7458. });
  7459. svr.wait_until_ready();
  7460. {
  7461. Client cli(HOST, PORT);
  7462. Params params;
  7463. params.emplace("hello", "world");
  7464. params.emplace("hello2", "world2");
  7465. params.emplace("hello3", "world3");
  7466. auto res = cli.Get("/", params, Headers{});
  7467. ASSERT_TRUE(res);
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. }
  7470. {
  7471. Client cli(HOST, PORT);
  7472. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7473. ASSERT_TRUE(res);
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. }
  7476. {
  7477. Client cli(HOST, PORT);
  7478. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7479. ASSERT_TRUE(res);
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. {
  7483. Client cli(HOST, PORT);
  7484. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7485. ASSERT_TRUE(res);
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. }
  7488. }
  7489. TEST(GetWithParametersTest, GetWithParameters2) {
  7490. Server svr;
  7491. svr.Get("/", [&](const Request &req, Response &res) {
  7492. auto text = req.get_param_value("hello");
  7493. res.set_content(text, "text/plain");
  7494. });
  7495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7496. auto se = detail::scope_exit([&] {
  7497. svr.stop();
  7498. listen_thread.join();
  7499. ASSERT_FALSE(svr.is_running());
  7500. });
  7501. svr.wait_until_ready();
  7502. Client cli("localhost", PORT);
  7503. Params params;
  7504. params.emplace("hello", "world");
  7505. std::string body;
  7506. auto res = cli.Get("/", params, Headers{},
  7507. [&](const char *data, size_t data_length) {
  7508. body.append(data, data_length);
  7509. return true;
  7510. });
  7511. ASSERT_TRUE(res);
  7512. EXPECT_EQ(StatusCode::OK_200, res->status);
  7513. EXPECT_EQ("world", body);
  7514. }
  7515. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7516. auto host = "httpbingo.org";
  7517. auto path = std::string{"/range/32"};
  7518. #ifdef CPPHTTPLIB_SSL_ENABLED
  7519. SSLClient cli(host);
  7520. #else
  7521. Client cli(host);
  7522. #endif
  7523. cli.set_default_headers({make_range_header({{1, 10}})});
  7524. cli.set_connection_timeout(5);
  7525. {
  7526. auto res = cli.Get(path);
  7527. ASSERT_TRUE(res);
  7528. EXPECT_EQ("bcdefghijk", res->body);
  7529. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7530. }
  7531. {
  7532. auto res = cli.Get(path);
  7533. ASSERT_TRUE(res);
  7534. EXPECT_EQ("bcdefghijk", res->body);
  7535. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7536. }
  7537. }
  7538. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7539. Server svr;
  7540. svr.set_default_headers({{"Hello", "World"}});
  7541. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7542. res.set_content("ok", "text/plain");
  7543. });
  7544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7545. auto se = detail::scope_exit([&] {
  7546. svr.stop();
  7547. listen_thread.join();
  7548. ASSERT_FALSE(svr.is_running());
  7549. });
  7550. svr.wait_until_ready();
  7551. Client cli("localhost", PORT);
  7552. auto res = cli.Get("/");
  7553. ASSERT_TRUE(res);
  7554. EXPECT_EQ(StatusCode::OK_200, res->status);
  7555. EXPECT_EQ("ok", res->body);
  7556. EXPECT_EQ("World", res->get_header_value("Hello"));
  7557. }
  7558. #ifdef CPPHTTPLIB_SSL_ENABLED
  7559. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7561. ASSERT_TRUE(svr.is_valid());
  7562. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7563. std::this_thread::sleep_for(std::chrono::seconds(2));
  7564. res.set_content("a", "text/plain");
  7565. });
  7566. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7567. res.set_content("b", "text/plain");
  7568. });
  7569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7570. auto se = detail::scope_exit([&] {
  7571. svr.stop();
  7572. listen_thread.join();
  7573. ASSERT_FALSE(svr.is_running());
  7574. });
  7575. svr.wait_until_ready();
  7576. SSLClient cli("localhost", PORT);
  7577. cli.enable_server_certificate_verification(false);
  7578. cli.set_keep_alive(true);
  7579. cli.set_read_timeout(std::chrono::seconds(1));
  7580. auto resa = cli.Get("/a");
  7581. ASSERT_TRUE(!resa);
  7582. EXPECT_EQ(Error::Read, resa.error());
  7583. auto resb = cli.Get("/b");
  7584. ASSERT_TRUE(resb);
  7585. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7586. EXPECT_EQ("b", resb->body);
  7587. }
  7588. #endif
  7589. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7590. protected:
  7591. ServerTestWithAI_PASSIVE()
  7592. : cli_(HOST, PORT)
  7593. #ifdef CPPHTTPLIB_SSL_ENABLED
  7594. ,
  7595. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7596. #endif
  7597. {
  7598. #ifdef CPPHTTPLIB_SSL_ENABLED
  7599. cli_.enable_server_certificate_verification(false);
  7600. #endif
  7601. }
  7602. virtual void SetUp() {
  7603. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7604. res.set_content("Hello World!", "text/plain");
  7605. });
  7606. t_ = thread(
  7607. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7608. svr_.wait_until_ready();
  7609. }
  7610. virtual void TearDown() {
  7611. svr_.stop();
  7612. t_.join();
  7613. }
  7614. #ifdef CPPHTTPLIB_SSL_ENABLED
  7615. SSLClient cli_;
  7616. SSLServer svr_;
  7617. #else
  7618. Client cli_;
  7619. Server svr_;
  7620. #endif
  7621. thread t_;
  7622. };
  7623. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7624. auto res = cli_.Get("/hi");
  7625. ASSERT_TRUE(res);
  7626. EXPECT_EQ(StatusCode::OK_200, res->status);
  7627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7628. EXPECT_EQ("Hello World!", res->body);
  7629. }
  7630. class ServerUpDownTest : public ::testing::Test {
  7631. protected:
  7632. ServerUpDownTest() : cli_(HOST, PORT) {}
  7633. virtual void SetUp() {
  7634. t_ = thread([&]() {
  7635. svr_.bind_to_any_port(HOST);
  7636. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7637. ASSERT_TRUE(svr_.listen_after_bind());
  7638. });
  7639. svr_.wait_until_ready();
  7640. }
  7641. virtual void TearDown() {
  7642. svr_.stop();
  7643. t_.join();
  7644. }
  7645. Client cli_;
  7646. Server svr_;
  7647. thread t_;
  7648. };
  7649. TEST_F(ServerUpDownTest, QuickStartStop) {
  7650. // Should not crash, especially when run with
  7651. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7652. }
  7653. class PayloadMaxLengthTest : public ::testing::Test {
  7654. protected:
  7655. PayloadMaxLengthTest()
  7656. : cli_(HOST, PORT)
  7657. #ifdef CPPHTTPLIB_SSL_ENABLED
  7658. ,
  7659. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7660. #endif
  7661. {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. cli_.enable_server_certificate_verification(false);
  7664. #endif
  7665. }
  7666. virtual void SetUp() {
  7667. svr_.set_payload_max_length(8);
  7668. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7669. res.set_content("test", "text/plain");
  7670. });
  7671. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7672. svr_.wait_until_ready();
  7673. }
  7674. virtual void TearDown() {
  7675. svr_.stop();
  7676. t_.join();
  7677. }
  7678. #ifdef CPPHTTPLIB_SSL_ENABLED
  7679. SSLClient cli_;
  7680. SSLServer svr_;
  7681. #else
  7682. Client cli_;
  7683. Server svr_;
  7684. #endif
  7685. thread t_;
  7686. };
  7687. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7688. auto res = cli_.Post("/test", "123456789", "text/plain");
  7689. ASSERT_TRUE(res);
  7690. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7691. res = cli_.Post("/test", "12345678", "text/plain");
  7692. ASSERT_TRUE(res);
  7693. EXPECT_EQ(StatusCode::OK_200, res->status);
  7694. }
  7695. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7696. // Test chunked encoding with payload exceeding the 8-byte limit
  7697. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7698. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7699. ASSERT_TRUE(res);
  7700. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7701. }
  7702. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7703. // Test chunked encoding with payload within the 8-byte limit
  7704. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7705. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7706. ASSERT_TRUE(res);
  7707. EXPECT_EQ(StatusCode::OK_200, res->status);
  7708. }
  7709. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7710. // Test using send_request to send chunked data exceeding payload limit
  7711. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7712. "Host: " +
  7713. std::string(HOST) + ":" + std::to_string(PORT) +
  7714. "\r\n"
  7715. "Transfer-Encoding: chunked\r\n"
  7716. "Connection: close\r\n"
  7717. "\r\n"
  7718. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7719. "0123456789\r\n"
  7720. "0\r\n" // End chunk
  7721. "\r\n";
  7722. std::string response;
  7723. bool result = send_request(1, chunked_request, &response);
  7724. if (!result) {
  7725. // If send_request fails, it might be because the server closed the
  7726. // connection due to payload limit enforcement, which is acceptable
  7727. SUCCEED()
  7728. << "Server rejected oversized chunked request (connection closed)";
  7729. } else {
  7730. // If we got a response, check if it's an error response or connection was
  7731. // closed early Short response length indicates connection was closed due to
  7732. // payload limit
  7733. if (response.length() <= 10) {
  7734. SUCCEED() << "Server closed connection for oversized chunked request";
  7735. } else {
  7736. // Check for error status codes
  7737. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7738. response.find("Payload Too Large") != std::string::npos ||
  7739. response.find("400") != std::string::npos);
  7740. }
  7741. }
  7742. }
  7743. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7744. // Test request without Content-Length header exceeding payload limit
  7745. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7746. "Host: " +
  7747. std::string(HOST) + ":" +
  7748. std::to_string(PORT) +
  7749. "\r\n"
  7750. "Connection: close\r\n"
  7751. "\r\n";
  7752. // Add payload exceeding the 8-byte limit
  7753. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7754. request_without_content_length += large_payload;
  7755. std::string response;
  7756. bool result = send_request(1, request_without_content_length, &response);
  7757. if (!result) {
  7758. // If send_request fails, server likely closed connection due to payload
  7759. // limit
  7760. SUCCEED() << "Server rejected oversized request without Content-Length "
  7761. "(connection closed)";
  7762. } else {
  7763. // Check if server responded with error or closed connection early
  7764. if (response.length() <= 10) {
  7765. SUCCEED() << "Server closed connection for oversized request without "
  7766. "Content-Length";
  7767. } else {
  7768. // Check for error status codes
  7769. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7770. response.find("Payload Too Large") != std::string::npos ||
  7771. response.find("400") != std::string::npos);
  7772. }
  7773. }
  7774. }
  7775. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7776. // Test request without Content-Length header within payload limit
  7777. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7778. "Host: " +
  7779. std::string(HOST) + ":" +
  7780. std::to_string(PORT) +
  7781. "\r\n"
  7782. "Connection: close\r\n"
  7783. "\r\n";
  7784. // Add payload within the 8-byte limit
  7785. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7786. request_without_content_length += small_payload;
  7787. std::string response;
  7788. bool result = send_request(1, request_without_content_length, &response);
  7789. // For requests without Content-Length, the server may have different behavior
  7790. // The key is that it should not reject due to payload limit for small
  7791. // payloads
  7792. if (result) {
  7793. // Check for any HTTP response (success or error, but not connection closed)
  7794. if (response.length() > 10) {
  7795. SUCCEED()
  7796. << "Server processed request without Content-Length within limit";
  7797. } else {
  7798. // Short response might indicate connection closed, which is acceptable
  7799. SUCCEED() << "Server closed connection for request without "
  7800. "Content-Length (acceptable behavior)";
  7801. }
  7802. } else {
  7803. // Connection failure might be due to protocol requirements
  7804. SUCCEED() << "Connection issue with request without Content-Length "
  7805. "(environment-specific)";
  7806. }
  7807. }
  7808. class LargePayloadMaxLengthTest : public ::testing::Test {
  7809. protected:
  7810. LargePayloadMaxLengthTest()
  7811. : cli_(HOST, PORT)
  7812. #ifdef CPPHTTPLIB_SSL_ENABLED
  7813. ,
  7814. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7815. #endif
  7816. {
  7817. #ifdef CPPHTTPLIB_SSL_ENABLED
  7818. cli_.enable_server_certificate_verification(false);
  7819. #endif
  7820. }
  7821. virtual void SetUp() {
  7822. // Set 10MB payload limit
  7823. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7824. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7825. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7826. res.set_content("Large payload test", "text/plain");
  7827. });
  7828. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7829. svr_.wait_until_ready();
  7830. }
  7831. virtual void TearDown() {
  7832. svr_.stop();
  7833. t_.join();
  7834. }
  7835. #ifdef CPPHTTPLIB_SSL_ENABLED
  7836. SSLClient cli_;
  7837. SSLServer svr_;
  7838. #else
  7839. Client cli_;
  7840. Server svr_;
  7841. #endif
  7842. thread t_;
  7843. };
  7844. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7845. // Test chunked encoding with payload within 10MB limit
  7846. std::string medium_payload(5 * 1024 * 1024,
  7847. 'A'); // 5MB payload, within 10MB limit
  7848. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7849. ASSERT_TRUE(res);
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. }
  7852. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7853. // Test chunked encoding with payload exceeding 10MB limit
  7854. std::string large_payload(12 * 1024 * 1024,
  7855. 'B'); // 12MB payload, exceeds 10MB limit
  7856. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7857. // Server may either return 413 or close the connection
  7858. if (res) {
  7859. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7860. } else {
  7861. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7862. }
  7863. }
  7864. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7865. // Test request without Content-Length header within 10MB limit
  7866. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7867. "Host: " +
  7868. std::string(HOST) + ":" +
  7869. std::to_string(PORT) +
  7870. "\r\n"
  7871. "Connection: close\r\n"
  7872. "\r\n";
  7873. // Add 1MB payload (within 10MB limit)
  7874. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7875. request_without_content_length += medium_payload;
  7876. std::string response;
  7877. bool result = send_request(5, request_without_content_length, &response);
  7878. if (result) {
  7879. // Should get a proper HTTP response for payloads within limit
  7880. if (response.length() > 10) {
  7881. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7882. "10MB limit";
  7883. } else {
  7884. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7885. "Content-Length)";
  7886. }
  7887. } else {
  7888. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7889. }
  7890. }
  7891. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7892. // Test request without Content-Length header exceeding 10MB limit
  7893. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7894. "Host: " +
  7895. std::string(HOST) + ":" +
  7896. std::to_string(PORT) +
  7897. "\r\n"
  7898. "Connection: close\r\n"
  7899. "\r\n";
  7900. // Add 12MB payload (exceeds 10MB limit)
  7901. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7902. request_without_content_length += large_payload;
  7903. std::string response;
  7904. bool result = send_request(10, request_without_content_length, &response);
  7905. if (!result) {
  7906. // Server should close connection due to payload limit
  7907. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7908. "(connection closed)";
  7909. } else {
  7910. // Check for error response
  7911. if (response.length() <= 10) {
  7912. SUCCEED()
  7913. << "Server closed connection for 12MB request exceeding 10MB limit";
  7914. } else {
  7915. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7916. response.find("Payload Too Large") != std::string::npos ||
  7917. response.find("400") != std::string::npos);
  7918. }
  7919. }
  7920. }
  7921. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7922. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7923. // path.
  7924. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7925. Server svr;
  7926. const size_t LIMIT = 64 * 1024; // 64KB
  7927. svr.set_payload_max_length(LIMIT);
  7928. size_t total = 0;
  7929. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7930. const ContentReader &content_reader) {
  7931. content_reader([&](const char * /*data*/, size_t len) {
  7932. total += len;
  7933. return true;
  7934. });
  7935. res.status = 200;
  7936. res.set_content("stream_ok", "text/plain");
  7937. });
  7938. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7939. auto se = detail::scope_exit([&] {
  7940. svr.stop();
  7941. thread.join();
  7942. ASSERT_FALSE(svr.is_running());
  7943. });
  7944. svr.wait_until_ready();
  7945. // Prepare 256KB raw data and gzip-compress it
  7946. std::string raw(256 * 1024, 'A');
  7947. std::string gz;
  7948. {
  7949. z_stream zs{};
  7950. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7951. Z_DEFAULT_STRATEGY);
  7952. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7953. zs.avail_in = static_cast<uInt>(raw.size());
  7954. char outbuf[4096];
  7955. int ret;
  7956. do {
  7957. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7958. zs.avail_out = sizeof(outbuf);
  7959. ret = deflate(&zs, Z_FINISH);
  7960. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7961. } while (ret != Z_STREAM_END);
  7962. deflateEnd(&zs);
  7963. }
  7964. Client cli(HOST, PORT);
  7965. cli.set_connection_timeout(std::chrono::seconds(5));
  7966. Headers headers = {{"Content-Encoding", "gzip"}};
  7967. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7968. "application/octet-stream");
  7969. ASSERT_TRUE(res);
  7970. // Server must reject oversized decompressed payloads with 413.
  7971. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7972. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7973. EXPECT_LE(total, LIMIT);
  7974. }
  7975. #endif
  7976. // Regression test for DoS vulnerability: a malicious server sending a response
  7977. // without Content-Length header must not cause unbounded memory consumption on
  7978. // the client side. The client should stop reading after a reasonable limit,
  7979. // similar to the server-side set_payload_max_length protection.
  7980. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7981. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7982. #ifndef _WIN32
  7983. signal(SIGPIPE, SIG_IGN);
  7984. #endif
  7985. auto server_thread = std::thread([] {
  7986. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7987. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7988. default_socket_options(srv);
  7989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7991. sockaddr_in addr{};
  7992. addr.sin_family = AF_INET;
  7993. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7994. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7995. int opt = 1;
  7996. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7997. #ifdef _WIN32
  7998. reinterpret_cast<const char *>(&opt),
  7999. #else
  8000. &opt,
  8001. #endif
  8002. sizeof(opt));
  8003. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8004. ::listen(srv, 1);
  8005. sockaddr_in cli_addr{};
  8006. socklen_t cli_len = sizeof(cli_addr);
  8007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8008. if (cli != INVALID_SOCKET) {
  8009. char buf[4096];
  8010. ::recv(cli, buf, sizeof(buf), 0);
  8011. // Malicious response: no Content-Length, no chunked encoding
  8012. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8013. "Connection: close\r\n"
  8014. "\r\n";
  8015. ::send(cli,
  8016. #ifdef _WIN32
  8017. static_cast<const char *>(response_header.c_str()),
  8018. static_cast<int>(response_header.size()),
  8019. #else
  8020. response_header.c_str(), response_header.size(),
  8021. #endif
  8022. 0);
  8023. // Send 10MB of data
  8024. std::string chunk(64 * 1024, 'A');
  8025. size_t total_sent = 0;
  8026. while (total_sent < MALICIOUS_DATA_SIZE) {
  8027. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8028. auto sent = ::send(cli,
  8029. #ifdef _WIN32
  8030. static_cast<const char *>(chunk.c_str()),
  8031. static_cast<int>(to_send),
  8032. #else
  8033. chunk.c_str(), to_send,
  8034. #endif
  8035. 0);
  8036. if (sent <= 0) break;
  8037. total_sent += static_cast<size_t>(sent);
  8038. }
  8039. detail::close_socket(cli);
  8040. }
  8041. detail::close_socket(srv);
  8042. });
  8043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8044. size_t total_read = 0;
  8045. {
  8046. Client cli("127.0.0.1", PORT + 2);
  8047. cli.set_read_timeout(5, 0);
  8048. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8049. auto stream = cli.open_stream("GET", "/malicious");
  8050. ASSERT_TRUE(stream.is_valid());
  8051. char buffer[64 * 1024];
  8052. ssize_t n;
  8053. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8054. total_read += static_cast<size_t>(n);
  8055. }
  8056. } // StreamHandle and Client destroyed here, closing the socket
  8057. server_thread.join();
  8058. // With set_payload_max_length, the client must stop reading before consuming
  8059. // all 10MB. The read loop should be cut off at or near the configured limit.
  8060. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8061. << "Client read " << total_read << " bytes, exceeding the configured "
  8062. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8063. }
  8064. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8065. // the entire response body without truncation.
  8066. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8067. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8068. #ifndef _WIN32
  8069. signal(SIGPIPE, SIG_IGN);
  8070. #endif
  8071. auto server_thread = std::thread([] {
  8072. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8073. default_socket_options(srv);
  8074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8075. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8076. sockaddr_in addr{};
  8077. addr.sin_family = AF_INET;
  8078. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8080. int opt = 1;
  8081. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8082. #ifdef _WIN32
  8083. reinterpret_cast<const char *>(&opt),
  8084. #else
  8085. &opt,
  8086. #endif
  8087. sizeof(opt));
  8088. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8089. ::listen(srv, 1);
  8090. sockaddr_in cli_addr{};
  8091. socklen_t cli_len = sizeof(cli_addr);
  8092. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8093. if (cli != INVALID_SOCKET) {
  8094. char buf[4096];
  8095. ::recv(cli, buf, sizeof(buf), 0);
  8096. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8097. "Connection: close\r\n"
  8098. "\r\n";
  8099. ::send(cli,
  8100. #ifdef _WIN32
  8101. static_cast<const char *>(response_header.c_str()),
  8102. static_cast<int>(response_header.size()),
  8103. #else
  8104. response_header.c_str(), response_header.size(),
  8105. #endif
  8106. 0);
  8107. std::string chunk(64 * 1024, 'A');
  8108. size_t total_sent = 0;
  8109. while (total_sent < DATA_SIZE) {
  8110. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8111. auto sent = ::send(cli,
  8112. #ifdef _WIN32
  8113. static_cast<const char *>(chunk.c_str()),
  8114. static_cast<int>(to_send),
  8115. #else
  8116. chunk.c_str(), to_send,
  8117. #endif
  8118. 0);
  8119. if (sent <= 0) break;
  8120. total_sent += static_cast<size_t>(sent);
  8121. }
  8122. #ifdef _WIN32
  8123. ::shutdown(cli, SD_SEND);
  8124. #else
  8125. ::shutdown(cli, SHUT_WR);
  8126. #endif
  8127. // Drain until the client closes its end, ensuring all data is delivered
  8128. char drain[1024];
  8129. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8130. detail::close_socket(cli);
  8131. }
  8132. detail::close_socket(srv);
  8133. });
  8134. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8135. size_t total_read = 0;
  8136. {
  8137. Client cli("127.0.0.1", PORT + 2);
  8138. cli.set_read_timeout(5, 0);
  8139. cli.set_payload_max_length(0); // 0 means no limit
  8140. auto stream = cli.open_stream("GET", "/data");
  8141. ASSERT_TRUE(stream.is_valid());
  8142. char buffer[64 * 1024];
  8143. ssize_t n;
  8144. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8145. total_read += static_cast<size_t>(n);
  8146. }
  8147. }
  8148. server_thread.join();
  8149. EXPECT_EQ(total_read, DATA_SIZE)
  8150. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8151. << " bytes without truncation, but only read " << total_read << " bytes.";
  8152. }
  8153. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8154. // enormous Content-Length must not cause the client to pre-allocate a huge
  8155. // response body buffer. The reservation is capped at payload_max_length_, and
  8156. // the read itself fails when the body exceeds the limit.
  8157. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8158. #ifndef _WIN32
  8159. signal(SIGPIPE, SIG_IGN);
  8160. #endif
  8161. auto server_thread = std::thread([] {
  8162. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8163. default_socket_options(srv);
  8164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8166. sockaddr_in addr{};
  8167. addr.sin_family = AF_INET;
  8168. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8169. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8170. int opt = 1;
  8171. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8172. #ifdef _WIN32
  8173. reinterpret_cast<const char *>(&opt),
  8174. #else
  8175. &opt,
  8176. #endif
  8177. sizeof(opt));
  8178. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8179. ::listen(srv, 1);
  8180. sockaddr_in cli_addr{};
  8181. socklen_t cli_len = sizeof(cli_addr);
  8182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8183. if (cli != INVALID_SOCKET) {
  8184. char buf[4096];
  8185. ::recv(cli, buf, sizeof(buf), 0);
  8186. // Malicious response: claim a 20GB body but send only a tiny payload.
  8187. std::string response = "HTTP/1.1 200 OK\r\n"
  8188. "Content-Length: 20000000000\r\n"
  8189. "\r\n"
  8190. "abc";
  8191. ::send(cli,
  8192. #ifdef _WIN32
  8193. static_cast<const char *>(response.c_str()),
  8194. static_cast<int>(response.size()),
  8195. #else
  8196. response.c_str(), response.size(),
  8197. #endif
  8198. 0);
  8199. detail::close_socket(cli);
  8200. }
  8201. detail::close_socket(srv);
  8202. });
  8203. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8204. {
  8205. Client cli("127.0.0.1", PORT + 2);
  8206. cli.set_read_timeout(5, 0);
  8207. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8208. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8209. // (server claims more bytes than payload_max_length permits), but it must
  8210. // not exhaust memory before getting there.
  8211. auto res = cli.Get("/malicious");
  8212. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8213. }
  8214. server_thread.join();
  8215. }
  8216. // Verify that content_receiver bypasses the default payload_max_length,
  8217. // allowing streaming downloads larger than 100MB without requiring an explicit
  8218. // set_payload_max_length call.
  8219. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8220. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8221. #ifndef _WIN32
  8222. signal(SIGPIPE, SIG_IGN);
  8223. #endif
  8224. auto server_thread = std::thread([] {
  8225. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8226. default_socket_options(srv);
  8227. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8228. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8229. sockaddr_in addr{};
  8230. addr.sin_family = AF_INET;
  8231. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8232. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8233. int opt = 1;
  8234. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8235. #ifdef _WIN32
  8236. reinterpret_cast<const char *>(&opt),
  8237. #else
  8238. &opt,
  8239. #endif
  8240. sizeof(opt));
  8241. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8242. ::listen(srv, 1);
  8243. sockaddr_in cli_addr{};
  8244. socklen_t cli_len = sizeof(cli_addr);
  8245. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8246. if (cli != INVALID_SOCKET) {
  8247. char buf[4096];
  8248. ::recv(cli, buf, sizeof(buf), 0);
  8249. // Response with Content-Length larger than default 100MB limit
  8250. auto content_length = std::to_string(DATA_SIZE);
  8251. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8252. "Content-Length: " +
  8253. content_length +
  8254. "\r\n"
  8255. "Connection: close\r\n"
  8256. "\r\n";
  8257. ::send(cli,
  8258. #ifdef _WIN32
  8259. static_cast<const char *>(response_header.c_str()),
  8260. static_cast<int>(response_header.size()),
  8261. #else
  8262. response_header.c_str(), response_header.size(),
  8263. #endif
  8264. 0);
  8265. std::string chunk(64 * 1024, 'A');
  8266. size_t total_sent = 0;
  8267. while (total_sent < DATA_SIZE) {
  8268. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8269. auto sent = ::send(cli,
  8270. #ifdef _WIN32
  8271. static_cast<const char *>(chunk.c_str()),
  8272. static_cast<int>(to_send),
  8273. #else
  8274. chunk.c_str(), to_send,
  8275. #endif
  8276. 0);
  8277. if (sent <= 0) break;
  8278. total_sent += static_cast<size_t>(sent);
  8279. }
  8280. detail::close_socket(cli);
  8281. }
  8282. detail::close_socket(srv);
  8283. });
  8284. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8285. size_t total_received = 0;
  8286. {
  8287. Client cli("127.0.0.1", PORT + 2);
  8288. cli.set_read_timeout(10, 0);
  8289. // Do NOT call set_payload_max_length — use the default 100MB limit
  8290. auto res =
  8291. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8292. total_received += data_length;
  8293. return true;
  8294. });
  8295. ASSERT_TRUE(res);
  8296. EXPECT_EQ(StatusCode::OK_200, res->status);
  8297. }
  8298. server_thread.join();
  8299. EXPECT_EQ(total_received, DATA_SIZE)
  8300. << "With content_receiver, the client should read all " << DATA_SIZE
  8301. << " bytes despite the default 100MB payload_max_length, but only read "
  8302. << total_received << " bytes.";
  8303. }
  8304. // Verify that an explicit set_payload_max_length smaller than the response is
  8305. // enforced even when a content_receiver is used.
  8306. TEST(ClientVulnerabilityTest,
  8307. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8308. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8309. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8310. #ifndef _WIN32
  8311. signal(SIGPIPE, SIG_IGN);
  8312. #endif
  8313. auto server_thread = std::thread([] {
  8314. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8315. default_socket_options(srv);
  8316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8317. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8318. sockaddr_in addr{};
  8319. addr.sin_family = AF_INET;
  8320. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8321. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8322. int opt = 1;
  8323. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8324. #ifdef _WIN32
  8325. reinterpret_cast<const char *>(&opt),
  8326. #else
  8327. &opt,
  8328. #endif
  8329. sizeof(opt));
  8330. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8331. ::listen(srv, 1);
  8332. sockaddr_in cli_addr{};
  8333. socklen_t cli_len = sizeof(cli_addr);
  8334. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8335. if (cli != INVALID_SOCKET) {
  8336. char buf[4096];
  8337. ::recv(cli, buf, sizeof(buf), 0);
  8338. auto content_length = std::to_string(DATA_SIZE);
  8339. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8340. "Content-Length: " +
  8341. content_length +
  8342. "\r\n"
  8343. "Connection: close\r\n"
  8344. "\r\n";
  8345. ::send(cli,
  8346. #ifdef _WIN32
  8347. static_cast<const char *>(response_header.c_str()),
  8348. static_cast<int>(response_header.size()),
  8349. #else
  8350. response_header.c_str(), response_header.size(),
  8351. #endif
  8352. 0);
  8353. std::string chunk(64 * 1024, 'A');
  8354. size_t total_sent = 0;
  8355. while (total_sent < DATA_SIZE) {
  8356. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8357. auto sent = ::send(cli,
  8358. #ifdef _WIN32
  8359. static_cast<const char *>(chunk.c_str()),
  8360. static_cast<int>(to_send),
  8361. #else
  8362. chunk.c_str(), to_send,
  8363. #endif
  8364. 0);
  8365. if (sent <= 0) break;
  8366. total_sent += static_cast<size_t>(sent);
  8367. }
  8368. detail::close_socket(cli);
  8369. }
  8370. detail::close_socket(srv);
  8371. });
  8372. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8373. size_t total_received = 0;
  8374. {
  8375. Client cli("127.0.0.1", PORT + 2);
  8376. cli.set_read_timeout(10, 0);
  8377. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8378. auto res =
  8379. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8380. total_received += data_length;
  8381. return true;
  8382. });
  8383. // Should fail because 200MB exceeds the explicit 150MB limit
  8384. EXPECT_FALSE(res);
  8385. }
  8386. server_thread.join();
  8387. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8388. << "Client with content_receiver should respect the explicit "
  8389. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8390. << total_received << " bytes.";
  8391. }
  8392. // Verify that an explicit set_payload_max_length larger than the response
  8393. // allows the content_receiver to read all data successfully.
  8394. TEST(ClientVulnerabilityTest,
  8395. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8396. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8397. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8398. #ifndef _WIN32
  8399. signal(SIGPIPE, SIG_IGN);
  8400. #endif
  8401. auto server_thread = std::thread([] {
  8402. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8403. default_socket_options(srv);
  8404. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8405. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8406. sockaddr_in addr{};
  8407. addr.sin_family = AF_INET;
  8408. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8409. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8410. int opt = 1;
  8411. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8412. #ifdef _WIN32
  8413. reinterpret_cast<const char *>(&opt),
  8414. #else
  8415. &opt,
  8416. #endif
  8417. sizeof(opt));
  8418. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8419. ::listen(srv, 1);
  8420. sockaddr_in cli_addr{};
  8421. socklen_t cli_len = sizeof(cli_addr);
  8422. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8423. if (cli != INVALID_SOCKET) {
  8424. char buf[4096];
  8425. ::recv(cli, buf, sizeof(buf), 0);
  8426. auto content_length = std::to_string(DATA_SIZE);
  8427. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8428. "Content-Length: " +
  8429. content_length +
  8430. "\r\n"
  8431. "Connection: close\r\n"
  8432. "\r\n";
  8433. ::send(cli,
  8434. #ifdef _WIN32
  8435. static_cast<const char *>(response_header.c_str()),
  8436. static_cast<int>(response_header.size()),
  8437. #else
  8438. response_header.c_str(), response_header.size(),
  8439. #endif
  8440. 0);
  8441. std::string chunk(64 * 1024, 'A');
  8442. size_t total_sent = 0;
  8443. while (total_sent < DATA_SIZE) {
  8444. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8445. auto sent = ::send(cli,
  8446. #ifdef _WIN32
  8447. static_cast<const char *>(chunk.c_str()),
  8448. static_cast<int>(to_send),
  8449. #else
  8450. chunk.c_str(), to_send,
  8451. #endif
  8452. 0);
  8453. if (sent <= 0) break;
  8454. total_sent += static_cast<size_t>(sent);
  8455. }
  8456. #ifdef _WIN32
  8457. ::shutdown(cli, SD_SEND);
  8458. #else
  8459. ::shutdown(cli, SHUT_WR);
  8460. #endif
  8461. char drain[1024];
  8462. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8463. detail::close_socket(cli);
  8464. }
  8465. detail::close_socket(srv);
  8466. });
  8467. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8468. size_t total_received = 0;
  8469. {
  8470. Client cli("127.0.0.1", PORT + 2);
  8471. cli.set_read_timeout(10, 0);
  8472. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8473. auto res =
  8474. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8475. total_received += data_length;
  8476. return true;
  8477. });
  8478. ASSERT_TRUE(res);
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. }
  8481. server_thread.join();
  8482. EXPECT_EQ(total_received, DATA_SIZE)
  8483. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8484. << " bytes (larger than " << DATA_SIZE
  8485. << " bytes response), content_receiver should read all data, but only "
  8486. "read "
  8487. << total_received << " bytes.";
  8488. }
  8489. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8490. // Regression test for "zip bomb" attack on the client side: a malicious server
  8491. // sends a small gzip-compressed response that decompresses to a huge payload.
  8492. // The client must enforce payload_max_length on the decompressed size.
  8493. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8494. constexpr size_t DECOMPRESSED_SIZE =
  8495. 10 * 1024 * 1024; // 10MB after decompression
  8496. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8497. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8498. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8499. std::string compressed;
  8500. {
  8501. httplib::detail::gzip_compressor compressor;
  8502. bool ok =
  8503. compressor.compress(uncompressed.data(), uncompressed.size(),
  8504. /*last=*/true, [&](const char *buf, size_t len) {
  8505. compressed.append(buf, len);
  8506. return true;
  8507. });
  8508. ASSERT_TRUE(ok);
  8509. }
  8510. // Sanity: compressed data should be much smaller than the decompressed size
  8511. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8512. #ifndef _WIN32
  8513. signal(SIGPIPE, SIG_IGN);
  8514. #endif
  8515. // Set up the listening socket in the main thread so the server is guaranteed
  8516. // to be ready before the client connects (eliminates race condition).
  8517. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8518. default_socket_options(srv);
  8519. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8520. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8521. sockaddr_in addr{};
  8522. addr.sin_family = AF_INET;
  8523. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8524. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8525. int opt = 1;
  8526. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8527. #ifdef _WIN32
  8528. reinterpret_cast<const char *>(&opt),
  8529. #else
  8530. &opt,
  8531. #endif
  8532. sizeof(opt));
  8533. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8534. ASSERT_EQ(0, ::listen(srv, 1));
  8535. auto server_thread = std::thread([&compressed, srv] {
  8536. sockaddr_in cli_addr{};
  8537. socklen_t cli_len = sizeof(cli_addr);
  8538. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8539. if (cli != INVALID_SOCKET) {
  8540. // Read the full HTTP request (until \r\n\r\n)
  8541. char buf[4096];
  8542. size_t total = 0;
  8543. while (total < sizeof(buf)) {
  8544. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8545. if (n <= 0) break;
  8546. total += static_cast<size_t>(n);
  8547. // Check for end of headers
  8548. if (total >= 4) {
  8549. std::string req(buf, total);
  8550. if (req.find("\r\n\r\n") != std::string::npos) break;
  8551. }
  8552. }
  8553. // Malicious response: gzip-compressed body, no Content-Length
  8554. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8555. "Content-Encoding: gzip\r\n"
  8556. "Connection: close\r\n"
  8557. "\r\n";
  8558. ::send(cli,
  8559. #ifdef _WIN32
  8560. static_cast<const char *>(response_header.c_str()),
  8561. static_cast<int>(response_header.size()),
  8562. #else
  8563. response_header.c_str(), response_header.size(),
  8564. #endif
  8565. 0);
  8566. // Send the compressed payload (small on the wire, huge when decompressed)
  8567. size_t total_sent = 0;
  8568. while (total_sent < compressed.size()) {
  8569. auto to_send = std::min(compressed.size() - total_sent,
  8570. static_cast<size_t>(64 * 1024));
  8571. auto sent =
  8572. ::send(cli,
  8573. #ifdef _WIN32
  8574. static_cast<const char *>(compressed.c_str() + total_sent),
  8575. static_cast<int>(to_send),
  8576. #else
  8577. compressed.c_str() + total_sent, to_send,
  8578. #endif
  8579. 0);
  8580. if (sent <= 0) break;
  8581. total_sent += static_cast<size_t>(sent);
  8582. }
  8583. detail::close_socket(cli);
  8584. }
  8585. });
  8586. auto se = detail::scope_exit([&] {
  8587. detail::close_socket(srv);
  8588. server_thread.join();
  8589. });
  8590. size_t total_decompressed = 0;
  8591. {
  8592. Client cli("127.0.0.1", PORT + 3);
  8593. cli.set_read_timeout(5, 0);
  8594. cli.set_decompress(true);
  8595. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8596. auto stream = cli.open_stream("GET", "/zipbomb");
  8597. ASSERT_TRUE(stream.is_valid());
  8598. char buffer[64 * 1024];
  8599. ssize_t n;
  8600. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8601. total_decompressed += static_cast<size_t>(n);
  8602. }
  8603. }
  8604. // The decompressed size must be capped by payload_max_length. Without
  8605. // protection, the client would decompress the full 10MB from a tiny
  8606. // compressed payload, enabling a zip bomb DoS attack.
  8607. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8608. << "Client decompressed " << total_decompressed
  8609. << " bytes from a gzip response. The decompressed size should be "
  8610. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8611. }
  8612. #endif
  8613. TEST(HostAndPortPropertiesTest, NoSSL) {
  8614. httplib::Client cli("www.google.com", 1234);
  8615. ASSERT_EQ("www.google.com", cli.host());
  8616. ASSERT_EQ(1234, cli.port());
  8617. }
  8618. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8619. httplib::Client cli("www.google.com:1234");
  8620. ASSERT_EQ("www.google.com", cli.host());
  8621. ASSERT_EQ(1234, cli.port());
  8622. }
  8623. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8624. // Port number that overflows int — should not crash, client becomes invalid
  8625. httplib::Client cli("http://www.google.com:99999999999999999999");
  8626. ASSERT_FALSE(cli.is_valid());
  8627. }
  8628. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8629. // Port 99999 exceeds valid range (1-65535) — should not crash
  8630. httplib::Client cli("http://www.google.com:99999");
  8631. ASSERT_FALSE(cli.is_valid());
  8632. }
  8633. #ifdef CPPHTTPLIB_SSL_ENABLED
  8634. TEST(HostAndPortPropertiesTest, SSL) {
  8635. httplib::SSLClient cli("www.google.com");
  8636. ASSERT_EQ("www.google.com", cli.host());
  8637. ASSERT_EQ(443, cli.port());
  8638. }
  8639. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8640. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8641. std::string cert;
  8642. read_file(CA_CERT_FILE, cert);
  8643. httplib::SSLClient httplib_client("www.google.com");
  8644. // Load CA store first time
  8645. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8646. // Load CA store second time (update)
  8647. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8648. // Verify client is still valid and can make connections
  8649. httplib_client.enable_server_certificate_verification(true);
  8650. auto res = httplib_client.Get("/");
  8651. ASSERT_TRUE(res);
  8652. // Google may return 200 or 301 depending on various factors
  8653. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8654. res->status == StatusCode::MovedPermanently_301);
  8655. }
  8656. TEST(SSLClientTest, ServerNameIndication_Online) {
  8657. auto host = "httpbingo.org";
  8658. auto path = std::string{"/get"};
  8659. SSLClient cli(host, 443);
  8660. auto res = cli.Get(path);
  8661. ASSERT_TRUE(res);
  8662. ASSERT_EQ(StatusCode::OK_200, res->status);
  8663. }
  8664. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8665. // Use a site that will cause SSL verification failure due to self-signed cert
  8666. SSLClient cli("self-signed.badssl.com", 443);
  8667. cli.enable_server_certificate_verification(true);
  8668. auto res = cli.Get("/");
  8669. ASSERT_TRUE(!res);
  8670. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8671. // Verify backend error is captured for SSLServerVerification
  8672. // This occurs when certificate verification fails
  8673. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8674. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8675. EXPECT_NE(0UL, res.ssl_backend_error());
  8676. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8677. // For OpenSSL, ssl_error is 0 for verification errors
  8678. EXPECT_EQ(0, res.ssl_error());
  8679. #if !defined(_WIN32) || \
  8680. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8681. // On non-Windows or when Windows Schannel is disabled, the error comes
  8682. // from OpenSSL's verification
  8683. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8684. res.ssl_backend_error());
  8685. #endif
  8686. #endif
  8687. }
  8688. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8689. // Use a site where hostname doesn't match the certificate
  8690. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8691. SSLClient cli("wrong.host.badssl.com", 443);
  8692. cli.enable_server_certificate_verification(true);
  8693. cli.enable_server_hostname_verification(true);
  8694. auto res = cli.Get("/");
  8695. ASSERT_TRUE(!res);
  8696. // The error type depends on when hostname verification occurs:
  8697. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8698. // - Mbed TLS: SSLServerVerification (during handshake)
  8699. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8700. res.error() == Error::SSLServerVerification);
  8701. // Verify backend error is captured for hostname verification failure
  8702. EXPECT_NE(0UL, res.ssl_backend_error());
  8703. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8704. // For OpenSSL, ssl_error is 0 for verification errors
  8705. EXPECT_EQ(0, res.ssl_error());
  8706. #if !defined(_WIN32) || \
  8707. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8708. // On non-Windows or when Windows Schannel is disabled, the error comes
  8709. // from OpenSSL's hostname verification
  8710. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8711. res.ssl_backend_error());
  8712. #endif
  8713. #endif
  8714. }
  8715. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8716. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8717. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8718. SSLClient cli("www.google.com", 443);
  8719. cli.enable_server_certificate_verification(true);
  8720. auto res = cli.Get("/");
  8721. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8722. }
  8723. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8724. SSLClient cli("www.google.com", 443);
  8725. cli.enable_server_certificate_verification(true);
  8726. cli.enable_windows_certificate_verification(false);
  8727. auto res = cli.Get("/");
  8728. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8729. }
  8730. #endif
  8731. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8732. Client cli("https://google.com");
  8733. auto res = cli.Get("/");
  8734. ASSERT_TRUE(res);
  8735. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8736. }
  8737. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8738. SSLClient cli("google.com");
  8739. cli.set_ca_cert_path(CA_CERT_FILE);
  8740. auto res = cli.Get("/");
  8741. ASSERT_TRUE(res);
  8742. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8743. }
  8744. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8745. SSLClient cli("google.com");
  8746. cli.enable_server_certificate_verification(true);
  8747. cli.set_ca_cert_path("hello");
  8748. auto res = cli.Get("/");
  8749. ASSERT_TRUE(!res);
  8750. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8751. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8752. // should be set
  8753. EXPECT_EQ(0, res.ssl_error());
  8754. // Verify backend error is captured for SSLLoadingCerts
  8755. // This error occurs when loading CA certificates fails
  8756. EXPECT_NE(0UL, res.ssl_backend_error());
  8757. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8758. // OpenSSL specific error codes:
  8759. // > openssl errstr 0x80000002
  8760. // error:80000002:system library::No such file or directory
  8761. // > openssl errstr 0xA000126
  8762. // error:0A000126:SSL routines::unexpected eof while reading
  8763. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8764. res.ssl_backend_error() == 0xA000126);
  8765. #endif
  8766. }
  8767. TEST(SSLClientTest, ServerCertificateVerification4) {
  8768. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8769. ASSERT_TRUE(svr.is_valid());
  8770. svr.Get("/test", [&](const Request &, Response &res) {
  8771. res.set_content("test", "text/plain");
  8772. svr.stop();
  8773. ASSERT_TRUE(true);
  8774. });
  8775. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8776. auto se = detail::scope_exit([&] {
  8777. t.join();
  8778. ASSERT_FALSE(svr.is_running());
  8779. });
  8780. svr.wait_until_ready();
  8781. SSLClient cli("127.0.0.1", PORT);
  8782. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8783. cli.enable_server_certificate_verification(true);
  8784. cli.set_connection_timeout(30);
  8785. auto res = cli.Get("/test");
  8786. ASSERT_TRUE(res);
  8787. ASSERT_EQ(StatusCode::OK_200, res->status);
  8788. }
  8789. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8790. std::string cert;
  8791. read_file(CA_CERT_FILE, cert);
  8792. SSLClient cli("google.com");
  8793. cli.load_ca_cert_store(cert.data(), cert.size());
  8794. const auto res = cli.Get("/");
  8795. ASSERT_TRUE(res);
  8796. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8797. }
  8798. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8799. // clang-format off
  8800. static constexpr char cert[] =
  8801. "GlobalSign Root CA\n"
  8802. "==================\n"
  8803. "-----BEGIN CERTIFICATE-----\n"
  8804. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8805. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8806. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8807. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8808. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8809. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8810. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8811. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8812. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8813. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8814. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8815. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8816. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8817. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8818. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8819. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8820. "-----END CERTIFICATE-----\n";
  8821. // clang-format on
  8822. SSLClient cli("google.com");
  8823. cli.load_ca_cert_store(cert, sizeof(cert));
  8824. const auto res = cli.Get("/");
  8825. ASSERT_TRUE(res);
  8826. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8827. }
  8828. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8829. SSLClient cli("www.youtube.com");
  8830. cli.set_ca_cert_path(CA_CERT_FILE);
  8831. cli.enable_server_certificate_verification(true);
  8832. cli.set_follow_location(true);
  8833. auto res = cli.Get("/");
  8834. ASSERT_TRUE(res);
  8835. ASSERT_EQ(StatusCode::OK_200, res->status);
  8836. }
  8837. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8838. SSLClient cli("wWw.YouTube.Com");
  8839. cli.set_ca_cert_path(CA_CERT_FILE);
  8840. cli.enable_server_certificate_verification(true);
  8841. cli.enable_server_hostname_verification(true);
  8842. cli.set_follow_location(true);
  8843. auto res = cli.Get("/");
  8844. ASSERT_TRUE(res);
  8845. ASSERT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8848. SSLClient cli("gOoGlE.COm");
  8849. cli.enable_server_certificate_verification(true);
  8850. cli.enable_server_hostname_verification(true);
  8851. cli.set_follow_location(true);
  8852. auto res = cli.Get("/");
  8853. ASSERT_TRUE(res);
  8854. ASSERT_EQ(StatusCode::OK_200, res->status);
  8855. }
  8856. TEST(SSLClientTest, Issue2004_Online) {
  8857. Client client("https://google.com");
  8858. client.set_follow_location(true);
  8859. auto res = client.Get("/");
  8860. ASSERT_TRUE(res);
  8861. ASSERT_EQ(StatusCode::OK_200, res->status);
  8862. auto body = res->body;
  8863. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8864. }
  8865. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8866. // Create SSLClient with invalid cert/key to make is_valid() return false
  8867. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8868. "nonexistent_key.pem");
  8869. // is_valid() should be false due to cert loading failure
  8870. ASSERT_FALSE(cli.is_valid());
  8871. auto res = cli.Get("/");
  8872. ASSERT_FALSE(res);
  8873. EXPECT_EQ(Error::SSLConnection, res.error());
  8874. }
  8875. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8876. // Test for Issue #2251: SSL error not properly reported when client cert
  8877. // and key paths are swapped or mismatched
  8878. // This simulates the scenario where user accidentally swaps the cert and key
  8879. // files
  8880. // Using client cert file as private key and vice versa (completely wrong)
  8881. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8882. // Should fail validation due to cert/key mismatch
  8883. ASSERT_FALSE(cli.is_valid());
  8884. // Attempt to make a request should fail with proper error
  8885. auto res = cli.Get("/");
  8886. ASSERT_FALSE(res);
  8887. EXPECT_EQ(Error::SSLConnection, res.error());
  8888. // SSL error should be recorded in the Result object (this is the key fix for
  8889. // Issue #2251)
  8890. auto backend_error = res.ssl_backend_error();
  8891. EXPECT_NE(0u, backend_error);
  8892. }
  8893. // Tests cert/key mismatch detection at the TLS context level
  8894. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8895. // Test that using mismatched cert/key causes connection failure.
  8896. // We verify this at the SSLClient level rather than through internal
  8897. // TLS API functions.
  8898. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8899. cli.enable_server_certificate_verification(false);
  8900. cli.set_connection_timeout(2);
  8901. // The mismatch should cause a connection or handshake error
  8902. auto res = cli.Get("/test");
  8903. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8904. // Either way, the request should fail
  8905. EXPECT_FALSE(res);
  8906. }
  8907. #endif
  8908. #if 0
  8909. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8910. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8911. ASSERT_TRUE(cli != nullptr);
  8912. cli->set_address_family(AF_INET6);
  8913. cli->set_interface("en0");
  8914. auto res = cli->Get("/get");
  8915. ASSERT_TRUE(res);
  8916. ASSERT_EQ(StatusCode::OK_200, res->status);
  8917. }
  8918. #endif
  8919. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8920. #ifdef CPPHTTPLIB_SSL_ENABLED
  8921. void ClientCertPresent(
  8922. const std::string &client_cert_file,
  8923. const std::string &client_private_key_file,
  8924. const std::string &client_encrypted_private_key_pass = std::string()) {
  8925. using namespace httplib::tls;
  8926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8927. CLIENT_CA_CERT_DIR);
  8928. ASSERT_TRUE(svr.is_valid());
  8929. svr.Get("/test", [&](const Request &req, Response &res) {
  8930. res.set_content("test", "text/plain");
  8931. auto cert = req.peer_cert();
  8932. ASSERT_TRUE(static_cast<bool>(cert));
  8933. std::string common_name = cert.subject_cn();
  8934. EXPECT_EQ("Common Name", common_name);
  8935. });
  8936. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8937. auto se = detail::scope_exit([&] {
  8938. svr.stop();
  8939. t.join();
  8940. ASSERT_FALSE(svr.is_running());
  8941. });
  8942. svr.wait_until_ready();
  8943. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8944. client_encrypted_private_key_pass);
  8945. cli.enable_server_certificate_verification(false);
  8946. cli.set_connection_timeout(30);
  8947. auto res = cli.Get("/test");
  8948. ASSERT_TRUE(res);
  8949. ASSERT_EQ(StatusCode::OK_200, res->status);
  8950. }
  8951. TEST(SSLClientServerTest, ClientCertPresent) {
  8952. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8953. }
  8954. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8955. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8956. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8957. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8958. }
  8959. // PEM memory-based constructor tests (works with all TLS backends)
  8960. void PemMemoryClientCertPresent(
  8961. const std::string &client_cert_file,
  8962. const std::string &client_private_key_file,
  8963. const std::string &client_encrypted_private_key_pass = std::string()) {
  8964. // Read PEM files into memory
  8965. std::string server_cert_pem, server_key_pem;
  8966. std::string client_ca_pem;
  8967. std::string client_cert_pem, client_key_pem;
  8968. read_file(SERVER_CERT_FILE, server_cert_pem);
  8969. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8970. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8971. read_file(client_cert_file, client_cert_pem);
  8972. read_file(client_private_key_file, client_key_pem);
  8973. // Create server with PEM memory
  8974. SSLServer::PemMemory server_pem = {
  8975. server_cert_pem.c_str(),
  8976. server_cert_pem.size(),
  8977. server_key_pem.c_str(),
  8978. server_key_pem.size(),
  8979. client_ca_pem.c_str(),
  8980. client_ca_pem.size(),
  8981. nullptr // no password for server key
  8982. };
  8983. SSLServer svr(server_pem);
  8984. ASSERT_TRUE(svr.is_valid());
  8985. svr.Get("/test", [&](const Request &, Response &res) {
  8986. res.set_content("test", "text/plain");
  8987. });
  8988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8989. auto se = detail::scope_exit([&] {
  8990. svr.stop();
  8991. t.join();
  8992. ASSERT_FALSE(svr.is_running());
  8993. });
  8994. svr.wait_until_ready();
  8995. // Create client with PEM memory
  8996. const char *password = client_encrypted_private_key_pass.empty()
  8997. ? nullptr
  8998. : client_encrypted_private_key_pass.c_str();
  8999. SSLClient::PemMemory client_pem = {
  9000. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9001. client_key_pem.size(), password};
  9002. SSLClient cli(HOST, PORT, client_pem);
  9003. cli.enable_server_certificate_verification(false);
  9004. cli.set_connection_timeout(30);
  9005. auto res = cli.Get("/test");
  9006. ASSERT_TRUE(res);
  9007. ASSERT_EQ(StatusCode::OK_200, res->status);
  9008. }
  9009. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9010. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9011. }
  9012. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9013. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9014. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9015. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9016. }
  9017. TEST(SSLClientServerTest, ClientCertMissing) {
  9018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9019. CLIENT_CA_CERT_DIR);
  9020. ASSERT_TRUE(svr.is_valid());
  9021. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9023. auto se = detail::scope_exit([&] {
  9024. svr.stop();
  9025. t.join();
  9026. ASSERT_FALSE(svr.is_running());
  9027. });
  9028. svr.wait_until_ready();
  9029. SSLClient cli(HOST, PORT);
  9030. cli.set_connection_timeout(30);
  9031. auto res = cli.Get("/test");
  9032. ASSERT_TRUE(!res);
  9033. // When client cert is missing and server requires it, connection fails
  9034. // Error type depends on backend implementation
  9035. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9036. res.error() == Error::SSLConnection);
  9037. // Verify backend error is captured
  9038. // Note: This test may have different error codes depending on the exact
  9039. // verification failure
  9040. EXPECT_NE(0UL, res.ssl_backend_error());
  9041. }
  9042. TEST(SSLClientServerTest, TrustDirOptional) {
  9043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9044. ASSERT_TRUE(svr.is_valid());
  9045. svr.Get("/test", [&](const Request &, Response &res) {
  9046. res.set_content("test", "text/plain");
  9047. });
  9048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9049. auto se = detail::scope_exit([&] {
  9050. svr.stop();
  9051. t.join();
  9052. ASSERT_FALSE(svr.is_running());
  9053. });
  9054. svr.wait_until_ready();
  9055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9056. cli.enable_server_certificate_verification(false);
  9057. cli.set_connection_timeout(30);
  9058. auto res = cli.Get("/test");
  9059. ASSERT_TRUE(res);
  9060. ASSERT_EQ(StatusCode::OK_200, res->status);
  9061. }
  9062. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9063. class NoListenSSLServer : public SSLServer {
  9064. public:
  9065. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9066. const char *client_ca_cert_file_path,
  9067. const char *client_ca_cert_dir_path = nullptr)
  9068. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9069. client_ca_cert_dir_path),
  9070. stop_(false) {}
  9071. std::atomic_bool stop_;
  9072. private:
  9073. bool process_and_close_socket(socket_t /*sock*/) override {
  9074. // Don't create SSL context
  9075. while (!stop_.load()) {
  9076. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9077. }
  9078. return true;
  9079. }
  9080. };
  9081. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9082. CLIENT_CA_CERT_FILE);
  9083. ASSERT_TRUE(svr.is_valid());
  9084. svr.Get("/test", [&](const Request &, Response &res) {
  9085. res.set_content("test", "text/plain");
  9086. });
  9087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9088. auto se = detail::scope_exit([&] {
  9089. svr.stop_ = true;
  9090. svr.stop();
  9091. t.join();
  9092. ASSERT_FALSE(svr.is_running());
  9093. });
  9094. svr.wait_until_ready();
  9095. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9096. cli.enable_server_certificate_verification(false);
  9097. cli.set_connection_timeout(1);
  9098. auto res = cli.Get("/test");
  9099. ASSERT_TRUE(!res);
  9100. EXPECT_EQ(Error::SSLConnection, res.error());
  9101. // Timeout results in WantRead error code (maps to backend-specific value)
  9102. EXPECT_NE(0, res.ssl_error());
  9103. }
  9104. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9105. // Test SSLServer with client certificate verification using the standard
  9106. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9108. CLIENT_CA_CERT_DIR);
  9109. ASSERT_TRUE(svr.is_valid());
  9110. svr.Get("/test", [&](const Request &req, Response &res) {
  9111. res.set_content("test", "text/plain");
  9112. auto cert = req.peer_cert();
  9113. ASSERT_TRUE(static_cast<bool>(cert));
  9114. auto common_name = cert.subject_cn();
  9115. EXPECT_EQ("Common Name", common_name);
  9116. });
  9117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9118. auto se = detail::scope_exit([&] {
  9119. svr.stop();
  9120. t.join();
  9121. ASSERT_FALSE(svr.is_running());
  9122. });
  9123. svr.wait_until_ready();
  9124. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9125. cli.enable_server_certificate_verification(false);
  9126. cli.set_connection_timeout(30);
  9127. auto res = cli.Get("/test");
  9128. ASSERT_TRUE(res);
  9129. ASSERT_EQ(StatusCode::OK_200, res->status);
  9130. }
  9131. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9132. // Verifies that wildcard matching and exact matching work consistently
  9133. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9134. using namespace httplib::tls;
  9135. // We need a running server to test against
  9136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9137. ASSERT_TRUE(svr.is_valid());
  9138. svr.Get("/test", [](const Request &, Response &res) {
  9139. res.set_content("ok", "text/plain");
  9140. });
  9141. thread t([&]() { svr.listen(HOST, PORT); });
  9142. auto se = detail::scope_exit([&] {
  9143. svr.stop();
  9144. t.join();
  9145. });
  9146. svr.wait_until_ready();
  9147. bool verify_callback_called = false;
  9148. bool verify_result_wrong = false;
  9149. SSLClient cli(HOST, PORT);
  9150. cli.enable_server_certificate_verification(true);
  9151. cli.set_ca_cert_path(CA_CERT_FILE);
  9152. cli.set_connection_timeout(5);
  9153. // Note: Test certificate has CN="Common Name", not "localhost"
  9154. bool verify_result_cn = false;
  9155. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9156. verify_callback_called = true;
  9157. if (!ctx.cert) return false;
  9158. // Test 1: "Common Name" should match (our test server cert CN)
  9159. verify_result_cn = ctx.check_hostname("Common Name");
  9160. // Test 2: wrong hostname should not match
  9161. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9162. return true; // Accept for the purpose of this test
  9163. });
  9164. auto res = cli.Get("/test");
  9165. // The request may succeed or fail depending on cert configuration
  9166. // but the callback should have been called
  9167. ASSERT_TRUE(verify_callback_called)
  9168. << "Verify callback should have been called";
  9169. // CN="Common Name" should match our test certificate
  9170. //
  9171. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9172. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9173. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9174. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9175. // <openssl/base.h>, which is included transitively when
  9176. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9177. #if defined(OPENSSL_IS_BORINGSSL)
  9178. EXPECT_FALSE(verify_result_cn)
  9179. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9180. #else
  9181. EXPECT_TRUE(verify_result_cn)
  9182. << "verify_hostname should match 'Common Name' (certificate CN)";
  9183. #endif
  9184. // Wrong hostname should not match
  9185. EXPECT_FALSE(verify_result_wrong)
  9186. << "verify_hostname should not match 'wronghost.example.com'";
  9187. }
  9188. #endif
  9189. // mbedTLS-specific callback constructor test
  9190. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9191. #ifdef CPPHTTPLIB_SSL_ENABLED
  9192. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9193. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9194. ASSERT_TRUE(svr.is_valid());
  9195. // Set up a handler to verify client certificate is present
  9196. bool client_cert_verified = false;
  9197. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9198. // Verify that client certificate was provided
  9199. client_cert_verified = true;
  9200. res.set_content("success", "text/plain");
  9201. });
  9202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. t.join();
  9206. ASSERT_FALSE(svr.is_running());
  9207. });
  9208. svr.wait_until_ready();
  9209. // Client with certificate
  9210. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9211. cli.enable_server_certificate_verification(false);
  9212. cli.set_connection_timeout(30);
  9213. auto res = cli.Get("/test");
  9214. ASSERT_TRUE(res);
  9215. ASSERT_EQ(StatusCode::OK_200, res->status);
  9216. ASSERT_TRUE(client_cert_verified);
  9217. EXPECT_EQ("success", res->body);
  9218. }
  9219. #endif
  9220. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9221. // backends
  9222. #ifdef CPPHTTPLIB_SSL_ENABLED
  9223. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9224. using namespace httplib::tls;
  9225. // Test that when client CA cert file is provided,
  9226. // the server properly requests and validates client certificates
  9227. // Create a server with client authentication
  9228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9229. ASSERT_TRUE(svr.is_valid());
  9230. bool handler_called = false;
  9231. svr.Get("/test", [&](const Request &req, Response &res) {
  9232. handler_called = true;
  9233. // Verify that a client certificate was provided
  9234. auto cert = req.peer_cert();
  9235. ASSERT_TRUE(static_cast<bool>(cert));
  9236. // Get the issuer name
  9237. std::string issuer_str = cert.issuer_name();
  9238. ASSERT_FALSE(issuer_str.empty());
  9239. // The client certificate should be issued by our test CA
  9240. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9241. res.set_content("authenticated", "text/plain");
  9242. });
  9243. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9244. auto se = detail::scope_exit([&] {
  9245. svr.stop();
  9246. t.join();
  9247. ASSERT_FALSE(svr.is_running());
  9248. });
  9249. svr.wait_until_ready();
  9250. // Connect with a client certificate issued by the CA
  9251. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9252. cli.enable_server_certificate_verification(false);
  9253. cli.set_connection_timeout(30);
  9254. auto res = cli.Get("/test");
  9255. ASSERT_TRUE(res);
  9256. ASSERT_EQ(StatusCode::OK_200, res->status);
  9257. ASSERT_TRUE(handler_called);
  9258. EXPECT_EQ("authenticated", res->body);
  9259. }
  9260. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9261. using namespace httplib::tls;
  9262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9263. ASSERT_TRUE(svr.is_valid());
  9264. svr.Get("/test", [](const Request &, Response &res) {
  9265. res.set_content("ok", "text/plain");
  9266. });
  9267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9268. auto se = detail::scope_exit([&] {
  9269. svr.stop();
  9270. t.join();
  9271. });
  9272. svr.wait_until_ready();
  9273. SSLClient cli(HOST, PORT);
  9274. cli.enable_server_certificate_verification(false);
  9275. cli.set_connection_timeout(30);
  9276. bool cert_checked = false;
  9277. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9278. if (ctx.cert) {
  9279. auto sans = ctx.sans();
  9280. // Test certificate may or may not have SANs - just verify the API
  9281. // works If SANs exist, verify the types are valid
  9282. for (const auto &san : sans) {
  9283. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9284. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9285. san.type == SanType::OTHER);
  9286. EXPECT_FALSE(san.value.empty());
  9287. }
  9288. cert_checked = true;
  9289. }
  9290. return true;
  9291. });
  9292. auto res = cli.Get("/test");
  9293. ASSERT_TRUE(res);
  9294. EXPECT_TRUE(cert_checked);
  9295. }
  9296. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9297. using namespace httplib::tls;
  9298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9299. ASSERT_TRUE(svr.is_valid());
  9300. svr.Get("/test", [](const Request &, Response &res) {
  9301. res.set_content("ok", "text/plain");
  9302. });
  9303. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9304. auto se = detail::scope_exit([&] {
  9305. svr.stop();
  9306. t.join();
  9307. });
  9308. svr.wait_until_ready();
  9309. SSLClient cli(HOST, PORT);
  9310. cli.enable_server_certificate_verification(false);
  9311. cli.set_connection_timeout(30);
  9312. bool validity_checked = false;
  9313. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9314. if (ctx.cert) {
  9315. time_t not_before = 0, not_after = 0;
  9316. bool result = ctx.validity(not_before, not_after);
  9317. EXPECT_TRUE(result);
  9318. // Verify that not_before < now < not_after for a valid cert
  9319. time_t now = time(nullptr);
  9320. EXPECT_LT(not_before, now);
  9321. EXPECT_GT(not_after, now);
  9322. validity_checked = true;
  9323. }
  9324. return true;
  9325. });
  9326. auto res = cli.Get("/test");
  9327. ASSERT_TRUE(res);
  9328. EXPECT_TRUE(validity_checked);
  9329. }
  9330. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9331. using namespace httplib::tls;
  9332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9333. ASSERT_TRUE(svr.is_valid());
  9334. svr.Get("/test", [](const Request &, Response &res) {
  9335. res.set_content("ok", "text/plain");
  9336. });
  9337. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9338. auto se = detail::scope_exit([&] {
  9339. svr.stop();
  9340. t.join();
  9341. });
  9342. svr.wait_until_ready();
  9343. SSLClient cli(HOST, PORT);
  9344. cli.enable_server_certificate_verification(false);
  9345. cli.set_connection_timeout(30);
  9346. bool serial_checked = false;
  9347. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9348. if (ctx.cert) {
  9349. std::string serial = ctx.serial();
  9350. EXPECT_FALSE(serial.empty());
  9351. // Serial should be a hex string
  9352. for (char c : serial) {
  9353. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9354. (c >= 'a' && c <= 'f'));
  9355. }
  9356. serial_checked = true;
  9357. }
  9358. return true;
  9359. });
  9360. auto res = cli.Get("/test");
  9361. ASSERT_TRUE(res);
  9362. EXPECT_TRUE(serial_checked);
  9363. }
  9364. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9365. // Test 1: Valid CA file - no error should be recorded
  9366. {
  9367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9368. CLIENT_CA_CERT_FILE);
  9369. ASSERT_TRUE(svr.is_valid());
  9370. // With valid setup, last_ssl_error should be 0
  9371. EXPECT_EQ(0, svr.ssl_last_error());
  9372. }
  9373. // Test 2: Invalid CA file content
  9374. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9375. {
  9376. // Create a temporary file with completely invalid content
  9377. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9378. {
  9379. std::ofstream ofs(temp_invalid_ca);
  9380. ofs << "This is not a certificate file at all\n";
  9381. ofs << "Just plain text content\n";
  9382. }
  9383. // Create server with invalid CA file
  9384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9385. // Clean up temporary file
  9386. std::remove(temp_invalid_ca);
  9387. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9388. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9389. // Note: SSL_CTX_load_verify_locations typically fails first,
  9390. // but our error handling code path is still exercised
  9391. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9392. }
  9393. }
  9394. TEST(VerifyCallbackTest, VerifyContextFields) {
  9395. using namespace httplib::tls;
  9396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9397. ASSERT_TRUE(svr.is_valid());
  9398. svr.Get("/test", [](const Request &, Response &res) {
  9399. res.set_content("ok", "text/plain");
  9400. });
  9401. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. });
  9406. svr.wait_until_ready();
  9407. SSLClient cli(HOST, PORT);
  9408. cli.enable_server_certificate_verification(false);
  9409. cli.set_connection_timeout(30);
  9410. int callback_count = 0;
  9411. bool saw_leaf_cert = false;
  9412. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9413. if (ctx.cert) {
  9414. callback_count++;
  9415. // We should see at least one certificate (the leaf)
  9416. std::string cn = ctx.subject_cn();
  9417. if (!cn.empty()) { saw_leaf_cert = true; }
  9418. // Verify context fields are populated
  9419. EXPECT_NE(ctx.session, nullptr);
  9420. EXPECT_GE(ctx.depth, 0);
  9421. }
  9422. return true;
  9423. });
  9424. auto res = cli.Get("/test");
  9425. ASSERT_TRUE(res);
  9426. EXPECT_GT(callback_count, 0);
  9427. EXPECT_TRUE(saw_leaf_cert);
  9428. }
  9429. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9430. using httplib::tls::TlsError;
  9431. // Test that verify_error_to_string returns empty for success
  9432. std::string success_str = TlsError::verify_error_to_string(0);
  9433. EXPECT_TRUE(success_str.empty());
  9434. // Test that verify_error_to_string returns non-empty for error codes
  9435. // Using a common error code (certificate expired)
  9436. std::string error_str =
  9437. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9438. EXPECT_FALSE(error_str.empty());
  9439. }
  9440. TEST(SessionVerifierTest, CertificateAccepted) {
  9441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9442. ASSERT_TRUE(svr.is_valid());
  9443. svr.Get("/test", [](const Request &, Response &res) {
  9444. res.set_content("ok", "text/plain");
  9445. });
  9446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9447. auto se = detail::scope_exit([&] {
  9448. svr.stop();
  9449. t.join();
  9450. });
  9451. svr.wait_until_ready();
  9452. SSLClient cli(HOST, PORT);
  9453. cli.enable_server_certificate_verification(false);
  9454. cli.set_connection_timeout(30);
  9455. bool callback_called = false;
  9456. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9457. EXPECT_NE(session, nullptr);
  9458. callback_called = true;
  9459. return SSLVerifierResponse::CertificateAccepted;
  9460. });
  9461. auto res = cli.Get("/test");
  9462. ASSERT_TRUE(res);
  9463. EXPECT_EQ(200, res->status);
  9464. EXPECT_TRUE(callback_called);
  9465. }
  9466. TEST(SessionVerifierTest, CertificateRejected) {
  9467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9468. ASSERT_TRUE(svr.is_valid());
  9469. svr.Get("/test", [](const Request &, Response &res) {
  9470. res.set_content("ok", "text/plain");
  9471. });
  9472. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9473. auto se = detail::scope_exit([&] {
  9474. svr.stop();
  9475. t.join();
  9476. });
  9477. svr.wait_until_ready();
  9478. SSLClient cli(HOST, PORT);
  9479. cli.enable_server_certificate_verification(false);
  9480. cli.set_connection_timeout(30);
  9481. bool callback_called = false;
  9482. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9483. EXPECT_NE(session, nullptr);
  9484. callback_called = true;
  9485. return SSLVerifierResponse::CertificateRejected;
  9486. });
  9487. auto res = cli.Get("/test");
  9488. EXPECT_FALSE(res);
  9489. EXPECT_TRUE(callback_called);
  9490. }
  9491. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9493. ASSERT_TRUE(svr.is_valid());
  9494. svr.Get("/test", [](const Request &, Response &res) {
  9495. res.set_content("ok", "text/plain");
  9496. });
  9497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. });
  9502. svr.wait_until_ready();
  9503. // NoDecisionMade with verification disabled should succeed (no default check)
  9504. SSLClient cli(HOST, PORT);
  9505. cli.enable_server_certificate_verification(false);
  9506. cli.set_connection_timeout(30);
  9507. bool callback_called = false;
  9508. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9509. EXPECT_NE(session, nullptr);
  9510. callback_called = true;
  9511. return SSLVerifierResponse::NoDecisionMade;
  9512. });
  9513. auto res = cli.Get("/test");
  9514. ASSERT_TRUE(res);
  9515. EXPECT_EQ(200, res->status);
  9516. EXPECT_TRUE(callback_called);
  9517. }
  9518. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9520. ASSERT_TRUE(svr.is_valid());
  9521. svr.Get("/test", [](const Request &, Response &res) {
  9522. res.set_content("ok", "text/plain");
  9523. });
  9524. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9525. auto se = detail::scope_exit([&] {
  9526. svr.stop();
  9527. t.join();
  9528. });
  9529. svr.wait_until_ready();
  9530. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9531. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9532. // so we only check that the request fails, not whether the callback was
  9533. // called.
  9534. SSLClient cli(HOST, PORT);
  9535. cli.enable_server_certificate_verification(true);
  9536. cli.set_connection_timeout(30);
  9537. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9538. EXPECT_NE(session, nullptr);
  9539. return SSLVerifierResponse::NoDecisionMade;
  9540. });
  9541. auto res = cli.Get("/test");
  9542. EXPECT_FALSE(res);
  9543. }
  9544. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9545. // Test SSL server using PemMemory constructor with client CA certificates
  9546. // Read PEM files
  9547. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9548. read_file(SERVER_CERT_FILE, server_cert_pem);
  9549. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9550. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9551. // Create SSLServer with PemMemory constructor including client CA
  9552. SSLServer::PemMemory server_pem = {
  9553. server_cert_pem.c_str(),
  9554. server_cert_pem.size(),
  9555. server_key_pem.c_str(),
  9556. server_key_pem.size(),
  9557. client_ca_pem.c_str(),
  9558. client_ca_pem.size(),
  9559. nullptr // no password for server key
  9560. };
  9561. SSLServer svr(server_pem);
  9562. ASSERT_TRUE(svr.is_valid());
  9563. // No SSL error should be recorded for valid setup
  9564. EXPECT_EQ(0, svr.ssl_last_error());
  9565. // Set up server endpoints
  9566. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9567. res.set_content("ok", "text/plain");
  9568. });
  9569. // Start server in a thread
  9570. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9571. svr.wait_until_ready();
  9572. // Connect with client certificate (using constructor with paths)
  9573. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9574. cli.enable_server_certificate_verification(false);
  9575. auto res = cli.Get("/test-pem-ca");
  9576. ASSERT_TRUE(res);
  9577. EXPECT_EQ(200, res->status);
  9578. EXPECT_EQ("ok", res->body);
  9579. svr.stop();
  9580. server_thread.join();
  9581. }
  9582. #endif
  9583. #ifdef _WIN32
  9584. TEST(CleanupTest, WSACleanup) {
  9585. int ret = WSACleanup();
  9586. ASSERT_EQ(0, ret);
  9587. }
  9588. #endif
  9589. #ifndef CPPHTTPLIB_SSL_ENABLED
  9590. TEST(NoSSLSupport, SimpleInterface) {
  9591. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9592. }
  9593. #endif
  9594. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9595. TEST(InvalidScheme, SimpleInterface) {
  9596. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9597. }
  9598. #endif
  9599. TEST(NoScheme, SimpleInterface) {
  9600. Client cli("yahoo.com:80");
  9601. ASSERT_TRUE(cli.is_valid());
  9602. }
  9603. TEST(SendAPI, SimpleInterface_Online) {
  9604. Client cli("http://yahoo.com");
  9605. Request req;
  9606. req.method = "GET";
  9607. req.path = "/";
  9608. auto res = cli.send(req);
  9609. ASSERT_TRUE(res);
  9610. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9611. }
  9612. TEST(SendAPI, WithParamsInRequest) {
  9613. Server svr;
  9614. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9615. EXPECT_TRUE(req.has_param("test"));
  9616. EXPECT_EQ("test_value", req.get_param_value("test"));
  9617. });
  9618. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. Client cli(HOST, PORT);
  9626. {
  9627. Request req;
  9628. req.method = "GET";
  9629. req.path = "/";
  9630. req.params.emplace("test", "test_value");
  9631. auto res = cli.send(req);
  9632. ASSERT_TRUE(res);
  9633. }
  9634. {
  9635. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9636. ASSERT_TRUE(res);
  9637. }
  9638. }
  9639. TEST(ClientImplMethods, GetSocketTest) {
  9640. httplib::Server svr;
  9641. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9642. res.status = StatusCode::OK_200;
  9643. });
  9644. auto port = svr.bind_to_any_port("127.0.0.1");
  9645. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9646. auto se = detail::scope_exit([&] {
  9647. svr.stop();
  9648. thread.join();
  9649. ASSERT_FALSE(svr.is_running());
  9650. });
  9651. svr.wait_until_ready();
  9652. {
  9653. httplib::Client cli("127.0.0.1", port);
  9654. cli.set_keep_alive(true);
  9655. // Use the behavior of cpp-httplib of opening the connection
  9656. // only when the first request happens. If that changes,
  9657. // this test would be obsolete.
  9658. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9659. // This also implicitly tests the server. But other tests would fail much
  9660. // earlier than this one to be considered.
  9661. auto res = cli.Get("/");
  9662. ASSERT_TRUE(res);
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9665. }
  9666. }
  9667. #ifdef CPPHTTPLIB_SSL_ENABLED
  9668. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9669. Client cli("http://yahoo.com");
  9670. auto res = cli.Get("/");
  9671. ASSERT_TRUE(res);
  9672. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9673. cli.set_follow_location(true);
  9674. res = cli.Get("/");
  9675. ASSERT_TRUE(res);
  9676. EXPECT_EQ(StatusCode::OK_200, res->status);
  9677. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9678. }
  9679. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9680. Client cli("https://yahoo.com");
  9681. auto res = cli.Get("/");
  9682. ASSERT_TRUE(res);
  9683. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9684. cli.set_follow_location(true);
  9685. res = cli.Get("/");
  9686. ASSERT_TRUE(res);
  9687. EXPECT_EQ(StatusCode::OK_200, res->status);
  9688. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9689. }
  9690. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9691. Client cli("https://yahoo.com");
  9692. auto res = cli.Get("/");
  9693. ASSERT_TRUE(res);
  9694. ASSERT_FALSE(!res);
  9695. ASSERT_TRUE(res);
  9696. ASSERT_FALSE(res == nullptr);
  9697. ASSERT_TRUE(res != nullptr);
  9698. EXPECT_EQ(Error::Success, res.error());
  9699. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9700. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9702. cli.set_follow_location(true);
  9703. res = cli.Get("/");
  9704. ASSERT_TRUE(res);
  9705. EXPECT_EQ(Error::Success, res.error());
  9706. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9707. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9708. EXPECT_EQ(StatusCode::OK_200, res->status);
  9709. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9710. }
  9711. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9712. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9713. Client cli("https://cdnjs.cloudflare.com");
  9714. auto res =
  9715. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9716. ASSERT_TRUE(res);
  9717. EXPECT_EQ(StatusCode::OK_200, res->status);
  9718. EXPECT_EQ(287630U, res->body.size());
  9719. EXPECT_EQ("application/javascript; charset=utf-8",
  9720. res->get_header_value("Content-Type"));
  9721. }
  9722. #endif
  9723. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9724. #undef REDIR_HOST // Silence compiler warning
  9725. #define REDIR_HOST "https://httpbingo.org"
  9726. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9727. Client cli(REDIR_HOST);
  9728. cli.set_follow_location(true);
  9729. auto res =
  9730. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9731. ASSERT_TRUE(res);
  9732. EXPECT_EQ(StatusCode::OK_200, res->status);
  9733. }
  9734. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9735. Client cli(REDIR_HOST);
  9736. cli.set_follow_location(true);
  9737. Params params;
  9738. params.emplace("url", "http://example.com");
  9739. params.emplace("status_code", "302");
  9740. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9741. ASSERT_TRUE(res);
  9742. EXPECT_EQ(StatusCode::OK_200, res->status);
  9743. }
  9744. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9745. Client cli(REDIR_HOST);
  9746. cli.set_follow_location(true);
  9747. Params params;
  9748. params.emplace("url", "http://example.com");
  9749. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9750. ASSERT_TRUE(res);
  9751. EXPECT_EQ(StatusCode::OK_200, res->status);
  9752. }
  9753. TEST(HttpToHttpsRedirectTest, CertFile) {
  9754. auto ssl_port = PORT + 1;
  9755. Server svr;
  9756. ASSERT_TRUE(svr.is_valid());
  9757. svr.Get("/index", [&](const Request &, Response &res) {
  9758. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9759. "/index");
  9760. svr.stop();
  9761. });
  9762. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9763. ASSERT_TRUE(ssl_svr.is_valid());
  9764. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9765. res.set_content("test", "text/plain");
  9766. ssl_svr.stop();
  9767. });
  9768. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9769. thread t2 =
  9770. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9771. auto se = detail::scope_exit([&] {
  9772. t2.join();
  9773. t.join();
  9774. ASSERT_FALSE(svr.is_running());
  9775. });
  9776. svr.wait_until_ready();
  9777. ssl_svr.wait_until_ready();
  9778. Client cli("127.0.0.1", PORT);
  9779. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9780. cli.enable_server_certificate_verification(true);
  9781. cli.set_follow_location(true);
  9782. cli.set_connection_timeout(30);
  9783. auto res = cli.Get("/index");
  9784. ASSERT_TRUE(res);
  9785. ASSERT_EQ(StatusCode::OK_200, res->status);
  9786. }
  9787. TEST(SSLClientRedirectTest, CertFile) {
  9788. auto ssl_port = PORT + 1;
  9789. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9790. ASSERT_TRUE(ssl_svr1.is_valid());
  9791. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9792. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9793. "/index");
  9794. ssl_svr1.stop();
  9795. });
  9796. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9797. ASSERT_TRUE(ssl_svr2.is_valid());
  9798. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9799. res.set_content("test", "text/plain");
  9800. ssl_svr2.stop();
  9801. });
  9802. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9803. thread t2 =
  9804. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9805. auto se = detail::scope_exit([&] {
  9806. t2.join();
  9807. t.join();
  9808. ASSERT_FALSE(ssl_svr1.is_running());
  9809. });
  9810. ssl_svr1.wait_until_ready();
  9811. ssl_svr2.wait_until_ready();
  9812. SSLClient cli("127.0.0.1", PORT);
  9813. std::string cert;
  9814. read_file(SERVER_CERT2_FILE, cert);
  9815. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9816. cli.enable_server_certificate_verification(true);
  9817. cli.set_follow_location(true);
  9818. cli.set_connection_timeout(30);
  9819. auto res = cli.Get("/index");
  9820. ASSERT_TRUE(res);
  9821. ASSERT_EQ(StatusCode::OK_200, res->status);
  9822. }
  9823. #endif
  9824. #ifdef CPPHTTPLIB_SSL_ENABLED
  9825. // Test that set_ca_cert_store() skips system certs (consistent with
  9826. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9827. // should be trusted - system certs should NOT be loaded.
  9828. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9829. // Load a specific cert that is NOT a system CA cert
  9830. std::string cert;
  9831. read_file(SERVER_CERT2_FILE, cert);
  9832. SSLClient cli("google.com");
  9833. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9834. cli.enable_server_certificate_verification(true);
  9835. // This should FAIL because:
  9836. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9837. // 2. System certs should NOT be loaded when custom store is set
  9838. // If system certs WERE loaded, this would succeed
  9839. auto res = cli.Get("/");
  9840. ASSERT_FALSE(res);
  9841. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9842. }
  9843. // Same as above, but through the native store handle path. Regression test:
  9844. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  9845. // merged system certs into the user-provided store.
  9846. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  9847. std::string cert;
  9848. read_file(SERVER_CERT2_FILE, cert);
  9849. SSLClient cli("google.com");
  9850. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9851. cli.enable_server_certificate_verification(true);
  9852. auto res = cli.Get("/");
  9853. ASSERT_FALSE(res);
  9854. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9855. }
  9856. // A custom store set via the native handle must still verify a server whose
  9857. // cert it does contain.
  9858. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  9859. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9860. ASSERT_TRUE(svr.is_valid());
  9861. svr.Get("/test", [&](const Request &, Response &res) {
  9862. res.set_content("test", "text/plain");
  9863. });
  9864. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9865. auto se = detail::scope_exit([&] {
  9866. svr.stop();
  9867. t.join();
  9868. ASSERT_FALSE(svr.is_running());
  9869. });
  9870. svr.wait_until_ready();
  9871. SSLClient cli("127.0.0.1", PORT);
  9872. std::string cert;
  9873. read_file(SERVER_CERT2_FILE, cert);
  9874. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9875. cli.enable_server_certificate_verification(true);
  9876. cli.set_connection_timeout(30);
  9877. auto res = cli.Get("/test");
  9878. ASSERT_TRUE(res);
  9879. ASSERT_EQ(StatusCode::OK_200, res->status);
  9880. }
  9881. // CA certs loaded through the universal Client must be transferred to the
  9882. // client created internally for following an HTTPS redirect. Regression test:
  9883. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  9884. // the CA data for redirect transfer.
  9885. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  9886. auto ssl_port = PORT + 1;
  9887. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9888. ASSERT_TRUE(ssl_svr1.is_valid());
  9889. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9890. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9891. "/index");
  9892. });
  9893. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9894. ASSERT_TRUE(ssl_svr2.is_valid());
  9895. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9896. res.set_content("test", "text/plain");
  9897. });
  9898. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9899. thread t2 =
  9900. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9901. auto se = detail::scope_exit([&] {
  9902. ssl_svr2.stop();
  9903. ssl_svr1.stop();
  9904. t2.join();
  9905. t.join();
  9906. ASSERT_FALSE(ssl_svr1.is_running());
  9907. });
  9908. ssl_svr1.wait_until_ready();
  9909. ssl_svr2.wait_until_ready();
  9910. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9911. std::string cert;
  9912. read_file(SERVER_CERT2_FILE, cert);
  9913. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9914. cli.enable_server_certificate_verification(true);
  9915. cli.set_follow_location(true);
  9916. cli.set_connection_timeout(30);
  9917. auto res = cli.Get("/index");
  9918. ASSERT_TRUE(res);
  9919. ASSERT_EQ(StatusCode::OK_200, res->status);
  9920. }
  9921. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  9922. // so a host signed by a system CA verifies even though a custom CA is set
  9923. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  9924. std::string cert;
  9925. read_file(SERVER_CERT2_FILE, cert);
  9926. SSLClient cli("google.com");
  9927. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9928. cli.enable_system_ca(true);
  9929. cli.enable_server_certificate_verification(true);
  9930. auto res = cli.Get("/");
  9931. ASSERT_TRUE(res);
  9932. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9933. }
  9934. // The custom CA remains effective when combined with the system CA
  9935. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  9936. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9937. ASSERT_TRUE(svr.is_valid());
  9938. svr.Get("/test", [&](const Request &, Response &res) {
  9939. res.set_content("test", "text/plain");
  9940. });
  9941. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. t.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. SSLClient cli("127.0.0.1", PORT);
  9949. std::string cert;
  9950. read_file(SERVER_CERT2_FILE, cert);
  9951. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9952. cli.enable_system_ca(true);
  9953. cli.enable_server_certificate_verification(true);
  9954. cli.set_connection_timeout(30);
  9955. auto res = cli.Get("/test");
  9956. ASSERT_TRUE(res);
  9957. ASSERT_EQ(StatusCode::OK_200, res->status);
  9958. }
  9959. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  9960. // skip chain verification entirely (only the certificate identity was
  9961. // checked), so a server presenting an untrusted certificate with a matching
  9962. // IP SAN was accepted. The chain must be validated for IP hosts too.
  9963. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  9964. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9965. ASSERT_TRUE(svr.is_valid());
  9966. svr.Get("/test", [&](const Request &, Response &res) {
  9967. res.set_content("test", "text/plain");
  9968. });
  9969. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. SSLClient cli("127.0.0.1", PORT);
  9977. std::string cert;
  9978. // A trusted CA that did not sign the server certificate. The server cert
  9979. // (cert2) carries the matching IP SAN, so only chain validation can reject
  9980. // this connection.
  9981. read_file(CLIENT_CA_CERT_FILE, cert);
  9982. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9983. cli.enable_server_certificate_verification(true);
  9984. cli.set_connection_timeout(30);
  9985. auto res = cli.Get("/test");
  9986. ASSERT_FALSE(res);
  9987. }
  9988. // enable_system_ca(false) prevents system CA loading entirely
  9989. TEST(SSLClientTest, DisableSystemCa_Online) {
  9990. SSLClient cli("google.com");
  9991. cli.enable_system_ca(false);
  9992. cli.enable_server_certificate_verification(true);
  9993. auto res = cli.Get("/");
  9994. ASSERT_FALSE(res);
  9995. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  9996. // itself when the CA chain is empty
  9997. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9998. res.error() == Error::SSLConnection);
  9999. }
  10000. // The universal Client forwards enable_system_ca()
  10001. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10002. std::string cert;
  10003. read_file(SERVER_CERT2_FILE, cert);
  10004. Client cli("https://google.com");
  10005. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10006. cli.enable_system_ca(true);
  10007. cli.enable_server_certificate_verification(true);
  10008. auto res = cli.Get("/");
  10009. ASSERT_TRUE(res);
  10010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10011. }
  10012. // The system CA policy must carry over to the client created internally for
  10013. // following a cross-host HTTPS redirect
  10014. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10015. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10016. ASSERT_TRUE(svr.is_valid());
  10017. svr.Get("/index", [&](const Request &, Response &res) {
  10018. res.set_redirect("https://www.google.com/");
  10019. });
  10020. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. t.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10028. std::string cert;
  10029. read_file(SERVER_CERT2_FILE, cert);
  10030. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10031. cli.enable_system_ca(true);
  10032. cli.enable_server_certificate_verification(true);
  10033. cli.set_follow_location(true);
  10034. cli.set_connection_timeout(30);
  10035. // Receiving any response proves the redirect client completed the TLS
  10036. // handshake with a system-CA-signed host
  10037. auto res = cli.Get("/index");
  10038. ASSERT_TRUE(res);
  10039. }
  10040. TEST(MultipartFormDataTest, LargeData) {
  10041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10042. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10043. const ContentReader &content_reader) {
  10044. if (req.is_multipart_form_data()) {
  10045. std::vector<FormData> items;
  10046. content_reader(
  10047. [&](const FormData &file) {
  10048. items.push_back(file);
  10049. return true;
  10050. },
  10051. [&](const char *data, size_t data_length) {
  10052. items.back().content.append(data, data_length);
  10053. return true;
  10054. });
  10055. EXPECT_TRUE(std::string(items[0].name) == "document");
  10056. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10057. EXPECT_TRUE(items[0].filename == "2MB_data");
  10058. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10059. EXPECT_TRUE(items[1].name == "hello");
  10060. EXPECT_TRUE(items[1].content == "world");
  10061. EXPECT_TRUE(items[1].filename == "");
  10062. EXPECT_TRUE(items[1].content_type == "");
  10063. } else {
  10064. std::string body;
  10065. content_reader([&](const char *data, size_t data_length) {
  10066. body.append(data, data_length);
  10067. return true;
  10068. });
  10069. }
  10070. });
  10071. auto port = svr.bind_to_any_port(HOST);
  10072. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. t.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. {
  10080. std::string data(1024 * 1024 * 2, '.');
  10081. std::stringstream buffer;
  10082. buffer << data;
  10083. SSLClient cli(HOST, port);
  10084. cli.enable_server_certificate_verification(false);
  10085. UploadFormDataItems items{
  10086. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10087. {"hello", "world", "", ""},
  10088. };
  10089. auto res = cli.Post("/post", items);
  10090. ASSERT_TRUE(res);
  10091. ASSERT_EQ(StatusCode::OK_200, res->status);
  10092. }
  10093. }
  10094. TEST(MultipartFormDataTest, DataProviderItems) {
  10095. std::random_device seed_gen;
  10096. std::mt19937 random(seed_gen());
  10097. std::string rand1;
  10098. rand1.resize(1000);
  10099. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10100. std::string rand2;
  10101. rand2.resize(3000);
  10102. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10104. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10105. const ContentReader &content_reader) {
  10106. ASSERT_FALSE(req.is_multipart_form_data());
  10107. std::string body;
  10108. content_reader([&](const char *data, size_t data_length) {
  10109. body.append(data, data_length);
  10110. return true;
  10111. });
  10112. EXPECT_EQ(body, "");
  10113. });
  10114. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10115. const ContentReader &content_reader) {
  10116. ASSERT_TRUE(req.is_multipart_form_data());
  10117. std::vector<FormData> items;
  10118. content_reader(
  10119. [&](const FormData &file) {
  10120. items.push_back(file);
  10121. return true;
  10122. },
  10123. [&](const char *data, size_t data_length) {
  10124. items.back().content.append(data, data_length);
  10125. return true;
  10126. });
  10127. ASSERT_TRUE(items.size() == 2);
  10128. EXPECT_EQ(std::string(items[0].name), "name1");
  10129. EXPECT_EQ(items[0].content, "Testing123");
  10130. EXPECT_EQ(items[0].filename, "filename1");
  10131. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10132. EXPECT_EQ(items[1].name, "name2");
  10133. EXPECT_EQ(items[1].content, "Testing456");
  10134. EXPECT_EQ(items[1].filename, "");
  10135. EXPECT_EQ(items[1].content_type, "");
  10136. });
  10137. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10138. const ContentReader &content_reader) {
  10139. ASSERT_TRUE(req.is_multipart_form_data());
  10140. std::vector<FormData> items;
  10141. content_reader(
  10142. [&](const FormData &file) {
  10143. items.push_back(file);
  10144. return true;
  10145. },
  10146. [&](const char *data, size_t data_length) {
  10147. items.back().content.append(data, data_length);
  10148. return true;
  10149. });
  10150. ASSERT_TRUE(items.size() == 2);
  10151. EXPECT_EQ(items[0].name, "name3");
  10152. EXPECT_EQ(items[0].content, rand1);
  10153. EXPECT_EQ(items[0].filename, "filename3");
  10154. EXPECT_EQ(items[0].content_type, "");
  10155. EXPECT_EQ(items[1].name, "name4");
  10156. EXPECT_EQ(items[1].content, rand2);
  10157. EXPECT_EQ(items[1].filename, "filename4");
  10158. EXPECT_EQ(items[1].content_type, "");
  10159. });
  10160. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10161. const ContentReader &content_reader) {
  10162. ASSERT_TRUE(req.is_multipart_form_data());
  10163. std::vector<FormData> items;
  10164. content_reader(
  10165. [&](const FormData &file) {
  10166. items.push_back(file);
  10167. return true;
  10168. },
  10169. [&](const char *data, size_t data_length) {
  10170. items.back().content.append(data, data_length);
  10171. return true;
  10172. });
  10173. ASSERT_TRUE(items.size() == 4);
  10174. EXPECT_EQ(std::string(items[0].name), "name1");
  10175. EXPECT_EQ(items[0].content, "Testing123");
  10176. EXPECT_EQ(items[0].filename, "filename1");
  10177. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10178. EXPECT_EQ(items[1].name, "name2");
  10179. EXPECT_EQ(items[1].content, "Testing456");
  10180. EXPECT_EQ(items[1].filename, "");
  10181. EXPECT_EQ(items[1].content_type, "");
  10182. EXPECT_EQ(items[2].name, "name3");
  10183. EXPECT_EQ(items[2].content, rand1);
  10184. EXPECT_EQ(items[2].filename, "filename3");
  10185. EXPECT_EQ(items[2].content_type, "");
  10186. EXPECT_EQ(items[3].name, "name4");
  10187. EXPECT_EQ(items[3].content, rand2);
  10188. EXPECT_EQ(items[3].filename, "filename4");
  10189. EXPECT_EQ(items[3].content_type, "");
  10190. });
  10191. auto port = svr.bind_to_any_port("localhost");
  10192. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10193. auto se = detail::scope_exit([&] {
  10194. svr.stop();
  10195. t.join();
  10196. ASSERT_FALSE(svr.is_running());
  10197. });
  10198. svr.wait_until_ready();
  10199. {
  10200. SSLClient cli("localhost", port);
  10201. cli.enable_server_certificate_verification(false);
  10202. UploadFormDataItems items{
  10203. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10204. {"name2", "Testing456", "", ""}, // not a file
  10205. };
  10206. {
  10207. auto res = cli.Post("/post-none", {}, {}, {});
  10208. ASSERT_TRUE(res);
  10209. ASSERT_EQ(StatusCode::OK_200, res->status);
  10210. }
  10211. FormDataProviderItems providers;
  10212. {
  10213. auto res =
  10214. cli.Post("/post-items", {}, items, providers); // empty providers
  10215. ASSERT_TRUE(res);
  10216. ASSERT_EQ(StatusCode::OK_200, res->status);
  10217. }
  10218. providers.push_back({"name3",
  10219. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10220. // test the offset is given correctly at each step
  10221. if (!offset)
  10222. sink.os.write(rand1.data(), 30);
  10223. else if (offset == 30)
  10224. sink.os.write(rand1.data() + 30, 300);
  10225. else if (offset == 330)
  10226. sink.os.write(rand1.data() + 330, 670);
  10227. else if (offset == rand1.size())
  10228. sink.done();
  10229. return true;
  10230. },
  10231. "filename3",
  10232. {}});
  10233. providers.push_back({"name4",
  10234. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10235. // test the offset is given correctly at each step
  10236. if (!offset)
  10237. sink.os.write(rand2.data(), 2000);
  10238. else if (offset == 2000)
  10239. sink.os.write(rand2.data() + 2000, 1);
  10240. else if (offset == 2001)
  10241. sink.os.write(rand2.data() + 2001, 999);
  10242. else if (offset == rand2.size())
  10243. sink.done();
  10244. return true;
  10245. },
  10246. "filename4",
  10247. {}});
  10248. {
  10249. auto res = cli.Post("/post-providers", {}, {}, providers);
  10250. ASSERT_TRUE(res);
  10251. ASSERT_EQ(StatusCode::OK_200, res->status);
  10252. }
  10253. {
  10254. auto res = cli.Post("/post-both", {}, items, providers);
  10255. ASSERT_TRUE(res);
  10256. ASSERT_EQ(StatusCode::OK_200, res->status);
  10257. }
  10258. }
  10259. }
  10260. TEST(MultipartFormDataTest, BadHeader) {
  10261. Server svr;
  10262. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10263. res.set_content("ok", "text/plain");
  10264. });
  10265. thread t = thread([&] { svr.listen(HOST, PORT); });
  10266. auto se = detail::scope_exit([&] {
  10267. svr.stop();
  10268. t.join();
  10269. ASSERT_FALSE(svr.is_running());
  10270. });
  10271. svr.wait_until_ready();
  10272. const std::string body =
  10273. "This is the preamble. It is to be ignored, though it\r\n"
  10274. "is a handy place for composition agents to include an\r\n"
  10275. "explanatory note to non-MIME conformant readers.\r\n"
  10276. "\r\n"
  10277. "\r\n"
  10278. "--simple boundary\r\n"
  10279. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10280. ": BAD...\r\n"
  10281. "\r\n"
  10282. "value1\r\n"
  10283. "--simple boundary\r\n"
  10284. "Content-Disposition: form-data; name=\"field2\"; "
  10285. "filename=\"example.txt\"\r\n"
  10286. "\r\n"
  10287. "value2\r\n"
  10288. "--simple boundary--\r\n"
  10289. "This is the epilogue. It is also to be ignored.\r\n";
  10290. std::string content_type =
  10291. R"(multipart/form-data; boundary="simple boundary")";
  10292. Client cli(HOST, PORT);
  10293. auto res = cli.Post("/post", body, content_type.c_str());
  10294. ASSERT_TRUE(res);
  10295. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10296. }
  10297. TEST(MultipartFormDataTest, WithPreamble) {
  10298. Server svr;
  10299. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10300. res.set_content("ok", "text/plain");
  10301. });
  10302. thread t = thread([&] { svr.listen(HOST, PORT); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. t.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. const std::string body =
  10310. "This is the preamble. It is to be ignored, though it\r\n"
  10311. "is a handy place for composition agents to include an\r\n"
  10312. "explanatory note to non-MIME conformant readers.\r\n"
  10313. "\r\n"
  10314. "\r\n"
  10315. "--simple boundary\r\n"
  10316. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10317. "\r\n"
  10318. "value1\r\n"
  10319. "--simple boundary\r\n"
  10320. "Content-Disposition: form-data; name=\"field2\"; "
  10321. "filename=\"example.txt\"\r\n"
  10322. "\r\n"
  10323. "value2\r\n"
  10324. "--simple boundary--\r\n"
  10325. "This is the epilogue. It is also to be ignored.\r\n";
  10326. std::string content_type =
  10327. R"(multipart/form-data; boundary="simple boundary")";
  10328. Client cli(HOST, PORT);
  10329. auto res = cli.Post("/post", body, content_type.c_str());
  10330. ASSERT_TRUE(res);
  10331. EXPECT_EQ(StatusCode::OK_200, res->status);
  10332. }
  10333. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10335. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10336. const ContentReader &content_reader) {
  10337. if (req.is_multipart_form_data()) {
  10338. std::vector<FormData> items;
  10339. content_reader(
  10340. [&](const FormData &file) {
  10341. items.push_back(file);
  10342. return true;
  10343. },
  10344. [&](const char *data, size_t data_length) {
  10345. items.back().content.append(data, data_length);
  10346. return true;
  10347. });
  10348. EXPECT_TRUE(std::string(items[0].name) == "document");
  10349. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10350. EXPECT_TRUE(items[0].filename == "2MB_data");
  10351. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10352. EXPECT_TRUE(items[1].name == "hello");
  10353. EXPECT_TRUE(items[1].content == "world");
  10354. EXPECT_TRUE(items[1].filename == "");
  10355. EXPECT_TRUE(items[1].content_type == "");
  10356. } else {
  10357. std::string body;
  10358. content_reader([&](const char *data, size_t data_length) {
  10359. body.append(data, data_length);
  10360. return true;
  10361. });
  10362. }
  10363. });
  10364. auto port = svr.bind_to_any_port("localhost");
  10365. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10366. auto se = detail::scope_exit([&] {
  10367. svr.stop();
  10368. t.join();
  10369. ASSERT_FALSE(svr.is_running());
  10370. });
  10371. svr.wait_until_ready();
  10372. {
  10373. std::string data(1024 * 1024 * 2, '.');
  10374. std::stringstream buffer;
  10375. buffer << data;
  10376. SSLClient cli("localhost", port);
  10377. cli.enable_server_certificate_verification(false);
  10378. UploadFormDataItems items{
  10379. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10380. {"hello", "world", "", ""},
  10381. };
  10382. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10383. ASSERT_TRUE(res);
  10384. ASSERT_EQ(StatusCode::OK_200, res->status);
  10385. }
  10386. }
  10387. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10388. std::string data(1024 * 1024 * 2, '&');
  10389. std::stringstream buffer;
  10390. buffer << data;
  10391. Client cli("https://localhost:8080");
  10392. UploadFormDataItems items{
  10393. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10394. {"hello", "world", "", ""},
  10395. };
  10396. for (const char &c : " \t\r\n") {
  10397. auto res =
  10398. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10399. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10400. ASSERT_FALSE(res);
  10401. }
  10402. }
  10403. TEST(MultipartFormDataTest, PutFormData) {
  10404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10405. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10406. const ContentReader &content_reader) {
  10407. if (req.is_multipart_form_data()) {
  10408. std::vector<FormData> items;
  10409. content_reader(
  10410. [&](const FormData &file) {
  10411. items.push_back(file);
  10412. return true;
  10413. },
  10414. [&](const char *data, size_t data_length) {
  10415. items.back().content.append(data, data_length);
  10416. return true;
  10417. });
  10418. EXPECT_TRUE(std::string(items[0].name) == "document");
  10419. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10420. EXPECT_TRUE(items[0].filename == "2MB_data");
  10421. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10422. EXPECT_TRUE(items[1].name == "hello");
  10423. EXPECT_TRUE(items[1].content == "world");
  10424. EXPECT_TRUE(items[1].filename == "");
  10425. EXPECT_TRUE(items[1].content_type == "");
  10426. } else {
  10427. std::string body;
  10428. content_reader([&](const char *data, size_t data_length) {
  10429. body.append(data, data_length);
  10430. return true;
  10431. });
  10432. }
  10433. });
  10434. auto port = svr.bind_to_any_port("localhost");
  10435. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10436. auto se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. t.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. });
  10441. svr.wait_until_ready();
  10442. {
  10443. std::string data(1024 * 1024 * 2, '&');
  10444. std::stringstream buffer;
  10445. buffer << data;
  10446. SSLClient cli("localhost", port);
  10447. cli.enable_server_certificate_verification(false);
  10448. UploadFormDataItems items{
  10449. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10450. {"hello", "world", "", ""},
  10451. };
  10452. auto res = cli.Put("/put", items);
  10453. ASSERT_TRUE(res);
  10454. ASSERT_EQ(StatusCode::OK_200, res->status);
  10455. }
  10456. }
  10457. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10459. svr.Put("/put_customboundary",
  10460. [&](const Request &req, const Response & /*res*/,
  10461. const ContentReader &content_reader) {
  10462. if (req.is_multipart_form_data()) {
  10463. std::vector<FormData> items;
  10464. content_reader(
  10465. [&](const FormData &file) {
  10466. items.push_back(file);
  10467. return true;
  10468. },
  10469. [&](const char *data, size_t data_length) {
  10470. items.back().content.append(data, data_length);
  10471. return true;
  10472. });
  10473. EXPECT_TRUE(std::string(items[0].name) == "document");
  10474. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10475. EXPECT_TRUE(items[0].filename == "2MB_data");
  10476. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10477. EXPECT_TRUE(items[1].name == "hello");
  10478. EXPECT_TRUE(items[1].content == "world");
  10479. EXPECT_TRUE(items[1].filename == "");
  10480. EXPECT_TRUE(items[1].content_type == "");
  10481. } else {
  10482. std::string body;
  10483. content_reader([&](const char *data, size_t data_length) {
  10484. body.append(data, data_length);
  10485. return true;
  10486. });
  10487. }
  10488. });
  10489. auto port = svr.bind_to_any_port("localhost");
  10490. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10491. auto se = detail::scope_exit([&] {
  10492. svr.stop();
  10493. t.join();
  10494. ASSERT_FALSE(svr.is_running());
  10495. });
  10496. svr.wait_until_ready();
  10497. {
  10498. std::string data(1024 * 1024 * 2, '&');
  10499. std::stringstream buffer;
  10500. buffer << data;
  10501. SSLClient cli("localhost", port);
  10502. cli.enable_server_certificate_verification(false);
  10503. UploadFormDataItems items{
  10504. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10505. {"hello", "world", "", ""},
  10506. };
  10507. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10508. ASSERT_TRUE(res);
  10509. ASSERT_EQ(StatusCode::OK_200, res->status);
  10510. }
  10511. }
  10512. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10513. std::string data(1024 * 1024 * 2, '&');
  10514. std::stringstream buffer;
  10515. buffer << data;
  10516. Client cli("https://localhost:8080");
  10517. cli.enable_server_certificate_verification(false);
  10518. UploadFormDataItems items{
  10519. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10520. {"hello", "world", "", ""},
  10521. };
  10522. for (const char &c : " \t\r\n") {
  10523. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10524. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10525. ASSERT_FALSE(res);
  10526. }
  10527. }
  10528. TEST(MultipartFormDataTest, AlternateFilename) {
  10529. auto handled = false;
  10530. Server svr;
  10531. svr.Post("/test", [&](const Request &req, Response &res) {
  10532. ASSERT_EQ(2u, req.form.files.size());
  10533. ASSERT_EQ(1u, req.form.fields.size());
  10534. // Test files
  10535. const auto &file1 = req.form.get_file("file1");
  10536. ASSERT_EQ("file1", file1.name);
  10537. ASSERT_EQ("A.txt", file1.filename);
  10538. ASSERT_EQ("text/plain", file1.content_type);
  10539. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10540. const auto &file2 = req.form.get_file("file2");
  10541. ASSERT_EQ("file2", file2.name);
  10542. ASSERT_EQ("a.html", file2.filename);
  10543. ASSERT_EQ("text/html", file2.content_type);
  10544. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10545. file2.content);
  10546. // Test text field
  10547. const auto &text = req.form.get_field("text");
  10548. ASSERT_EQ("text default", text);
  10549. res.set_content("ok", "text/plain");
  10550. handled = true;
  10551. });
  10552. thread t = thread([&] { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. t.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. ASSERT_TRUE(handled);
  10558. });
  10559. svr.wait_until_ready();
  10560. auto req = "POST /test HTTP/1.1\r\n"
  10561. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10562. "Content-Length: 399\r\n"
  10563. "\r\n"
  10564. "----------\r\n"
  10565. "Content-Disposition: form-data; name=\"text\"\r\n"
  10566. "\r\n"
  10567. "text default\r\n"
  10568. "----------\r\n"
  10569. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10570. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10571. "Content-Type: text/plain\r\n"
  10572. "\r\n"
  10573. "Content of a.txt.\r\n"
  10574. "\r\n"
  10575. "----------\r\n"
  10576. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10577. "\"a.html\"\r\n"
  10578. "Content-Type: text/html\r\n"
  10579. "\r\n"
  10580. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10581. "\r\n"
  10582. "------------\r\n";
  10583. ASSERT_TRUE(send_request(1, req));
  10584. }
  10585. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10586. auto handled = false;
  10587. Server svr;
  10588. svr.Post("/test", [&](const Request &req, Response &res) {
  10589. // Case-insensitive "utf-8''" prefix with a long value
  10590. const auto &file = req.form.get_file("file1");
  10591. ASSERT_EQ("file1", file.name);
  10592. // 8000 chars exercises both the Content-Disposition parser and the
  10593. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10594. // Prior to the fix, std::regex_match on this header would cause O(N)
  10595. // stack recursion in libstdc++, leading to SIGSEGV.
  10596. std::string expected_filename(8000, 'A');
  10597. ASSERT_EQ(expected_filename, file.filename);
  10598. res.set_content("ok", "text/plain");
  10599. handled = true;
  10600. });
  10601. thread t = thread([&] { svr.listen(HOST, PORT); });
  10602. auto se = detail::scope_exit([&] {
  10603. svr.stop();
  10604. t.join();
  10605. ASSERT_FALSE(svr.is_running());
  10606. ASSERT_TRUE(handled);
  10607. });
  10608. svr.wait_until_ready();
  10609. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10610. // Regression test for GHSA-qq6v-r583-3h69
  10611. std::string long_filename(8000, 'A');
  10612. std::string body = "----------\r\n"
  10613. "Content-Disposition: form-data; name=\"file1\"; "
  10614. "filename*=\"Utf-8''" +
  10615. long_filename +
  10616. "\"\r\n"
  10617. "\r\n"
  10618. "hello\r\n"
  10619. "------------\r\n";
  10620. auto req = "POST /test HTTP/1.1\r\n"
  10621. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10622. "Content-Length: " +
  10623. std::to_string(body.size()) + "\r\n\r\n" + body;
  10624. ASSERT_TRUE(send_request(1, req));
  10625. }
  10626. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10627. auto handled = false;
  10628. Server svr;
  10629. svr.Post("/test", [&](const Request &req, Response &) {
  10630. ASSERT_EQ(2u, req.form.fields.size());
  10631. const auto &text1 = req.form.get_field("text1");
  10632. ASSERT_EQ("text1", text1);
  10633. const auto &text2 = req.form.get_field("text2");
  10634. ASSERT_EQ("text2", text2);
  10635. handled = true;
  10636. });
  10637. thread t = thread([&] { svr.listen(HOST, PORT); });
  10638. auto se = detail::scope_exit([&] {
  10639. svr.stop();
  10640. t.join();
  10641. ASSERT_FALSE(svr.is_running());
  10642. ASSERT_TRUE(handled);
  10643. });
  10644. svr.wait_until_ready();
  10645. auto req = "POST /test HTTP/1.1\r\n"
  10646. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10647. "Content-Length: 146\r\n"
  10648. "\r\n----------\r\n"
  10649. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10650. "\r\n"
  10651. "text1"
  10652. "\r\n----------\r\n"
  10653. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10654. "\r\n"
  10655. "text2"
  10656. "\r\n------------";
  10657. std::string response;
  10658. ASSERT_TRUE(send_request(1, req, &response));
  10659. ASSERT_EQ("200", response.substr(9, 3));
  10660. }
  10661. TEST(MultipartFormDataTest, ContentLength) {
  10662. auto handled = false;
  10663. Server svr;
  10664. svr.Post("/test", [&](const Request &req, Response &) {
  10665. ASSERT_EQ(2u, req.form.fields.size());
  10666. const auto &text1 = req.form.get_field("text1");
  10667. ASSERT_EQ("text1", text1);
  10668. const auto &text2 = req.form.get_field("text2");
  10669. ASSERT_EQ("text2", text2);
  10670. handled = true;
  10671. });
  10672. thread t = thread([&] { svr.listen(HOST, PORT); });
  10673. auto se = detail::scope_exit([&] {
  10674. svr.stop();
  10675. t.join();
  10676. ASSERT_FALSE(svr.is_running());
  10677. ASSERT_TRUE(handled);
  10678. });
  10679. svr.wait_until_ready();
  10680. auto req = "POST /test HTTP/1.1\r\n"
  10681. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10682. "Content-Length: 167\r\n"
  10683. "\r\n----------\r\n"
  10684. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10685. "Content-Length: 5\r\n"
  10686. "\r\n"
  10687. "text1"
  10688. "\r\n----------\r\n"
  10689. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10690. "\r\n"
  10691. "text2"
  10692. "\r\n------------\r\n";
  10693. std::string response;
  10694. ASSERT_TRUE(send_request(1, req, &response));
  10695. ASSERT_EQ("200", response.substr(9, 3));
  10696. }
  10697. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10698. auto handled = false;
  10699. Server svr;
  10700. svr.Post("/test", [&](const Request &req, Response &) {
  10701. ASSERT_EQ(2u, req.form.fields.size());
  10702. const auto &text1 = req.form.get_field("text1");
  10703. ASSERT_EQ("text1", text1);
  10704. // TODO: Add header access for text fields if needed
  10705. const auto &text2 = req.form.get_field("text2");
  10706. ASSERT_EQ("text2", text2);
  10707. // TODO: Header access for text fields needs to be implemented
  10708. // auto &headers = it->second.headers;
  10709. // ASSERT_EQ(3U, headers.size());
  10710. // auto custom_header = headers.find("x-whatever");
  10711. // ASSERT_TRUE(custom_header != headers.end());
  10712. // ASSERT_NE("customvalue", custom_header->second);
  10713. // ASSERT_EQ("CustomValue", custom_header->second);
  10714. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10715. handled = true;
  10716. });
  10717. thread t = thread([&] { svr.listen(HOST, PORT); });
  10718. auto se = detail::scope_exit([&] {
  10719. svr.stop();
  10720. t.join();
  10721. ASSERT_FALSE(svr.is_running());
  10722. ASSERT_TRUE(handled);
  10723. });
  10724. svr.wait_until_ready();
  10725. auto req = "POST /test HTTP/1.1\r\n"
  10726. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10727. "Content-Length: 232\r\n"
  10728. "\r\n----------\r\n"
  10729. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10730. "Content-Length: 5\r\n"
  10731. "X-Test: 1\r\n"
  10732. "\r\n"
  10733. "text1"
  10734. "\r\n----------\r\n"
  10735. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10736. "Content-Type: text/plain\r\n"
  10737. "X-Whatever: CustomValue\r\n"
  10738. "\r\n"
  10739. "text2"
  10740. "\r\n------------\r\n"
  10741. "That should be disregarded. Not even read";
  10742. std::string response;
  10743. ASSERT_TRUE(send_request(1, req, &response));
  10744. ASSERT_EQ("200", response.substr(9, 3));
  10745. }
  10746. TEST(MultipartFormDataTest, LargeHeader) {
  10747. auto handled = false;
  10748. Server svr;
  10749. svr.Post("/test", [&](const Request &req, Response &) {
  10750. ASSERT_EQ(1u, req.form.fields.size());
  10751. const auto &text = req.form.get_field("name1");
  10752. ASSERT_EQ("text1", text);
  10753. handled = true;
  10754. });
  10755. thread t = thread([&] { svr.listen(HOST, PORT); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. t.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. ASSERT_TRUE(handled);
  10761. });
  10762. svr.wait_until_ready();
  10763. auto boundary = std::string("cpp-httplib-multipart-data");
  10764. std::string content = "--" + boundary +
  10765. "\r\n"
  10766. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10767. "\r\n"
  10768. "text1\r\n"
  10769. "--" +
  10770. boundary + "--\r\n";
  10771. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10772. "Content-Type: multipart/form-data;boundary=" +
  10773. boundary +
  10774. "\r\n"
  10775. "Content-Length: " +
  10776. std::to_string(content.size()) +
  10777. "\r\n"
  10778. "Dummy-Header: ";
  10779. std::string header_suffix = "\r\n"
  10780. "\r\n";
  10781. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10782. size_t header_dummy_size =
  10783. read_buff_size -
  10784. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10785. auto header_dummy = std::string(header_dummy_size, '@');
  10786. auto req = header_prefix + header_dummy + header_suffix + content;
  10787. std::string response;
  10788. ASSERT_TRUE(send_request(1, req, &response));
  10789. ASSERT_EQ("200", response.substr(9, 3));
  10790. }
  10791. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10792. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10793. // (not chunked Transfer-Encoding) after the streaming refactor.
  10794. auto handled = false;
  10795. Server svr;
  10796. svr.Post("/upload", [&](const Request &req, Response &res) {
  10797. auto cl_it = req.headers.find("Content-Length");
  10798. EXPECT_TRUE(cl_it != req.headers.end());
  10799. auto te_it = req.headers.find("Transfer-Encoding");
  10800. EXPECT_TRUE(te_it == req.headers.end());
  10801. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10802. res.set_content("ok", "text/plain");
  10803. handled = true;
  10804. });
  10805. auto port = svr.bind_to_any_port(HOST);
  10806. auto t = thread([&] { svr.listen_after_bind(); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. t.join();
  10810. ASSERT_FALSE(svr.is_running());
  10811. ASSERT_TRUE(handled);
  10812. });
  10813. svr.wait_until_ready();
  10814. UploadFormDataItems items = {
  10815. {"field1", "hello", "", "text/plain"},
  10816. {"file1", "world", "test.txt", "application/octet-stream"},
  10817. };
  10818. Client cli(HOST, port);
  10819. auto res = cli.Post("/upload", {}, items);
  10820. ASSERT_TRUE(res);
  10821. EXPECT_EQ(StatusCode::OK_200, res->status);
  10822. }
  10823. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10824. // Verify that make_multipart_content_provider coalesces many small segments
  10825. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10826. constexpr size_t kItemCount = 1000;
  10827. UploadFormDataItems items;
  10828. items.reserve(kItemCount);
  10829. for (size_t i = 0; i < kItemCount; i++) {
  10830. items.push_back(
  10831. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10832. }
  10833. const std::string boundary = "----test-boundary";
  10834. auto content_length = detail::get_multipart_content_length(items, boundary);
  10835. auto provider = detail::make_multipart_content_provider(items, boundary);
  10836. // Drive the provider the same way write_content_with_progress does
  10837. size_t write_count = 0;
  10838. size_t total_bytes = 0;
  10839. DataSink sink;
  10840. size_t offset = 0;
  10841. sink.write = [&](const char *d, size_t l) -> bool {
  10842. (void)d;
  10843. write_count++;
  10844. total_bytes += l;
  10845. offset += l;
  10846. return true;
  10847. };
  10848. sink.is_writable = []() -> bool { return true; };
  10849. while (offset < content_length) {
  10850. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10851. }
  10852. EXPECT_EQ(content_length, total_bytes);
  10853. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10854. // With buffering into 64KB blocks, write_count should be much smaller.
  10855. auto segment_count = 3 * kItemCount + 1;
  10856. EXPECT_LT(write_count, segment_count / 10);
  10857. }
  10858. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10859. // Integration test: send many UploadFormDataItems and verify the server
  10860. // receives all of them correctly (#2410).
  10861. constexpr size_t kItemCount = 500;
  10862. auto handled = false;
  10863. Server svr;
  10864. svr.Post("/upload", [&](const Request &req, Response &res) {
  10865. EXPECT_EQ(kItemCount, req.form.fields.size());
  10866. for (size_t i = 0; i < kItemCount; i++) {
  10867. auto key = "field" + std::to_string(i);
  10868. auto val = "value" + std::to_string(i);
  10869. auto it = req.form.fields.find(key);
  10870. if (it != req.form.fields.end()) {
  10871. EXPECT_EQ(val, it->second.content);
  10872. } else {
  10873. ADD_FAILURE() << "Missing field: " << key;
  10874. }
  10875. }
  10876. res.set_content("ok", "text/plain");
  10877. handled = true;
  10878. });
  10879. auto port = svr.bind_to_any_port(HOST);
  10880. auto t = thread([&] { svr.listen_after_bind(); });
  10881. auto se = detail::scope_exit([&] {
  10882. svr.stop();
  10883. t.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. ASSERT_TRUE(handled);
  10886. });
  10887. svr.wait_until_ready();
  10888. UploadFormDataItems items;
  10889. items.reserve(kItemCount);
  10890. for (size_t i = 0; i < kItemCount; i++) {
  10891. items.push_back(
  10892. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10893. }
  10894. Client cli(HOST, port);
  10895. auto res = cli.Post("/upload", items);
  10896. ASSERT_TRUE(res);
  10897. EXPECT_EQ(StatusCode::OK_200, res->status);
  10898. }
  10899. TEST(MultipartFormDataTest, MakeFileProvider) {
  10900. // Verify make_file_provider sends a file's contents correctly.
  10901. const std::string file_content(4096, 'Z');
  10902. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10903. {
  10904. std::ofstream ofs(tmp_path, std::ios::binary);
  10905. ofs.write(file_content.data(),
  10906. static_cast<std::streamsize>(file_content.size()));
  10907. }
  10908. auto handled = false;
  10909. Server svr;
  10910. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10911. const ContentReader &content_reader) {
  10912. ASSERT_TRUE(req.is_multipart_form_data());
  10913. std::vector<FormData> items;
  10914. content_reader(
  10915. [&](const FormData &file) {
  10916. items.push_back(file);
  10917. return true;
  10918. },
  10919. [&](const char *data, size_t data_length) {
  10920. items.back().content.append(data, data_length);
  10921. return true;
  10922. });
  10923. ASSERT_EQ(1u, items.size());
  10924. EXPECT_EQ("myfile", items[0].name);
  10925. EXPECT_EQ("data.bin", items[0].filename);
  10926. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10927. EXPECT_EQ(file_content, items[0].content);
  10928. handled = true;
  10929. });
  10930. auto port = svr.bind_to_any_port(HOST);
  10931. auto t = thread([&] { svr.listen_after_bind(); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. ASSERT_TRUE(handled);
  10937. std::remove(tmp_path.c_str());
  10938. });
  10939. svr.wait_until_ready();
  10940. FormDataProviderItems providers;
  10941. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10942. "application/octet-stream"));
  10943. Client cli(HOST, port);
  10944. auto res = cli.Post("/upload", {}, {}, providers);
  10945. ASSERT_TRUE(res);
  10946. EXPECT_EQ(StatusCode::OK_200, res->status);
  10947. }
  10948. TEST(MakeFileBodyTest, Basic) {
  10949. const std::string file_content(4096, 'Z');
  10950. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10951. {
  10952. std::ofstream ofs(tmp_path, std::ios::binary);
  10953. ofs.write(file_content.data(),
  10954. static_cast<std::streamsize>(file_content.size()));
  10955. }
  10956. auto handled = false;
  10957. Server svr;
  10958. svr.Post("/upload", [&](const Request &req, Response &res) {
  10959. EXPECT_EQ(file_content, req.body);
  10960. handled = true;
  10961. res.status = StatusCode::OK_200;
  10962. });
  10963. auto port = svr.bind_to_any_port(HOST);
  10964. auto t = thread([&] { svr.listen_after_bind(); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. t.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. ASSERT_TRUE(handled);
  10970. std::remove(tmp_path.c_str());
  10971. });
  10972. svr.wait_until_ready();
  10973. auto fb = make_file_body(tmp_path);
  10974. ASSERT_GT(fb.first, 0u);
  10975. Client cli(HOST, port);
  10976. auto res =
  10977. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10978. ASSERT_TRUE(res);
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. }
  10981. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10982. static constexpr unsigned int number_of_tasks{1000000};
  10983. std::atomic_uint count{0};
  10984. std::unique_ptr<TaskQueue> task_queue{
  10985. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10986. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10987. auto queued = task_queue->enqueue(
  10988. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10989. EXPECT_TRUE(queued);
  10990. }
  10991. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10992. task_queue->shutdown();
  10993. #else
  10994. EXPECT_NO_THROW(task_queue->shutdown());
  10995. #endif
  10996. EXPECT_EQ(number_of_tasks, count.load());
  10997. }
  10998. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10999. static constexpr unsigned int number_of_tasks{1000000};
  11000. static constexpr unsigned int qlimit{2};
  11001. unsigned int queued_count{0};
  11002. std::atomic_uint count{0};
  11003. std::unique_ptr<TaskQueue> task_queue{
  11004. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11005. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11006. if (task_queue->enqueue(
  11007. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11008. queued_count++;
  11009. }
  11010. }
  11011. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11012. task_queue->shutdown();
  11013. #else
  11014. EXPECT_NO_THROW(task_queue->shutdown());
  11015. #endif
  11016. EXPECT_EQ(queued_count, count.load());
  11017. EXPECT_TRUE(queued_count <= number_of_tasks);
  11018. EXPECT_TRUE(queued_count >= qlimit);
  11019. }
  11020. TEST(TaskQueueTest, MaxQueuedRequests) {
  11021. static constexpr unsigned int qlimit{3};
  11022. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11023. std::condition_variable sem_cv;
  11024. std::mutex sem_mtx;
  11025. int credits = 0;
  11026. bool queued;
  11027. /* Fill up the queue with tasks that will block until we give them credits to
  11028. * complete. */
  11029. for (unsigned int n = 0; n <= qlimit;) {
  11030. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11031. std::unique_lock<std::mutex> lock(sem_mtx);
  11032. while (credits <= 0) {
  11033. sem_cv.wait(lock);
  11034. }
  11035. /* Consume the credit and signal the test code if they are all gone. */
  11036. if (--credits == 0) { sem_cv.notify_one(); }
  11037. });
  11038. if (n < qlimit) {
  11039. /* The first qlimit enqueues must succeed. */
  11040. EXPECT_TRUE(queued);
  11041. } else {
  11042. /* The last one will succeed only when the worker thread
  11043. * starts and dequeues the first blocking task. Although
  11044. * not necessary for the correctness of this test, we sleep for
  11045. * a short while to avoid busy waiting. */
  11046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11047. }
  11048. if (queued) { n++; }
  11049. }
  11050. /* Further enqueues must fail since the queue is full. */
  11051. for (auto i = 0; i < 4; i++) {
  11052. queued = task_queue->enqueue([] {});
  11053. EXPECT_FALSE(queued);
  11054. }
  11055. /* Give the credits to allow the previous tasks to complete. */
  11056. {
  11057. std::unique_lock<std::mutex> lock(sem_mtx);
  11058. credits += qlimit + 1;
  11059. }
  11060. sem_cv.notify_all();
  11061. /* Wait for all the credits to be consumed. */
  11062. {
  11063. std::unique_lock<std::mutex> lock(sem_mtx);
  11064. while (credits > 0) {
  11065. sem_cv.wait(lock);
  11066. }
  11067. }
  11068. /* Check that we are able again to enqueue at least qlimit tasks. */
  11069. for (unsigned int i = 0; i < qlimit; i++) {
  11070. queued = task_queue->enqueue([] {});
  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. }
  11079. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11080. Server svr;
  11081. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11082. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11083. });
  11084. svr.Get("/hello", [](const Request &req, Response &res) {
  11085. res.set_content(req.get_param_value("key"), "text/plain");
  11086. });
  11087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11088. auto se = detail::scope_exit([&] {
  11089. svr.stop();
  11090. thread.join();
  11091. ASSERT_FALSE(svr.is_running());
  11092. });
  11093. svr.wait_until_ready();
  11094. {
  11095. Client cli(HOST, PORT);
  11096. cli.set_follow_location(true);
  11097. auto res = cli.Get("/");
  11098. ASSERT_TRUE(res);
  11099. EXPECT_EQ(StatusCode::OK_200, res->status);
  11100. EXPECT_EQ("val&key2=val2", res->body);
  11101. }
  11102. }
  11103. #endif
  11104. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11105. Server svr;
  11106. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11107. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11108. });
  11109. svr.Get("/hello", [](const Request &req, Response &res) {
  11110. res.set_content(req.get_param_value("key"), "text/plain");
  11111. });
  11112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11113. auto se = detail::scope_exit([&] {
  11114. svr.stop();
  11115. thread.join();
  11116. ASSERT_FALSE(svr.is_running());
  11117. });
  11118. svr.wait_until_ready();
  11119. {
  11120. Client cli(HOST, PORT);
  11121. cli.set_follow_location(true);
  11122. auto res = cli.Get("/");
  11123. ASSERT_TRUE(res);
  11124. EXPECT_EQ(StatusCode::OK_200, res->status);
  11125. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11126. }
  11127. }
  11128. TEST(RedirectTest, RedirectWithPlusInPath) {
  11129. Server svr;
  11130. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11131. res.set_redirect("/a+b");
  11132. });
  11133. // Route pattern uses regex; escape + as \\+
  11134. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11135. res.set_content(req.path, "text/plain");
  11136. });
  11137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11138. auto se = detail::scope_exit([&] {
  11139. svr.stop();
  11140. thread.join();
  11141. ASSERT_FALSE(svr.is_running());
  11142. });
  11143. svr.wait_until_ready();
  11144. {
  11145. Client cli(HOST, PORT);
  11146. cli.set_follow_location(true);
  11147. auto res = cli.Get("/");
  11148. ASSERT_TRUE(res);
  11149. EXPECT_EQ(StatusCode::OK_200, res->status);
  11150. EXPECT_EQ("/a+b", res->body);
  11151. }
  11152. }
  11153. #ifdef CPPHTTPLIB_SSL_ENABLED
  11154. TEST(RedirectTest, Issue2185_Online) {
  11155. SSLClient client("github.com");
  11156. client.set_follow_location(true);
  11157. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11158. "Coollab-Windows.zip");
  11159. ASSERT_TRUE(res);
  11160. EXPECT_EQ(StatusCode::OK_200, res->status);
  11161. EXPECT_EQ(9920427U, res->body.size());
  11162. }
  11163. #endif
  11164. TEST(VulnerabilityTest, CRLFInjection) {
  11165. Server svr;
  11166. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11167. res.set_content("Hello 1", "text/plain");
  11168. });
  11169. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11170. res.set_content("Hello 2", "text/plain");
  11171. });
  11172. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11173. res.set_content("Hello 3", "text/plain");
  11174. });
  11175. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11176. res.set_content("Hello 4", "text/plain");
  11177. });
  11178. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11179. for (const auto &x : req.headers) {
  11180. auto key = x.first;
  11181. EXPECT_STRNE("evil", key.c_str());
  11182. }
  11183. });
  11184. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. thread.join();
  11188. ASSERT_FALSE(svr.is_running());
  11189. });
  11190. svr.wait_until_ready();
  11191. {
  11192. Client cli(HOST, PORT);
  11193. cli.Post("/test1", "A=B",
  11194. "application/x-www-form-urlencoded\r\nevil: hello1");
  11195. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11196. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11197. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11198. }
  11199. }
  11200. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11201. auto server_thread = std::thread([] {
  11202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11203. default_socket_options(srv);
  11204. sockaddr_in addr{};
  11205. addr.sin_family = AF_INET;
  11206. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11207. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11208. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11209. ::listen(srv, 1);
  11210. sockaddr_in cli_addr{};
  11211. socklen_t cli_len = sizeof(cli_addr);
  11212. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11213. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11214. std::string buf_all;
  11215. char buf[2048];
  11216. ssize_t n;
  11217. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11218. buf_all.append(buf, static_cast<size_t>(n));
  11219. size_t pos;
  11220. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11221. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11222. auto e = request_block.find("\r\n");
  11223. if (e != std::string::npos) {
  11224. auto request_line = request_block.substr(0, e);
  11225. std::string msg =
  11226. "CRLF injection detected in request line: '" + request_line + "'";
  11227. EXPECT_FALSE(true) << msg;
  11228. }
  11229. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11230. ::send(cli,
  11231. #ifdef _WIN32
  11232. static_cast<const char *>(resp.c_str()),
  11233. static_cast<int>(resp.size()),
  11234. #else
  11235. resp.c_str(), resp.size(),
  11236. #endif
  11237. 0);
  11238. buf_all.erase(0, pos + 4);
  11239. }
  11240. }
  11241. detail::close_socket(cli);
  11242. detail::close_socket(srv);
  11243. });
  11244. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11245. auto cli = Client("127.0.0.1", PORT + 1);
  11246. auto headers = Headers{
  11247. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11248. {"Connection", "keep-alive"}};
  11249. auto res = cli.Get("/hi", headers);
  11250. EXPECT_FALSE(res);
  11251. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11252. server_thread.join();
  11253. }
  11254. TEST(PathParamsTest, StaticMatch) {
  11255. const auto pattern = "/users/all";
  11256. detail::PathParamsMatcher matcher(pattern);
  11257. Request request;
  11258. request.path = "/users/all";
  11259. ASSERT_TRUE(matcher.match(request));
  11260. std::unordered_map<std::string, std::string> expected_params = {};
  11261. EXPECT_EQ(request.path_params, expected_params);
  11262. }
  11263. TEST(PathParamsTest, StaticMismatch) {
  11264. const auto pattern = "/users/all";
  11265. detail::PathParamsMatcher matcher(pattern);
  11266. Request request;
  11267. request.path = "/users/1";
  11268. ASSERT_FALSE(matcher.match(request));
  11269. }
  11270. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11271. const auto pattern = "/users/:id/subscriptions";
  11272. detail::PathParamsMatcher matcher(pattern);
  11273. Request request;
  11274. request.path = "/users/42/subscriptions";
  11275. ASSERT_TRUE(matcher.match(request));
  11276. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11277. EXPECT_EQ(request.path_params, expected_params);
  11278. }
  11279. TEST(PathParamsTest, SingleParamInTheEnd) {
  11280. const auto pattern = "/users/:id";
  11281. detail::PathParamsMatcher matcher(pattern);
  11282. Request request;
  11283. request.path = "/users/24";
  11284. ASSERT_TRUE(matcher.match(request));
  11285. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11286. EXPECT_EQ(request.path_params, expected_params);
  11287. }
  11288. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11289. const auto pattern = "/users/:id/";
  11290. detail::PathParamsMatcher matcher(pattern);
  11291. Request request;
  11292. request.path = "/users/42/";
  11293. ASSERT_TRUE(matcher.match(request));
  11294. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11295. EXPECT_EQ(request.path_params, expected_params);
  11296. }
  11297. TEST(PathParamsTest, EmptyParam) {
  11298. const auto pattern = "/users/:id/";
  11299. detail::PathParamsMatcher matcher(pattern);
  11300. Request request;
  11301. request.path = "/users//";
  11302. ASSERT_TRUE(matcher.match(request));
  11303. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11304. EXPECT_EQ(request.path_params, expected_params);
  11305. }
  11306. TEST(PathParamsTest, FragmentMismatch) {
  11307. const auto pattern = "/users/:id/";
  11308. detail::PathParamsMatcher matcher(pattern);
  11309. Request request;
  11310. request.path = "/admins/24/";
  11311. ASSERT_FALSE(matcher.match(request));
  11312. }
  11313. TEST(PathParamsTest, ExtraFragments) {
  11314. const auto pattern = "/users/:id";
  11315. detail::PathParamsMatcher matcher(pattern);
  11316. Request request;
  11317. request.path = "/users/42/subscriptions";
  11318. ASSERT_FALSE(matcher.match(request));
  11319. }
  11320. TEST(PathParamsTest, MissingTrailingParam) {
  11321. const auto pattern = "/users/:id";
  11322. detail::PathParamsMatcher matcher(pattern);
  11323. Request request;
  11324. request.path = "/users";
  11325. ASSERT_FALSE(matcher.match(request));
  11326. }
  11327. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11328. const auto pattern = "/users/:id/subscriptions";
  11329. detail::PathParamsMatcher matcher(pattern);
  11330. Request request;
  11331. request.path = "/users/subscriptions";
  11332. ASSERT_FALSE(matcher.match(request));
  11333. }
  11334. TEST(PathParamsTest, MultipleParams) {
  11335. const auto pattern = "/users/:userid/subscriptions/:subid";
  11336. detail::PathParamsMatcher matcher(pattern);
  11337. Request request;
  11338. request.path = "/users/42/subscriptions/2";
  11339. ASSERT_TRUE(matcher.match(request));
  11340. std::unordered_map<std::string, std::string> expected_params = {
  11341. {"userid", "42"}, {"subid", "2"}};
  11342. EXPECT_EQ(request.path_params, expected_params);
  11343. }
  11344. TEST(PathParamsTest, SequenceOfParams) {
  11345. const auto pattern = "/values/:x/:y/:z";
  11346. detail::PathParamsMatcher matcher(pattern);
  11347. Request request;
  11348. request.path = "/values/1/2/3";
  11349. ASSERT_TRUE(matcher.match(request));
  11350. std::unordered_map<std::string, std::string> expected_params = {
  11351. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11352. EXPECT_EQ(request.path_params, expected_params);
  11353. }
  11354. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11355. const auto pattern = "/prefix:suffix";
  11356. detail::PathParamsMatcher matcher(pattern);
  11357. Request request;
  11358. request.path = "/prefix:suffix";
  11359. ASSERT_TRUE(matcher.match(request));
  11360. const std::unordered_map<std::string, std::string> expected_params = {};
  11361. EXPECT_EQ(request.path_params, expected_params);
  11362. }
  11363. TEST(ParseUrlTest, VariousPatterns) {
  11364. {
  11365. detail::UrlComponents uc;
  11366. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11367. EXPECT_EQ("http", uc.scheme);
  11368. EXPECT_EQ("example.com", uc.host);
  11369. EXPECT_EQ("8080", uc.port);
  11370. EXPECT_EQ("/path", uc.path);
  11371. EXPECT_EQ("?q=1", uc.query);
  11372. }
  11373. {
  11374. detail::UrlComponents uc;
  11375. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11376. EXPECT_EQ("https", uc.scheme);
  11377. EXPECT_EQ("example.com", uc.host);
  11378. EXPECT_TRUE(uc.port.empty());
  11379. EXPECT_EQ("/path", uc.path);
  11380. }
  11381. {
  11382. detail::UrlComponents uc;
  11383. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11384. EXPECT_EQ("::1", uc.host);
  11385. EXPECT_EQ("8080", uc.port);
  11386. EXPECT_EQ("/path", uc.path);
  11387. }
  11388. {
  11389. detail::UrlComponents uc;
  11390. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11391. }
  11392. {
  11393. detail::UrlComponents uc;
  11394. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11395. EXPECT_TRUE(uc.scheme.empty());
  11396. EXPECT_EQ("example.com", uc.host);
  11397. EXPECT_EQ("/path", uc.path);
  11398. EXPECT_EQ("?q=1", uc.query);
  11399. }
  11400. {
  11401. detail::UrlComponents uc;
  11402. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11403. EXPECT_TRUE(uc.host.empty());
  11404. EXPECT_EQ("/path", uc.path);
  11405. EXPECT_EQ("?q=1", uc.query);
  11406. }
  11407. {
  11408. detail::UrlComponents uc;
  11409. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11410. EXPECT_EQ("example.com", uc.host);
  11411. EXPECT_EQ("8080", uc.port);
  11412. }
  11413. {
  11414. // Unix socket path — must not be parsed as host
  11415. detail::UrlComponents uc;
  11416. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11417. EXPECT_TRUE(uc.host.empty());
  11418. }
  11419. {
  11420. detail::UrlComponents uc;
  11421. ASSERT_TRUE(detail::parse_url("", uc));
  11422. EXPECT_TRUE(uc.host.empty());
  11423. EXPECT_TRUE(uc.path.empty());
  11424. }
  11425. {
  11426. detail::UrlComponents uc;
  11427. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11428. }
  11429. {
  11430. detail::UrlComponents uc;
  11431. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11432. }
  11433. {
  11434. // Accepted by parse_url; callers restrict to http/https
  11435. detail::UrlComponents uc;
  11436. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11437. EXPECT_EQ("ftp", uc.scheme);
  11438. }
  11439. {
  11440. detail::UrlComponents uc;
  11441. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11442. }
  11443. {
  11444. detail::UrlComponents uc;
  11445. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11446. }
  11447. }
  11448. TEST(ParseUrlTest, FragmentHandling) {
  11449. {
  11450. detail::UrlComponents uc;
  11451. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11452. EXPECT_EQ("/path", uc.path);
  11453. EXPECT_TRUE(uc.query.empty());
  11454. }
  11455. {
  11456. detail::UrlComponents uc;
  11457. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11458. EXPECT_TRUE(uc.path.empty());
  11459. EXPECT_TRUE(uc.query.empty());
  11460. }
  11461. }
  11462. TEST(ParseUrlTest, UserinfoHandling) {
  11463. // Userinfo with @ but no colon — host includes @
  11464. detail::UrlComponents uc;
  11465. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11466. EXPECT_EQ("user@host.com", uc.host);
  11467. EXPECT_EQ("/path", uc.path);
  11468. }
  11469. TEST(ParseUrlTest, IPv6EdgeCases) {
  11470. {
  11471. detail::UrlComponents uc;
  11472. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11473. EXPECT_TRUE(uc.scheme.empty());
  11474. EXPECT_EQ("::1", uc.host);
  11475. EXPECT_EQ("8080", uc.port);
  11476. }
  11477. {
  11478. // Zone ID '%25' is not in [a-fA-F0-9:]
  11479. detail::UrlComponents uc;
  11480. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11481. }
  11482. }
  11483. TEST(ParseUrlTest, SchemeEdgeCases) {
  11484. {
  11485. detail::UrlComponents uc;
  11486. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11487. }
  11488. {
  11489. detail::UrlComponents uc;
  11490. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11491. }
  11492. {
  11493. detail::UrlComponents uc;
  11494. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11495. }
  11496. }
  11497. TEST(ParseUrlTest, PortEdgeCases) {
  11498. {
  11499. detail::UrlComponents uc;
  11500. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11501. EXPECT_TRUE(uc.port.empty());
  11502. EXPECT_EQ("/path", uc.path);
  11503. }
  11504. {
  11505. // parse_url accepts any port string; validation is done by parse_port
  11506. detail::UrlComponents uc;
  11507. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11508. EXPECT_EQ("abc", uc.port);
  11509. }
  11510. }
  11511. TEST(ParseUrlTest, WebSocketPatterns) {
  11512. {
  11513. detail::UrlComponents uc;
  11514. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11515. EXPECT_EQ("ws", uc.scheme);
  11516. EXPECT_EQ("echo.example.com", uc.host);
  11517. EXPECT_EQ("8080", uc.port);
  11518. EXPECT_EQ("/ws", uc.path);
  11519. }
  11520. {
  11521. detail::UrlComponents uc;
  11522. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11523. EXPECT_EQ("wss", uc.scheme);
  11524. EXPECT_EQ("echo.example.com", uc.host);
  11525. EXPECT_TRUE(uc.port.empty());
  11526. EXPECT_EQ("/ws", uc.path);
  11527. }
  11528. }
  11529. TEST(ParseUrlTest, QueryOnly) {
  11530. detail::UrlComponents uc;
  11531. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11532. EXPECT_TRUE(uc.host.empty());
  11533. EXPECT_TRUE(uc.path.empty());
  11534. EXPECT_EQ("?q=1&r=2", uc.query);
  11535. }
  11536. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11537. detail::UrlComponents uc;
  11538. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11539. EXPECT_TRUE(uc.scheme.empty());
  11540. EXPECT_EQ("example.com", uc.host);
  11541. EXPECT_EQ("443", uc.port);
  11542. EXPECT_EQ("/path", uc.path);
  11543. }
  11544. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11545. // If ipv6 regex working, regex match codepath is taken.
  11546. // else port will default to 80 in Client impl
  11547. int clientImplMagicPort = 80;
  11548. int port = 4321;
  11549. // above ports must be different to avoid false negative
  11550. EXPECT_NE(clientImplMagicPort, port);
  11551. std::string ipV6TestURL = "http://[ff06::c3]";
  11552. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11553. CLIENT_PRIVATE_KEY_FILE);
  11554. EXPECT_EQ(cli.port(), port);
  11555. }
  11556. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11557. auto file_path = "./www/dir/index.html";
  11558. auto dir_path = "./www/dir";
  11559. detail::FileStat stat_file(file_path);
  11560. EXPECT_TRUE(stat_file.is_file());
  11561. EXPECT_FALSE(stat_file.is_dir());
  11562. detail::FileStat stat_dir(dir_path);
  11563. EXPECT_FALSE(stat_dir.is_file());
  11564. EXPECT_TRUE(stat_dir.is_dir());
  11565. }
  11566. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11567. // IPv4 with default HTTP port (80)
  11568. EXPECT_EQ("example.com",
  11569. detail::make_host_and_port_string("example.com", 80, false));
  11570. // IPv4 with default HTTPS port (443)
  11571. EXPECT_EQ("example.com",
  11572. detail::make_host_and_port_string("example.com", 443, true));
  11573. // IPv4 with non-default HTTP port
  11574. EXPECT_EQ("example.com:8080",
  11575. detail::make_host_and_port_string("example.com", 8080, false));
  11576. // IPv4 with non-default HTTPS port
  11577. EXPECT_EQ("example.com:8443",
  11578. detail::make_host_and_port_string("example.com", 8443, true));
  11579. // IPv6 with default HTTP port (80)
  11580. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11581. // IPv6 with default HTTPS port (443)
  11582. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11583. // IPv6 with non-default HTTP port
  11584. EXPECT_EQ("[::1]:8080",
  11585. detail::make_host_and_port_string("::1", 8080, false));
  11586. // IPv6 with non-default HTTPS port
  11587. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11588. // IPv6 full address with default port
  11589. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11590. detail::make_host_and_port_string(
  11591. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11592. // IPv6 full address with non-default port
  11593. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11594. detail::make_host_and_port_string(
  11595. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11596. // IPv6 localhost with non-default port
  11597. EXPECT_EQ("[::1]:3000",
  11598. detail::make_host_and_port_string("::1", 3000, false));
  11599. // IPv6 with zone ID (link-local address) with default port
  11600. EXPECT_EQ("[fe80::1%eth0]",
  11601. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11602. // IPv6 with zone ID (link-local address) with non-default port
  11603. EXPECT_EQ("[fe80::1%eth0]:8080",
  11604. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11605. // Edge case: Port 443 with is_ssl=false (should add port)
  11606. EXPECT_EQ("example.com:443",
  11607. detail::make_host_and_port_string("example.com", 443, false));
  11608. // Edge case: Port 80 with is_ssl=true (should add port)
  11609. EXPECT_EQ("example.com:80",
  11610. detail::make_host_and_port_string("example.com", 80, true));
  11611. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11612. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11613. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11614. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11615. // Security fix: Already bracketed IPv6 should not get double brackets
  11616. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11617. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11618. EXPECT_EQ("[::1]:8080",
  11619. detail::make_host_and_port_string("[::1]", 8080, false));
  11620. EXPECT_EQ("[2001:db8::1]:8080",
  11621. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11622. EXPECT_EQ("[fe80::1%eth0]",
  11623. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11624. EXPECT_EQ("[fe80::1%eth0]:8080",
  11625. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11626. // Edge case: Empty host (should return as-is)
  11627. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11628. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11629. // This is a known limitation but shouldn't crash
  11630. EXPECT_EQ("[host:name]",
  11631. detail::make_host_and_port_string("host:name", 80, false));
  11632. // Port number edge cases (no validation, but should not crash)
  11633. EXPECT_EQ("example.com:0",
  11634. detail::make_host_and_port_string("example.com", 0, false));
  11635. EXPECT_EQ("example.com:-1",
  11636. detail::make_host_and_port_string("example.com", -1, false));
  11637. EXPECT_EQ("example.com:65535",
  11638. detail::make_host_and_port_string("example.com", 65535, false));
  11639. EXPECT_EQ("example.com:65536",
  11640. detail::make_host_and_port_string("example.com", 65536, false));
  11641. }
  11642. #ifdef CPPHTTPLIB_SSL_ENABLED
  11643. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11644. httplib::SSLClient cli("roblox.com", 443);
  11645. cli.set_follow_location(true);
  11646. auto res = cli.Get("/");
  11647. ASSERT_TRUE(res);
  11648. EXPECT_EQ(StatusCode::OK_200, res->status);
  11649. }
  11650. #endif
  11651. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11652. Server svr;
  11653. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11654. EXPECT_EQ(res.status, 400);
  11655. });
  11656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. thread.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. Client cli(HOST, PORT);
  11664. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11665. }
  11666. TEST(InvalidHeaderCharsTest, is_field_name) {
  11667. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11668. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11669. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11670. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11671. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11672. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11673. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11674. EXPECT_FALSE(detail::fields::is_field_name(""));
  11675. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11676. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11677. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11678. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11679. }
  11680. TEST(InvalidHeaderCharsTest, is_field_value) {
  11681. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11682. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11683. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11684. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11685. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11686. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11687. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11688. EXPECT_TRUE(detail::fields::is_field_value(""));
  11689. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11690. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11691. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11692. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11693. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11694. }
  11695. TEST(InvalidHeaderCharsTest, OnServer) {
  11696. Server svr;
  11697. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11698. std::string header = "Not Set";
  11699. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11700. res.set_header(header, "value");
  11701. res.set_content("Page Content Page Content", "text/plain");
  11702. });
  11703. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11704. std::string header = "Not Set";
  11705. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11706. res.set_header("X-Test", header);
  11707. res.set_content("Page Content Page Content", "text/plain");
  11708. });
  11709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11710. auto se = detail::scope_exit([&] {
  11711. svr.stop();
  11712. thread.join();
  11713. ASSERT_FALSE(svr.is_running());
  11714. });
  11715. svr.wait_until_ready();
  11716. Client cli(HOST, PORT);
  11717. {
  11718. auto res = cli.Get(
  11719. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11720. ASSERT_TRUE(res);
  11721. EXPECT_EQ("Page Content Page Content", res->body);
  11722. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11723. }
  11724. {
  11725. auto res = cli.Get(
  11726. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11727. ASSERT_TRUE(res);
  11728. EXPECT_EQ("Page Content Page Content", res->body);
  11729. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11730. }
  11731. }
  11732. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11733. auto handled = false;
  11734. Server svr;
  11735. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11736. thread t = thread([&] { svr.listen(HOST, PORT); });
  11737. auto se = detail::scope_exit([&] {
  11738. svr.stop();
  11739. t.join();
  11740. ASSERT_FALSE(svr.is_running());
  11741. ASSERT_FALSE(handled);
  11742. });
  11743. svr.wait_until_ready();
  11744. auto req = "POST /test HTTP/1.1\r\n"
  11745. "Content-Length: x\r\n"
  11746. "\r\n";
  11747. std::string response;
  11748. ASSERT_TRUE(send_request(1, req, &response));
  11749. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11750. response.substr(0, response.find("\r\n")));
  11751. }
  11752. #ifndef _WIN32
  11753. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11754. static constexpr char reject[] = "Unauthorized";
  11755. static constexpr char accept[] = "Upload accepted";
  11756. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11757. Server svr;
  11758. svr.set_expect_100_continue_handler(
  11759. [](const Request & /*req*/, Response &res) {
  11760. res.status = StatusCode::Unauthorized_401;
  11761. res.set_content(reject, "text/plain");
  11762. return res.status;
  11763. });
  11764. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11765. res.set_content(accept, "text/plain");
  11766. });
  11767. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11768. auto se = detail::scope_exit([&] {
  11769. svr.stop();
  11770. thread.join();
  11771. ASSERT_FALSE(svr.is_running());
  11772. });
  11773. svr.wait_until_ready();
  11774. {
  11775. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11776. curl_easy_init(), &curl_easy_cleanup};
  11777. ASSERT_NE(curl, nullptr);
  11778. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11779. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11780. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11781. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11782. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11783. &curl_slist_free_all};
  11784. ASSERT_NE(list, nullptr);
  11785. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11786. struct read_data {
  11787. size_t read_size;
  11788. size_t total_size;
  11789. } data = {0, total_size};
  11790. using read_callback_t =
  11791. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11792. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11793. void *userdata) -> size_t {
  11794. read_data *d = (read_data *)userdata;
  11795. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11796. std::fill_n(ptr, size * nmemb, 'A');
  11797. d->read_size += size * nmemb;
  11798. return size * nmemb;
  11799. };
  11800. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11801. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11802. std::vector<char> buffer;
  11803. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11804. using write_callback_t =
  11805. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11806. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11807. void *userdata) -> size_t {
  11808. std::vector<char> *buf = (std::vector<char> *)userdata;
  11809. buf->reserve(buf->size() + size * nmemb + 1);
  11810. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11811. return size * nmemb;
  11812. };
  11813. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11814. {
  11815. const auto res = curl_easy_perform(curl.get());
  11816. ASSERT_EQ(res, CURLE_OK);
  11817. }
  11818. {
  11819. auto response_code = long{};
  11820. const auto res =
  11821. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11822. ASSERT_EQ(res, CURLE_OK);
  11823. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11824. }
  11825. {
  11826. auto dl = curl_off_t{};
  11827. const auto res =
  11828. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11829. ASSERT_EQ(res, CURLE_OK);
  11830. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11831. }
  11832. {
  11833. buffer.push_back('\0');
  11834. ASSERT_STRCASEEQ(buffer.data(), reject);
  11835. }
  11836. }
  11837. }
  11838. #endif
  11839. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11840. // Regression test for #2458.
  11841. //
  11842. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11843. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11844. // ticket can make the client socket spuriously readable during the
  11845. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11846. // the client withholds the body and then blocks reading a response that never
  11847. // comes, failing with `Failed to read connection`.
  11848. //
  11849. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11850. // within the timeout. This raw OpenSSL server deliberately never sends
  11851. // `100 Continue`; the client must still deliver the body and receive 200.
  11852. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11853. signal(SIGPIPE, SIG_IGN);
  11854. const auto port = PORT + 4;
  11855. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11856. ASSERT_NE(srv, INVALID_SOCKET);
  11857. int opt = 1;
  11858. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11859. sockaddr_in addr{};
  11860. addr.sin_family = AF_INET;
  11861. addr.sin_port = htons(static_cast<uint16_t>(port));
  11862. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11863. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11864. ASSERT_EQ(0, ::listen(srv, 1));
  11865. std::atomic<size_t> server_body_bytes{0};
  11866. auto server_thread = std::thread([&] {
  11867. sockaddr_in cli_addr{};
  11868. socklen_t cli_len = sizeof(cli_addr);
  11869. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11870. if (cli == INVALID_SOCKET) { return; }
  11871. // Bound the lifetime of the server side so a buggy client (which never
  11872. // sends the body) cannot make this thread block forever on join.
  11873. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11874. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11875. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11876. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11877. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11878. SSL *ssl = SSL_new(ctx);
  11879. SSL_set_fd(ssl, static_cast<int>(cli));
  11880. if (SSL_accept(ssl) > 0) {
  11881. // Read the request headers. Reading here also flushes the TLS 1.3
  11882. // session tickets to the client. Deliberately do NOT send
  11883. // `100 Continue`.
  11884. std::string buf;
  11885. char tmp[1024];
  11886. while (buf.find("\r\n\r\n") == std::string::npos) {
  11887. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11888. if (n <= 0) { break; }
  11889. buf.append(tmp, static_cast<size_t>(n));
  11890. }
  11891. // A correct client sends the body now; count what arrives.
  11892. auto pos = buf.find("\r\n\r\n");
  11893. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11894. while (body < 4096) {
  11895. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11896. if (n <= 0) { break; }
  11897. body += static_cast<size_t>(n);
  11898. }
  11899. server_body_bytes = body;
  11900. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11901. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11902. SSL_shutdown(ssl);
  11903. }
  11904. SSL_free(ssl);
  11905. detail::close_socket(cli);
  11906. SSL_CTX_free(ctx);
  11907. });
  11908. auto se = detail::scope_exit([&] {
  11909. server_thread.join();
  11910. detail::close_socket(srv);
  11911. });
  11912. SSLClient cli("127.0.0.1", port);
  11913. cli.enable_server_certificate_verification(false);
  11914. cli.set_connection_timeout(5, 0);
  11915. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11916. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11917. std::string body(4096, 'A');
  11918. auto res = cli.Put("/api/test", body, "application/json");
  11919. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11920. EXPECT_EQ(StatusCode::OK_200, res->status);
  11921. EXPECT_EQ(body.size(), server_body_bytes.load());
  11922. }
  11923. #endif
  11924. template <typename S, typename C>
  11925. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11926. svr.Get("/stream", [&](const Request &, Response &res) {
  11927. auto data = new std::string("01234567890123456789");
  11928. res.set_content_provider(
  11929. data->size(), "text/plain",
  11930. [&, data](size_t offset, size_t length, DataSink &sink) {
  11931. const size_t DATA_CHUNK_SIZE = 4;
  11932. const auto &d = *data;
  11933. std::this_thread::sleep_for(std::chrono::seconds(1));
  11934. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11935. return true;
  11936. },
  11937. [data](bool success) {
  11938. EXPECT_FALSE(success);
  11939. delete data;
  11940. });
  11941. });
  11942. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11943. auto i = new size_t(0);
  11944. res.set_content_provider(
  11945. "text/plain",
  11946. [i](size_t, DataSink &sink) {
  11947. if (*i < 5) {
  11948. std::this_thread::sleep_for(std::chrono::seconds(1));
  11949. sink.write("abcd", 4);
  11950. (*i)++;
  11951. } else {
  11952. sink.done();
  11953. }
  11954. return true;
  11955. },
  11956. [i](bool success) {
  11957. EXPECT_FALSE(success);
  11958. delete i;
  11959. });
  11960. });
  11961. svr.Get("/chunked", [&](const Request &, Response &res) {
  11962. auto i = new size_t(0);
  11963. res.set_chunked_content_provider(
  11964. "text/plain",
  11965. [i](size_t, DataSink &sink) {
  11966. if (*i < 5) {
  11967. std::this_thread::sleep_for(std::chrono::seconds(1));
  11968. sink.os << "abcd";
  11969. (*i)++;
  11970. } else {
  11971. sink.done();
  11972. }
  11973. return true;
  11974. },
  11975. [i](bool success) {
  11976. EXPECT_FALSE(success);
  11977. delete i;
  11978. });
  11979. });
  11980. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. listen_thread.join();
  11984. ASSERT_FALSE(svr.is_running());
  11985. });
  11986. svr.wait_until_ready();
  11987. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11988. {
  11989. auto start = std::chrono::steady_clock::now();
  11990. auto res = cli.Get("/stream");
  11991. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11992. std::chrono::steady_clock::now() - start)
  11993. .count();
  11994. ASSERT_FALSE(res);
  11995. EXPECT_EQ(Error::Read, res.error());
  11996. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11997. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11998. }
  11999. {
  12000. auto start = std::chrono::steady_clock::now();
  12001. auto res = cli.Get("/stream_without_length");
  12002. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12003. std::chrono::steady_clock::now() - start)
  12004. .count();
  12005. ASSERT_FALSE(res);
  12006. EXPECT_EQ(Error::Read, res.error());
  12007. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12008. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12009. }
  12010. {
  12011. auto start = std::chrono::steady_clock::now();
  12012. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12013. EXPECT_EQ("abcd", string(data, data_length));
  12014. return true;
  12015. });
  12016. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12017. std::chrono::steady_clock::now() - start)
  12018. .count();
  12019. ASSERT_FALSE(res);
  12020. EXPECT_EQ(Error::Read, res.error());
  12021. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12022. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12023. }
  12024. }
  12025. TEST(MaxTimeoutTest, ContentStream) {
  12026. time_t timeout = 2000;
  12027. time_t threshold = 200;
  12028. Server svr;
  12029. Client cli("localhost", PORT);
  12030. max_timeout_test(svr, cli, timeout, threshold);
  12031. }
  12032. #ifdef CPPHTTPLIB_SSL_ENABLED
  12033. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12034. time_t timeout = 2000;
  12035. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12036. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12037. SSLClient cli("localhost", PORT);
  12038. cli.enable_server_certificate_verification(false);
  12039. max_timeout_test(svr, cli, timeout, threshold);
  12040. }
  12041. #endif
  12042. class EventDispatcher {
  12043. public:
  12044. EventDispatcher() {}
  12045. bool wait_event(DataSink *sink) {
  12046. unique_lock<mutex> lk(m_);
  12047. int id = id_;
  12048. // Wait with timeout to prevent hanging if client disconnects
  12049. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12050. [&] { return cid_ == id; })) {
  12051. return false; // Timeout occurred
  12052. }
  12053. sink->write(message_.data(), message_.size());
  12054. return true;
  12055. }
  12056. void send_event(const string &message) {
  12057. lock_guard<mutex> lk(m_);
  12058. cid_ = id_++;
  12059. message_ = message;
  12060. cv_.notify_all();
  12061. }
  12062. private:
  12063. mutex m_;
  12064. condition_variable cv_;
  12065. atomic_int id_{0};
  12066. atomic_int cid_{-1};
  12067. string message_;
  12068. };
  12069. TEST(ClientInThreadTest, Issue2068) {
  12070. EventDispatcher ed;
  12071. Server svr;
  12072. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12073. res.set_chunked_content_provider("text/event-stream",
  12074. [&](size_t /*offset*/, DataSink &sink) {
  12075. return ed.wait_event(&sink);
  12076. });
  12077. });
  12078. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12079. svr.wait_until_ready();
  12080. thread event_thread([&] {
  12081. int id = 0;
  12082. while (svr.is_running()) {
  12083. this_thread::sleep_for(chrono::milliseconds(500));
  12084. std::stringstream ss;
  12085. ss << "data: " << id << "\n\n";
  12086. ed.send_event(ss.str());
  12087. id++;
  12088. }
  12089. });
  12090. auto se = detail::scope_exit([&] {
  12091. svr.stop();
  12092. listen_thread.join();
  12093. event_thread.join();
  12094. ASSERT_FALSE(svr.is_running());
  12095. });
  12096. {
  12097. auto client = detail::make_unique<Client>(HOST, PORT);
  12098. client->set_read_timeout(std::chrono::minutes(10));
  12099. std::atomic<bool> stop{false};
  12100. std::thread t([&] {
  12101. client->Get("/event1",
  12102. [&](const char *, size_t) -> bool { return !stop; });
  12103. });
  12104. std::this_thread::sleep_for(std::chrono::seconds(2));
  12105. stop = true;
  12106. client->stop();
  12107. t.join();
  12108. // Reset client after thread has finished
  12109. client.reset();
  12110. }
  12111. }
  12112. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12113. auto handled = false;
  12114. Server svr;
  12115. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12117. auto se = detail::scope_exit([&] {
  12118. svr.stop();
  12119. t.join();
  12120. ASSERT_FALSE(svr.is_running());
  12121. ASSERT_FALSE(handled);
  12122. });
  12123. svr.wait_until_ready();
  12124. // Two Content-Length headers with different values — must be rejected
  12125. auto req = "POST /test HTTP/1.1\r\n"
  12126. "Content-Length: 5\r\n"
  12127. "Content-Length: 10\r\n"
  12128. "\r\n"
  12129. "hello";
  12130. std::string response;
  12131. ASSERT_TRUE(send_request(1, req, &response));
  12132. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12133. response.substr(0, response.find("\r\n")));
  12134. }
  12135. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12136. auto handled = false;
  12137. Server svr;
  12138. svr.Post("/test", [&](const Request &, Response &res) {
  12139. handled = true;
  12140. res.set_content("ok", "text/plain");
  12141. });
  12142. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12143. auto se = detail::scope_exit([&] {
  12144. svr.stop();
  12145. t.join();
  12146. ASSERT_FALSE(svr.is_running());
  12147. ASSERT_TRUE(handled);
  12148. });
  12149. svr.wait_until_ready();
  12150. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12151. auto req = "POST /test HTTP/1.1\r\n"
  12152. "Content-Length: 5\r\n"
  12153. "Content-Length: 5\r\n"
  12154. "\r\n"
  12155. "hello";
  12156. std::string response;
  12157. ASSERT_TRUE(send_request(1, req, &response));
  12158. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12159. }
  12160. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12161. Server svr;
  12162. svr.Get("/", [](const Request &req, Response &res) {
  12163. EXPECT_EQ(2U, req.trailers.size());
  12164. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12165. // Denied
  12166. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12167. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12168. // Accepted
  12169. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12170. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12171. EXPECT_TRUE(req.has_trailer("X-World"));
  12172. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12173. res.set_content("ok", "text/plain");
  12174. });
  12175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. t.join();
  12179. ASSERT_FALSE(svr.is_running());
  12180. });
  12181. svr.wait_until_ready();
  12182. const std::string req = "GET / HTTP/1.1\r\n"
  12183. "Transfer-Encoding: chunked\r\n"
  12184. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12185. "\r\n"
  12186. "0\r\n"
  12187. "Content-Length: 10\r\n"
  12188. "Host: internal.local\r\n"
  12189. "Content-Type: malicious/content\r\n"
  12190. "Cookie: any\r\n"
  12191. "Set-Cookie: any\r\n"
  12192. "X-Forwarded-For: attacker.com\r\n"
  12193. "X-Real-Ip: 1.1.1.1\r\n"
  12194. "X-Hello: hello\r\n"
  12195. "X-World: world\r\n"
  12196. "\r\n";
  12197. std::string res;
  12198. ASSERT_TRUE(send_request(1, req, &res));
  12199. }
  12200. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12201. Server svr;
  12202. std::string observed_remote_addr;
  12203. std::string observed_xff;
  12204. svr.Get("/ip", [&](const Request &req, Response &res) {
  12205. observed_remote_addr = req.remote_addr;
  12206. observed_xff = req.get_header_value("X-Forwarded-For");
  12207. res.set_content("ok", "text/plain");
  12208. });
  12209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. t.join();
  12213. ASSERT_FALSE(svr.is_running());
  12214. });
  12215. svr.wait_until_ready();
  12216. Client cli(HOST, PORT);
  12217. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12218. ASSERT_TRUE(res);
  12219. EXPECT_EQ(StatusCode::OK_200, res->status);
  12220. EXPECT_EQ(observed_xff, "203.0.113.66");
  12221. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12222. observed_remote_addr == "127.0.0.1");
  12223. }
  12224. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12225. Server svr;
  12226. svr.set_trusted_proxies({"203.0.113.66"});
  12227. std::string observed_remote_addr;
  12228. std::string observed_xff;
  12229. svr.Get("/ip", [&](const Request &req, Response &res) {
  12230. observed_remote_addr = req.remote_addr;
  12231. observed_xff = req.get_header_value("X-Forwarded-For");
  12232. res.set_content("ok", "text/plain");
  12233. });
  12234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12235. auto se = detail::scope_exit([&] {
  12236. svr.stop();
  12237. t.join();
  12238. ASSERT_FALSE(svr.is_running());
  12239. });
  12240. svr.wait_until_ready();
  12241. Client cli(HOST, PORT);
  12242. auto res = cli.Get("/ip");
  12243. ASSERT_TRUE(res);
  12244. EXPECT_EQ(StatusCode::OK_200, res->status);
  12245. EXPECT_EQ(observed_xff, "");
  12246. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12247. observed_remote_addr == "127.0.0.1");
  12248. }
  12249. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12250. Server svr;
  12251. svr.set_trusted_proxies({"203.0.113.66"});
  12252. std::string observed_remote_addr;
  12253. std::string observed_xff;
  12254. svr.Get("/ip", [&](const Request &req, Response &res) {
  12255. observed_remote_addr = req.remote_addr;
  12256. observed_xff = req.get_header_value("X-Forwarded-For");
  12257. res.set_content("ok", "text/plain");
  12258. });
  12259. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12260. auto se = detail::scope_exit([&] {
  12261. svr.stop();
  12262. t.join();
  12263. ASSERT_FALSE(svr.is_running());
  12264. });
  12265. svr.wait_until_ready();
  12266. Client cli(HOST, PORT);
  12267. auto res =
  12268. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12269. ASSERT_TRUE(res);
  12270. EXPECT_EQ(StatusCode::OK_200, res->status);
  12271. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12272. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12273. }
  12274. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12275. Server svr;
  12276. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12277. std::string observed_remote_addr;
  12278. std::string observed_xff;
  12279. svr.Get("/ip", [&](const Request &req, Response &res) {
  12280. observed_remote_addr = req.remote_addr;
  12281. observed_xff = req.get_header_value("X-Forwarded-For");
  12282. res.set_content("ok", "text/plain");
  12283. });
  12284. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12285. auto se = detail::scope_exit([&] {
  12286. svr.stop();
  12287. t.join();
  12288. ASSERT_FALSE(svr.is_running());
  12289. });
  12290. svr.wait_until_ready();
  12291. Client cli(HOST, PORT);
  12292. auto res = cli.Get(
  12293. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12294. ASSERT_TRUE(res);
  12295. EXPECT_EQ(StatusCode::OK_200, res->status);
  12296. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12297. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12298. }
  12299. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12300. Server svr;
  12301. svr.set_trusted_proxies({"192.0.2.45"});
  12302. std::string observed_remote_addr;
  12303. std::string observed_xff;
  12304. svr.Get("/ip", [&](const Request &req, Response &res) {
  12305. observed_remote_addr = req.remote_addr;
  12306. observed_xff = req.get_header_value("X-Forwarded-For");
  12307. res.set_content("ok", "text/plain");
  12308. });
  12309. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12310. auto se = detail::scope_exit([&] {
  12311. svr.stop();
  12312. t.join();
  12313. ASSERT_FALSE(svr.is_running());
  12314. });
  12315. svr.wait_until_ready();
  12316. Client cli(HOST, PORT);
  12317. auto res =
  12318. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12319. ASSERT_TRUE(res);
  12320. EXPECT_EQ(StatusCode::OK_200, res->status);
  12321. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12322. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12323. }
  12324. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12325. Server svr;
  12326. svr.set_trusted_proxies({"192.0.2.45"});
  12327. std::string observed_remote_addr;
  12328. std::string observed_xff;
  12329. svr.Get("/ip", [&](const Request &req, Response &res) {
  12330. observed_remote_addr = req.remote_addr;
  12331. observed_xff = req.get_header_value("X-Forwarded-For");
  12332. res.set_content("ok", "text/plain");
  12333. });
  12334. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12335. auto se = detail::scope_exit([&] {
  12336. svr.stop();
  12337. t.join();
  12338. ASSERT_FALSE(svr.is_running());
  12339. });
  12340. svr.wait_until_ready();
  12341. Client cli(HOST, PORT);
  12342. auto res = cli.Get(
  12343. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12344. ASSERT_TRUE(res);
  12345. EXPECT_EQ(StatusCode::OK_200, res->status);
  12346. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12347. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12348. }
  12349. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12350. Server svr;
  12351. svr.set_trusted_proxies({"192.0.2.45"});
  12352. std::string observed_remote_addr;
  12353. std::string observed_xff;
  12354. svr.Get("/ip", [&](const Request &req, Response &res) {
  12355. observed_remote_addr = req.remote_addr;
  12356. observed_xff = req.get_header_value("X-Forwarded-For");
  12357. res.set_content("ok", "text/plain");
  12358. });
  12359. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. ASSERT_FALSE(svr.is_running());
  12364. });
  12365. svr.wait_until_ready();
  12366. std::string raw_req =
  12367. "GET /ip HTTP/1.1\r\n"
  12368. "Host: localhost\r\n"
  12369. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12370. "Connection: close\r\n"
  12371. "\r\n";
  12372. std::string out;
  12373. ASSERT_TRUE(send_request(5, raw_req, &out));
  12374. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12375. // Header parser trims surrounding whitespace of the header value
  12376. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12377. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12378. }
  12379. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12380. // crash the server (it used to call front() on an empty vector inside
  12381. // get_client_ip). The connection-level remote address must be retained instead.
  12382. static void run_malformed_xff_test(const std::string &xff_value) {
  12383. Server svr;
  12384. svr.set_trusted_proxies({"192.0.2.45"});
  12385. std::string observed_remote_addr;
  12386. svr.Get("/ip", [&](const Request &req, Response &res) {
  12387. observed_remote_addr = req.remote_addr;
  12388. res.set_content("ok", "text/plain");
  12389. });
  12390. int port = 0;
  12391. thread t = thread([&]() {
  12392. port = svr.bind_to_any_port(HOST);
  12393. svr.listen_after_bind();
  12394. });
  12395. auto se = detail::scope_exit([&] {
  12396. svr.stop();
  12397. t.join();
  12398. ASSERT_FALSE(svr.is_running());
  12399. });
  12400. svr.wait_until_ready();
  12401. Client cli(HOST, port);
  12402. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12403. ASSERT_TRUE(res);
  12404. EXPECT_EQ(StatusCode::OK_200, res->status);
  12405. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12406. observed_remote_addr == "127.0.0.1");
  12407. }
  12408. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12409. run_malformed_xff_test("");
  12410. }
  12411. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12412. run_malformed_xff_test(",");
  12413. }
  12414. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12415. run_malformed_xff_test(", , ,");
  12416. }
  12417. #ifndef _WIN32
  12418. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12419. Server svr;
  12420. svr.Post("/post", [&](const Request &req, Response &res) {
  12421. res.set_content(req.body, "text/plain");
  12422. });
  12423. svr.Put("/put", [&](const Request &req, Response &res) {
  12424. res.set_content(req.body, "text/plain");
  12425. });
  12426. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12427. res.set_content(req.body, "text/plain");
  12428. });
  12429. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12430. res.set_content(req.body, "text/plain");
  12431. });
  12432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12433. auto se = detail::scope_exit([&] {
  12434. svr.stop();
  12435. t.join();
  12436. ASSERT_FALSE(svr.is_running());
  12437. });
  12438. svr.wait_until_ready();
  12439. std::string resp;
  12440. // POST without Content-Length
  12441. ASSERT_TRUE(send_request(5,
  12442. "POST /post HTTP/1.1\r\n"
  12443. "Host: localhost\r\n"
  12444. "Connection: close\r\n"
  12445. "\r\n",
  12446. &resp));
  12447. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12448. // PUT without Content-Length
  12449. resp.clear();
  12450. ASSERT_TRUE(send_request(5,
  12451. "PUT /put HTTP/1.1\r\n"
  12452. "Host: localhost\r\n"
  12453. "Connection: close\r\n"
  12454. "\r\n",
  12455. &resp));
  12456. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12457. // PATCH without Content-Length
  12458. resp.clear();
  12459. ASSERT_TRUE(send_request(5,
  12460. "PATCH /patch HTTP/1.1\r\n"
  12461. "Host: localhost\r\n"
  12462. "Connection: close\r\n"
  12463. "\r\n",
  12464. &resp));
  12465. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12466. // DELETE without Content-Length
  12467. resp.clear();
  12468. ASSERT_TRUE(send_request(5,
  12469. "DELETE /delete HTTP/1.1\r\n"
  12470. "Host: localhost\r\n"
  12471. "Connection: close\r\n"
  12472. "\r\n",
  12473. &resp));
  12474. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12475. }
  12476. #endif
  12477. //==============================================================================
  12478. // open_stream() Tests
  12479. //==============================================================================
  12480. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12481. std::string result;
  12482. char buf[8192];
  12483. ssize_t n;
  12484. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12485. result.append(buf, static_cast<size_t>(n));
  12486. }
  12487. return result;
  12488. }
  12489. // Mock stream for unit tests
  12490. class MockStream : public Stream {
  12491. public:
  12492. std::string data;
  12493. size_t pos = 0;
  12494. ssize_t error_after = -1; // -1 = no error
  12495. explicit MockStream(const std::string &d, ssize_t err = -1)
  12496. : data(d), error_after(err) {}
  12497. bool is_readable() const override { return true; }
  12498. bool wait_readable() const override { return true; }
  12499. bool wait_writable() const override { return true; }
  12500. ssize_t read(char *ptr, size_t size) override {
  12501. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12502. if (pos >= data.size()) return 0;
  12503. size_t limit =
  12504. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12505. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12506. std::memcpy(ptr, data.data() + pos, to_read);
  12507. pos += to_read;
  12508. return static_cast<ssize_t>(to_read);
  12509. }
  12510. ssize_t write(const char *, size_t) override { return -1; }
  12511. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12512. ip = "127.0.0.1";
  12513. port = 0;
  12514. }
  12515. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12516. ip = "127.0.0.1";
  12517. port = 0;
  12518. }
  12519. socket_t socket() const override { return INVALID_SOCKET; }
  12520. time_t duration() const override { return 0; }
  12521. };
  12522. TEST(StreamHandleTest, Basic) {
  12523. ClientImpl::StreamHandle handle;
  12524. EXPECT_FALSE(handle.is_valid());
  12525. handle.response = detail::make_unique<Response>();
  12526. handle.error = Error::Connection;
  12527. EXPECT_FALSE(handle.is_valid());
  12528. handle.error = Error::Success;
  12529. EXPECT_TRUE(handle.is_valid());
  12530. }
  12531. TEST(BodyReaderTest, Basic) {
  12532. MockStream stream("Hello, World!");
  12533. detail::BodyReader reader;
  12534. reader.stream = &stream;
  12535. reader.content_length = 13;
  12536. char buf[32];
  12537. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12538. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12539. EXPECT_TRUE(reader.eof);
  12540. }
  12541. TEST(BodyReaderTest, NoStream) {
  12542. detail::BodyReader reader;
  12543. char buf[32];
  12544. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12545. EXPECT_EQ(Error::Connection, reader.last_error);
  12546. }
  12547. TEST(BodyReaderTest, Error) {
  12548. MockStream stream("Hello, World!", 5);
  12549. detail::BodyReader reader;
  12550. reader.stream = &stream;
  12551. reader.content_length = 13;
  12552. char buf[32];
  12553. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12554. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12555. EXPECT_EQ(Error::Read, reader.last_error);
  12556. }
  12557. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12558. // Mock-based StreamHandle tests relying on private internals are removed.
  12559. class OpenStreamTest : public ::testing::Test {
  12560. protected:
  12561. void SetUp() override {
  12562. svr_.Get("/hello", [](const Request &, Response &res) {
  12563. res.set_content("Hello World!", "text/plain");
  12564. });
  12565. svr_.Get("/large", [](const Request &, Response &res) {
  12566. res.set_content(std::string(10000, 'X'), "text/plain");
  12567. });
  12568. svr_.Get("/chunked", [](const Request &, Response &res) {
  12569. res.set_chunked_content_provider("text/plain",
  12570. [](size_t offset, DataSink &sink) {
  12571. if (offset < 15) {
  12572. sink.write("chunk", 5);
  12573. return true;
  12574. }
  12575. sink.done();
  12576. return true;
  12577. });
  12578. });
  12579. svr_.Get("/compressible", [](const Request &, Response &res) {
  12580. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12581. DataSink &sink) {
  12582. if (offset < 100 * 1024) {
  12583. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12584. sink.write(chunk.data(), chunk.size());
  12585. return true;
  12586. }
  12587. sink.done();
  12588. return true;
  12589. });
  12590. });
  12591. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12592. [](const Request & /*req*/, Response &res) {
  12593. auto i = new int(0);
  12594. res.set_header("Trailer", "Content-Length, X-Allowed");
  12595. res.set_chunked_content_provider(
  12596. "text/plain",
  12597. [i](size_t /*offset*/, DataSink &sink) {
  12598. switch (*i) {
  12599. case 0: sink.os << "123"; break;
  12600. case 1: sink.os << "456"; break;
  12601. case 2: sink.os << "789"; break;
  12602. case 3: {
  12603. sink.done_with_trailer(
  12604. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12605. } break;
  12606. }
  12607. (*i)++;
  12608. return true;
  12609. },
  12610. [i](bool success) {
  12611. EXPECT_TRUE(success);
  12612. delete i;
  12613. });
  12614. });
  12615. // Echo headers endpoint for header-related tests
  12616. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12617. std::string body;
  12618. for (const auto &h : req.headers) {
  12619. body.append(h.first);
  12620. body.push_back(':');
  12621. body.append(h.second);
  12622. body.push_back('\n');
  12623. }
  12624. res.set_content(body, "text/plain");
  12625. });
  12626. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12627. std::string body;
  12628. for (const auto &h : req.headers) {
  12629. body.append(h.first);
  12630. body.push_back(':');
  12631. body.append(h.second);
  12632. body.push_back('\n');
  12633. }
  12634. res.set_content(body, "text/plain");
  12635. });
  12636. port_ = svr_.bind_to_any_port("127.0.0.1");
  12637. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12638. svr_.wait_until_ready();
  12639. }
  12640. void TearDown() override {
  12641. svr_.stop();
  12642. if (thread_.joinable()) thread_.join();
  12643. }
  12644. Server svr_;
  12645. std::thread thread_;
  12646. int port_ = 0;
  12647. };
  12648. TEST_F(OpenStreamTest, Basic) {
  12649. Client cli("127.0.0.1", port_);
  12650. auto handle = cli.open_stream("GET", "/hello");
  12651. EXPECT_TRUE(handle.is_valid());
  12652. EXPECT_EQ("Hello World!", read_all(handle));
  12653. }
  12654. TEST_F(OpenStreamTest, SmallBuffer) {
  12655. Client cli("127.0.0.1", port_);
  12656. auto handle = cli.open_stream("GET", "/hello");
  12657. std::string result;
  12658. char buf[4];
  12659. ssize_t n;
  12660. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12661. result.append(buf, static_cast<size_t>(n));
  12662. EXPECT_EQ("Hello World!", result);
  12663. }
  12664. TEST_F(OpenStreamTest, DefaultHeaders) {
  12665. Client cli("127.0.0.1", port_);
  12666. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12667. {
  12668. auto handle = cli.open_stream("GET", "/echo-headers");
  12669. ASSERT_TRUE(handle.is_valid());
  12670. auto body = read_all(handle);
  12671. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12672. std::string::npos);
  12673. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12674. std::string::npos);
  12675. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12676. }
  12677. // open_stream POST with body and no explicit content_type should NOT add
  12678. // text/plain Content-Type (behavior differs from non-streaming path), but
  12679. // should include Content-Length
  12680. {
  12681. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12682. ASSERT_TRUE(handle.is_valid());
  12683. auto body = read_all(handle);
  12684. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12685. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12686. }
  12687. // open_stream POST with explicit Content-Type should preserve it
  12688. {
  12689. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12690. {{"Content-Type", "application/custom"}},
  12691. "{}", "application/custom");
  12692. ASSERT_TRUE(handle.is_valid());
  12693. auto body = read_all(handle);
  12694. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12695. }
  12696. // User-specified User-Agent must not be overwritten for stream API
  12697. {
  12698. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12699. {{"User-Agent", "MyAgent/1.2"}});
  12700. ASSERT_TRUE(handle.is_valid());
  12701. auto body = read_all(handle);
  12702. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12703. }
  12704. }
  12705. TEST_F(OpenStreamTest, Large) {
  12706. Client cli("127.0.0.1", port_);
  12707. auto handle = cli.open_stream("GET", "/large");
  12708. EXPECT_EQ(10000u, read_all(handle).size());
  12709. }
  12710. TEST_F(OpenStreamTest, ConnectionError) {
  12711. Client cli("127.0.0.1", 9999);
  12712. auto handle = cli.open_stream("GET", "/hello");
  12713. EXPECT_FALSE(handle.is_valid());
  12714. }
  12715. TEST_F(OpenStreamTest, Chunked) {
  12716. Client cli("127.0.0.1", port_);
  12717. auto handle = cli.open_stream("GET", "/chunked");
  12718. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12719. "Transfer-Encoding") == "chunked");
  12720. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12721. }
  12722. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12723. Client cli("127.0.0.1", port_);
  12724. auto handle =
  12725. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12726. ASSERT_TRUE(handle.is_valid());
  12727. // Consume body to allow trailers to be received/parsed
  12728. auto body = read_all(handle);
  12729. // Explicitly parse trailers (ensure trailers are available for assertion)
  12730. handle.parse_trailers_if_needed();
  12731. EXPECT_EQ(std::string("123456789"), body);
  12732. // The response should include a Trailer header declaring both names
  12733. ASSERT_TRUE(handle.response);
  12734. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12735. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12736. handle.response->get_header_value("Trailer"));
  12737. // Prohibited trailer must not be present
  12738. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12739. // Allowed trailer should be present
  12740. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12741. EXPECT_EQ(std::string("yes"),
  12742. handle.response->get_trailer_value("X-Allowed"));
  12743. // Verify trailers are NOT present as regular headers
  12744. EXPECT_EQ(std::string(""),
  12745. handle.response->get_header_value("Content-Length"));
  12746. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12747. }
  12748. static std::thread serve_single_response(std::promise<int> &port_promise,
  12749. const std::string &response) {
  12750. return std::thread([&port_promise, response] {
  12751. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12752. default_socket_options(srv);
  12753. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12754. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12755. sockaddr_in addr{};
  12756. addr.sin_family = AF_INET;
  12757. addr.sin_port = htons(0); // Let OS assign a free port
  12758. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12759. int opt = 1;
  12760. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12761. #ifdef _WIN32
  12762. reinterpret_cast<const char *>(&opt),
  12763. #else
  12764. &opt,
  12765. #endif
  12766. sizeof(opt));
  12767. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12768. ::listen(srv, 1) != 0) {
  12769. port_promise.set_value(-1);
  12770. detail::close_socket(srv);
  12771. return;
  12772. }
  12773. socklen_t addr_len = sizeof(addr);
  12774. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12775. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12776. sockaddr_in cli_addr{};
  12777. socklen_t cli_len = sizeof(cli_addr);
  12778. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12779. if (cli != INVALID_SOCKET) {
  12780. // Read the complete HTTP request (until the blank line that terminates
  12781. // headers) before sending the response. If the server closes the socket
  12782. // while the client's request data is still unread in the kernel receive
  12783. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12784. // connection on both sides: it discards the client's receive buffer
  12785. // (which already holds our response) and causes any in-progress write on
  12786. // the client to fail with ECONNRESET. Reading all request data first
  12787. // ensures close() emits a graceful FIN.
  12788. {
  12789. char rbuf[256];
  12790. std::string req;
  12791. while (req.find("\r\n\r\n") == std::string::npos) {
  12792. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12793. if (n <= 0) { break; }
  12794. req.append(rbuf, static_cast<size_t>(n));
  12795. }
  12796. }
  12797. ::send(cli,
  12798. #ifdef _WIN32
  12799. static_cast<const char *>(response.c_str()),
  12800. static_cast<int>(response.size()),
  12801. #else
  12802. response.c_str(), response.size(),
  12803. #endif
  12804. 0);
  12805. detail::close_socket(cli);
  12806. }
  12807. detail::close_socket(srv);
  12808. });
  12809. }
  12810. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12811. #ifndef _WIN32
  12812. signal(SIGPIPE, SIG_IGN);
  12813. #endif
  12814. std::promise<int> port_promise;
  12815. auto port_future = port_promise.get_future();
  12816. auto server_thread =
  12817. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12818. "Content-Type: text/plain\r\n"
  12819. "Content-Length: not-a-number\r\n"
  12820. "Connection: close\r\n"
  12821. "\r\n"
  12822. "hello");
  12823. auto port = port_future.get();
  12824. ASSERT_GT(port, 0);
  12825. Client cli("127.0.0.1", port);
  12826. auto handle = cli.open_stream("GET", "/");
  12827. EXPECT_FALSE(handle.is_valid());
  12828. server_thread.join();
  12829. }
  12830. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12831. #ifndef _WIN32
  12832. signal(SIGPIPE, SIG_IGN);
  12833. #endif
  12834. std::promise<int> port_promise;
  12835. auto port_future = port_promise.get_future();
  12836. auto server_thread = serve_single_response(
  12837. port_promise, "HTTP/1.1 200 OK\r\n"
  12838. "Content-Type: text/plain\r\n"
  12839. "Content-Length: 99999999999999999999999999\r\n"
  12840. "Connection: close\r\n"
  12841. "\r\n"
  12842. "hello");
  12843. auto port = port_future.get();
  12844. ASSERT_GT(port, 0);
  12845. // Before the fix, std::stoull would throw std::out_of_range here and
  12846. // crash the process. After the fix, strtoull silently clamps to
  12847. // ULLONG_MAX so the stream opens without crashing. The important thing
  12848. // is that the process does NOT terminate.
  12849. Client cli("127.0.0.1", port);
  12850. auto handle = cli.open_stream("GET", "/");
  12851. EXPECT_TRUE(handle.is_valid());
  12852. server_thread.join();
  12853. }
  12854. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12855. TEST_F(OpenStreamTest, Gzip) {
  12856. Client cli("127.0.0.1", port_);
  12857. auto handle = cli.open_stream("GET", "/compressible", {},
  12858. {{"Accept-Encoding", "gzip"}});
  12859. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12860. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12861. }
  12862. #endif
  12863. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12864. TEST_F(OpenStreamTest, Brotli) {
  12865. Client cli("127.0.0.1", port_);
  12866. auto handle =
  12867. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12868. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12869. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12870. }
  12871. #endif
  12872. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12873. TEST_F(OpenStreamTest, Zstd) {
  12874. Client cli("127.0.0.1", port_);
  12875. auto handle = cli.open_stream("GET", "/compressible", {},
  12876. {{"Accept-Encoding", "zstd"}});
  12877. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12878. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12879. }
  12880. #endif
  12881. #ifdef CPPHTTPLIB_SSL_ENABLED
  12882. class SSLOpenStreamTest : public ::testing::Test {
  12883. protected:
  12884. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12885. void SetUp() override {
  12886. svr_.Get("/hello", [](const Request &, Response &res) {
  12887. res.set_content("Hello SSL World!", "text/plain");
  12888. });
  12889. svr_.Get("/chunked", [](const Request &, Response &res) {
  12890. res.set_chunked_content_provider("text/plain",
  12891. [](size_t offset, DataSink &sink) {
  12892. if (offset < 15) {
  12893. sink.write("chunk", 5);
  12894. return true;
  12895. }
  12896. sink.done();
  12897. return true;
  12898. });
  12899. });
  12900. svr_.Post("/echo", [](const Request &req, Response &res) {
  12901. res.set_content(req.body, req.get_header_value("Content-Type"));
  12902. });
  12903. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12904. std::string body = req.body;
  12905. res.set_chunked_content_provider(
  12906. "text/plain", [body](size_t offset, DataSink &sink) {
  12907. if (offset < body.size()) {
  12908. sink.write(body.data() + offset, body.size() - offset);
  12909. }
  12910. sink.done();
  12911. return true;
  12912. });
  12913. });
  12914. port_ = svr_.bind_to_any_port("127.0.0.1");
  12915. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12916. svr_.wait_until_ready();
  12917. }
  12918. void TearDown() override {
  12919. svr_.stop();
  12920. if (thread_.joinable()) thread_.join();
  12921. }
  12922. SSLServer svr_;
  12923. std::thread thread_;
  12924. int port_ = 0;
  12925. };
  12926. TEST_F(SSLOpenStreamTest, Basic) {
  12927. SSLClient cli("127.0.0.1", port_);
  12928. cli.enable_server_certificate_verification(false);
  12929. auto handle = cli.open_stream("GET", "/hello");
  12930. ASSERT_TRUE(handle.is_valid());
  12931. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12932. }
  12933. TEST_F(SSLOpenStreamTest, Chunked) {
  12934. SSLClient cli("127.0.0.1", port_);
  12935. cli.enable_server_certificate_verification(false);
  12936. auto handle = cli.open_stream("GET", "/chunked");
  12937. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12938. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12939. "Transfer-Encoding") == "chunked");
  12940. auto body = read_all(handle);
  12941. EXPECT_EQ("chunkchunkchunk", body);
  12942. }
  12943. TEST_F(SSLOpenStreamTest, Post) {
  12944. SSLClient cli("127.0.0.1", port_);
  12945. cli.enable_server_certificate_verification(false);
  12946. auto handle =
  12947. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12948. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12949. EXPECT_EQ(200, handle.response->status);
  12950. auto body = read_all(handle);
  12951. EXPECT_EQ("Hello SSL POST", body);
  12952. }
  12953. TEST_F(SSLOpenStreamTest, PostChunked) {
  12954. SSLClient cli("127.0.0.1", port_);
  12955. cli.enable_server_certificate_verification(false);
  12956. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12957. "Chunked SSL Data", "text/plain");
  12958. ASSERT_TRUE(handle.is_valid());
  12959. EXPECT_EQ(200, handle.response->status);
  12960. auto body = read_all(handle);
  12961. EXPECT_EQ("Chunked SSL Data", body);
  12962. }
  12963. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12964. // Content-Length is terminated by the server closing the connection. When the
  12965. // SSL peer sends a close_notify after the body, the client must treat it as a
  12966. // clean EOF and return a successful response rather than an error.
  12967. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12969. ASSERT_TRUE(svr.is_valid());
  12970. svr.set_keep_alive_max_count(1);
  12971. const std::string expected_body = "Hello from connection-close response!";
  12972. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12973. res.set_content_provider("text/plain",
  12974. [&](size_t offset, DataSink &sink) -> bool {
  12975. if (offset < expected_body.size()) {
  12976. sink.write(expected_body.data() + offset,
  12977. expected_body.size() - offset);
  12978. }
  12979. sink.done();
  12980. return true;
  12981. });
  12982. });
  12983. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12984. auto se = detail::scope_exit([&] {
  12985. svr.stop();
  12986. listen_thread.join();
  12987. ASSERT_FALSE(svr.is_running());
  12988. });
  12989. svr.wait_until_ready();
  12990. SSLClient cli(HOST, PORT);
  12991. cli.enable_server_certificate_verification(false);
  12992. auto res = cli.Get("/no-content-length");
  12993. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12994. EXPECT_EQ(StatusCode::OK_200, res->status);
  12995. EXPECT_EQ(expected_body, res->body);
  12996. }
  12997. #endif // CPPHTTPLIB_SSL_ENABLED
  12998. //==============================================================================
  12999. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13000. // results for various scenarios.
  13001. //==============================================================================
  13002. TEST(ParityTest, GetVsOpenStream) {
  13003. Server svr;
  13004. const std::string path = "/parity";
  13005. const std::string content = "Parity test content: hello world";
  13006. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13007. res.set_content(content, "text/plain");
  13008. });
  13009. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13010. auto se = detail::scope_exit([&] {
  13011. svr.stop();
  13012. t.join();
  13013. ASSERT_FALSE(svr.is_running());
  13014. });
  13015. svr.wait_until_ready();
  13016. Client cli(HOST, PORT);
  13017. // Non-stream path
  13018. auto r1 = cli.Get(path);
  13019. ASSERT_TRUE(r1);
  13020. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13021. // Stream path
  13022. auto h = cli.open_stream("GET", path);
  13023. ASSERT_TRUE(h.is_valid());
  13024. EXPECT_EQ(r1->body, read_all(h));
  13025. }
  13026. // Helper to compress data with provided compressor type T
  13027. template <typename Compressor>
  13028. static std::string compress_payload_for_parity(const std::string &in) {
  13029. std::string out;
  13030. Compressor compressor;
  13031. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13032. [&](const char *data, size_t n) {
  13033. out.append(data, n);
  13034. return true;
  13035. });
  13036. EXPECT_TRUE(ok);
  13037. return out;
  13038. }
  13039. // Helper function for compression parity tests
  13040. template <typename Compressor>
  13041. static void test_compression_parity(const std::string &original,
  13042. const std::string &path,
  13043. const std::string &encoding) {
  13044. const std::string compressed =
  13045. compress_payload_for_parity<Compressor>(original);
  13046. Server svr;
  13047. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13048. res.set_content(compressed, "application/octet-stream");
  13049. res.set_header("Content-Encoding", encoding);
  13050. });
  13051. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. ASSERT_FALSE(svr.is_running());
  13056. });
  13057. svr.wait_until_ready();
  13058. Client cli(HOST, PORT);
  13059. // Non-streaming
  13060. {
  13061. auto res = cli.Get(path);
  13062. ASSERT_TRUE(res);
  13063. EXPECT_EQ(StatusCode::OK_200, res->status);
  13064. EXPECT_EQ(original, res->body);
  13065. }
  13066. // Streaming
  13067. {
  13068. auto h = cli.open_stream("GET", path);
  13069. ASSERT_TRUE(h.is_valid());
  13070. EXPECT_EQ(original, read_all(h));
  13071. }
  13072. }
  13073. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13074. TEST(ParityTest, Gzip) {
  13075. test_compression_parity<detail::gzip_compressor>(
  13076. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13077. }
  13078. #endif
  13079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13080. TEST(ParityTest, Brotli) {
  13081. test_compression_parity<detail::brotli_compressor>(
  13082. "Hello, brotli parity test payload", "/parity-br", "br");
  13083. }
  13084. #endif
  13085. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13086. TEST(ParityTest, Zstd) {
  13087. test_compression_parity<detail::zstd_compressor>(
  13088. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13089. }
  13090. #endif
  13091. //==============================================================================
  13092. // New Stream API Tests
  13093. //==============================================================================
  13094. inline std::string read_body(httplib::stream::Result &result) {
  13095. std::string body;
  13096. while (result.next()) {
  13097. body.append(result.data(), result.size());
  13098. }
  13099. return body;
  13100. }
  13101. TEST(ClientConnectionTest, Basic) {
  13102. httplib::ClientConnection conn;
  13103. EXPECT_FALSE(conn.is_open());
  13104. conn.sock = 1;
  13105. EXPECT_TRUE(conn.is_open());
  13106. httplib::ClientConnection conn2(std::move(conn));
  13107. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13108. conn2.sock = INVALID_SOCKET;
  13109. }
  13110. // Unified test server for all stream::* tests
  13111. class StreamApiTest : public ::testing::Test {
  13112. protected:
  13113. void SetUp() override {
  13114. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13115. res.set_content("Hello World!", "text/plain");
  13116. });
  13117. svr_.Get("/echo-params",
  13118. [](const httplib::Request &req, httplib::Response &res) {
  13119. std::string r;
  13120. for (const auto &p : req.params) {
  13121. if (!r.empty()) r += "&";
  13122. r += p.first + "=" + p.second;
  13123. }
  13124. res.set_content(r, "text/plain");
  13125. });
  13126. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13127. res.set_content(req.body, req.get_header_value("Content-Type"));
  13128. });
  13129. svr_.Post("/echo-headers",
  13130. [](const httplib::Request &req, httplib::Response &res) {
  13131. std::string r;
  13132. for (const auto &h : req.headers)
  13133. r += h.first + ": " + h.second + "\n";
  13134. res.set_content(r, "text/plain");
  13135. });
  13136. svr_.Post("/echo-params",
  13137. [](const httplib::Request &req, httplib::Response &res) {
  13138. std::string r = "params:";
  13139. for (const auto &p : req.params)
  13140. r += p.first + "=" + p.second + ";";
  13141. res.set_content(r + " body:" + req.body, "text/plain");
  13142. });
  13143. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13144. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13145. });
  13146. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13147. res.set_content("PUT:" + req.body, "text/plain");
  13148. });
  13149. svr_.Patch("/echo",
  13150. [](const httplib::Request &req, httplib::Response &res) {
  13151. res.set_content("PATCH:" + req.body, "text/plain");
  13152. });
  13153. svr_.Delete(
  13154. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13155. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13156. "text/plain");
  13157. });
  13158. svr_.Get("/head-test",
  13159. [](const httplib::Request &, httplib::Response &res) {
  13160. res.set_content("body for HEAD", "text/plain");
  13161. });
  13162. svr_.Options("/options",
  13163. [](const httplib::Request &, httplib::Response &res) {
  13164. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13165. });
  13166. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13167. svr_.wait_until_ready();
  13168. }
  13169. void TearDown() override {
  13170. svr_.stop();
  13171. if (thread_.joinable()) thread_.join();
  13172. }
  13173. httplib::Server svr_;
  13174. std::thread thread_;
  13175. };
  13176. // stream::Get tests
  13177. TEST_F(StreamApiTest, GetBasic) {
  13178. httplib::Client cli(HOST, PORT);
  13179. auto result = httplib::stream::Get(cli, "/hello");
  13180. ASSERT_TRUE(result.is_valid());
  13181. EXPECT_EQ(200, result.status());
  13182. EXPECT_EQ("Hello World!", read_body(result));
  13183. }
  13184. TEST_F(StreamApiTest, GetWithParams) {
  13185. httplib::Client cli(HOST, PORT);
  13186. httplib::Params params{{"foo", "bar"}};
  13187. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13188. ASSERT_TRUE(result.is_valid());
  13189. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13190. }
  13191. TEST_F(StreamApiTest, GetConnectionError) {
  13192. httplib::Client cli(HOST, 9999);
  13193. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13194. }
  13195. TEST_F(StreamApiTest, Get404) {
  13196. httplib::Client cli(HOST, PORT);
  13197. auto result = httplib::stream::Get(cli, "/nonexistent");
  13198. EXPECT_TRUE(result.is_valid());
  13199. EXPECT_EQ(404, result.status());
  13200. }
  13201. // stream::Post tests
  13202. TEST_F(StreamApiTest, PostBasic) {
  13203. httplib::Client cli(HOST, PORT);
  13204. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13205. "application/json");
  13206. ASSERT_TRUE(result.is_valid());
  13207. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13208. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13209. }
  13210. TEST_F(StreamApiTest, PostWithHeaders) {
  13211. httplib::Client cli(HOST, PORT);
  13212. httplib::Headers headers{{"X-Custom", "value"}};
  13213. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13214. "text/plain");
  13215. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13216. }
  13217. TEST_F(StreamApiTest, PostWithParams) {
  13218. httplib::Client cli(HOST, PORT);
  13219. httplib::Params params{{"k", "v"}};
  13220. auto result =
  13221. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13222. auto body = read_body(result);
  13223. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13224. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13225. }
  13226. TEST_F(StreamApiTest, PostLarge) {
  13227. httplib::Client cli(HOST, PORT);
  13228. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13229. size_t total = 0;
  13230. while (result.next()) {
  13231. total += result.size();
  13232. }
  13233. EXPECT_EQ(100u * 1024u, total);
  13234. }
  13235. // stream::Put/Patch tests
  13236. TEST_F(StreamApiTest, PutAndPatch) {
  13237. httplib::Client cli(HOST, PORT);
  13238. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13239. EXPECT_EQ("PUT:test", read_body(put));
  13240. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13241. EXPECT_EQ("PATCH:test", read_body(patch));
  13242. }
  13243. // stream::Delete tests
  13244. TEST_F(StreamApiTest, Delete) {
  13245. httplib::Client cli(HOST, PORT);
  13246. auto del1 = httplib::stream::Delete(cli, "/resource");
  13247. EXPECT_EQ("Deleted", read_body(del1));
  13248. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13249. EXPECT_EQ("Deleted:data", read_body(del2));
  13250. }
  13251. // stream::Head/Options tests
  13252. TEST_F(StreamApiTest, HeadAndOptions) {
  13253. httplib::Client cli(HOST, PORT);
  13254. auto head = httplib::stream::Head(cli, "/head-test");
  13255. EXPECT_TRUE(head.is_valid());
  13256. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13257. auto opts = httplib::stream::Options(cli, "/options");
  13258. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13259. }
  13260. // SSL stream::* tests
  13261. #ifdef CPPHTTPLIB_SSL_ENABLED
  13262. class SSLStreamApiTest : public ::testing::Test {
  13263. protected:
  13264. void SetUp() override {
  13265. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13266. res.set_content("Hello SSL!", "text/plain");
  13267. });
  13268. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13269. res.set_content(req.body, "text/plain");
  13270. });
  13271. port_ = svr_.bind_to_any_port("127.0.0.1");
  13272. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13273. svr_.wait_until_ready();
  13274. }
  13275. void TearDown() override {
  13276. svr_.stop();
  13277. if (thread_.joinable()) thread_.join();
  13278. }
  13279. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13280. std::thread thread_;
  13281. int port_ = 0;
  13282. };
  13283. TEST_F(SSLStreamApiTest, GetAndPost) {
  13284. httplib::SSLClient cli("127.0.0.1", port_);
  13285. cli.enable_server_certificate_verification(false);
  13286. auto get = httplib::stream::Get(cli, "/hello");
  13287. EXPECT_EQ("Hello SSL!", read_body(get));
  13288. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13289. EXPECT_EQ("test", read_body(post));
  13290. }
  13291. #endif
  13292. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13293. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13294. // BodyReader
  13295. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13296. // Test that read timeout during streaming is detected
  13297. // Use a large content-length response where server delays mid-stream
  13298. Server svr;
  13299. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13300. // Send a large response with delay in the middle
  13301. res.set_content_provider(
  13302. 1000, // content_length
  13303. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13304. if (offset < 100) {
  13305. // Send first 100 bytes immediately
  13306. std::string data(100, 'A');
  13307. sink.write(data.c_str(), data.size());
  13308. return true;
  13309. }
  13310. // Then delay longer than client timeout
  13311. std::this_thread::sleep_for(std::chrono::seconds(3));
  13312. std::string data(900, 'B');
  13313. sink.write(data.c_str(), data.size());
  13314. return true;
  13315. });
  13316. });
  13317. auto port = 8091;
  13318. std::thread t([&]() { svr.listen("localhost", port); });
  13319. svr.wait_until_ready();
  13320. Client cli("localhost", port);
  13321. cli.set_read_timeout(1, 0); // 1 second timeout
  13322. auto handle = cli.open_stream("GET", "/slow-stream");
  13323. ASSERT_TRUE(handle.is_valid());
  13324. char buf[256];
  13325. ssize_t total = 0;
  13326. ssize_t n;
  13327. bool got_error = false;
  13328. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13329. total += n;
  13330. }
  13331. if (n < 0) {
  13332. got_error = true;
  13333. // Should be timeout or read error
  13334. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13335. handle.get_read_error() == Error::Read)
  13336. << "Actual error: " << to_string(handle.get_read_error());
  13337. }
  13338. // Either we got an error, or we got less data than expected
  13339. EXPECT_TRUE(got_error || total < 1000)
  13340. << "Expected timeout but got all " << total << " bytes";
  13341. svr.stop();
  13342. t.join();
  13343. }
  13344. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13345. // Test connection closed detection via BodyReader
  13346. Server svr;
  13347. std::atomic<bool> close_now{false};
  13348. svr.Get("/will-close", [&](const Request &, Response &res) {
  13349. res.set_content_provider(
  13350. 10000, // Large content_length that we won't fully send
  13351. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13352. if (offset < 100) {
  13353. std::string data(100, 'X');
  13354. sink.write(data.c_str(), data.size());
  13355. return true;
  13356. }
  13357. // Wait for signal then abort
  13358. while (!close_now) {
  13359. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13360. }
  13361. return false; // Abort - server will close connection
  13362. });
  13363. });
  13364. auto port = 8092;
  13365. std::thread t([&]() { svr.listen("localhost", port); });
  13366. svr.wait_until_ready();
  13367. Client cli("localhost", port);
  13368. auto handle = cli.open_stream("GET", "/will-close");
  13369. ASSERT_TRUE(handle.is_valid());
  13370. char buf[256];
  13371. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13372. EXPECT_GT(n, 0) << "First read should succeed";
  13373. // Signal server to close
  13374. close_now = true;
  13375. // Keep reading until error or EOF
  13376. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13377. // Keep reading
  13378. }
  13379. // Should get an error since content_length wasn't satisfied
  13380. if (n < 0) {
  13381. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13382. handle.get_read_error() == Error::Read)
  13383. << "Actual error: " << to_string(handle.get_read_error());
  13384. }
  13385. svr.stop();
  13386. t.join();
  13387. }
  13388. #ifdef CPPHTTPLIB_SSL_ENABLED
  13389. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13390. // Test that read timeout during SSL streaming is detected
  13391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13392. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13393. res.set_content_provider(
  13394. 1000, "text/plain",
  13395. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13396. if (offset < 100) {
  13397. std::string data(100, 'A');
  13398. sink.write(data.c_str(), data.size());
  13399. return true;
  13400. }
  13401. std::this_thread::sleep_for(std::chrono::seconds(3));
  13402. std::string data(900, 'B');
  13403. sink.write(data.c_str(), data.size());
  13404. return true;
  13405. });
  13406. });
  13407. auto port = 8093;
  13408. std::thread t([&]() { svr.listen("localhost", port); });
  13409. svr.wait_until_ready();
  13410. SSLClient cli("localhost", port);
  13411. cli.enable_server_certificate_verification(false);
  13412. cli.set_read_timeout(1, 0); // 1 second timeout
  13413. auto handle = cli.open_stream("GET", "/slow-stream");
  13414. ASSERT_TRUE(handle.is_valid());
  13415. char buf[256];
  13416. ssize_t total = 0;
  13417. ssize_t n;
  13418. bool got_error = false;
  13419. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13420. total += n;
  13421. }
  13422. if (n < 0) {
  13423. got_error = true;
  13424. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13425. handle.get_read_error() == Error::Read)
  13426. << "Actual error: " << to_string(handle.get_read_error());
  13427. }
  13428. EXPECT_TRUE(got_error || total < 1000)
  13429. << "Expected timeout but got all " << total << " bytes";
  13430. svr.stop();
  13431. t.join();
  13432. }
  13433. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13434. // Test SSL connection closed detection
  13435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13436. std::atomic<bool> close_now{false};
  13437. svr.Get("/will-close", [&](const Request &, Response &res) {
  13438. res.set_content_provider(
  13439. 10000, "text/plain",
  13440. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13441. if (offset < 100) {
  13442. std::string data(100, 'X');
  13443. sink.write(data.c_str(), data.size());
  13444. return true;
  13445. }
  13446. while (!close_now) {
  13447. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13448. }
  13449. return false;
  13450. });
  13451. });
  13452. auto port = 8094;
  13453. std::thread t([&]() { svr.listen("localhost", port); });
  13454. svr.wait_until_ready();
  13455. SSLClient cli("localhost", port);
  13456. cli.enable_server_certificate_verification(false);
  13457. auto handle = cli.open_stream("GET", "/will-close");
  13458. ASSERT_TRUE(handle.is_valid());
  13459. char buf[256];
  13460. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13461. EXPECT_GT(n, 0);
  13462. // Signal server to close
  13463. close_now = true;
  13464. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13465. // Keep reading
  13466. }
  13467. if (n < 0) {
  13468. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13469. handle.get_read_error() == Error::Read)
  13470. << "Actual error: " << to_string(handle.get_read_error());
  13471. }
  13472. svr.stop();
  13473. t.join();
  13474. }
  13475. #endif
  13476. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13477. using namespace httplib;
  13478. // Create a test file
  13479. const char *fname = "etag_testfile.txt";
  13480. const char *content = "etag-content";
  13481. {
  13482. std::ofstream ofs(fname);
  13483. ofs << content;
  13484. ASSERT_TRUE(ofs.good());
  13485. }
  13486. Server svr;
  13487. svr.set_mount_point("/static", ".");
  13488. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13489. svr.wait_until_ready();
  13490. Client cli(HOST, PORT);
  13491. // First request: should get 200 with ETag header
  13492. auto res1 = cli.Get("/static/etag_testfile.txt");
  13493. ASSERT_TRUE(res1);
  13494. ASSERT_EQ(200, res1->status);
  13495. ASSERT_TRUE(res1->has_header("ETag"));
  13496. std::string etag = res1->get_header_value("ETag");
  13497. EXPECT_FALSE(etag.empty());
  13498. // Verify ETag format: W/"hex-hex"
  13499. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13500. EXPECT_EQ('W', etag[0]);
  13501. EXPECT_EQ('/', etag[1]);
  13502. EXPECT_EQ('"', etag[2]);
  13503. EXPECT_EQ('"', etag.back());
  13504. // Exact match: expect 304 Not Modified
  13505. Headers h2 = {{"If-None-Match", etag}};
  13506. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13507. ASSERT_TRUE(res2);
  13508. EXPECT_EQ(304, res2->status);
  13509. // Wildcard match: expect 304 Not Modified
  13510. Headers h3 = {{"If-None-Match", "*"}};
  13511. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13512. ASSERT_TRUE(res3);
  13513. EXPECT_EQ(304, res3->status);
  13514. // Non-matching ETag: expect 200
  13515. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13516. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13517. ASSERT_TRUE(res4);
  13518. EXPECT_EQ(200, res4->status);
  13519. // Multiple ETags with one matching: expect 304
  13520. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13521. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13522. ASSERT_TRUE(res5);
  13523. EXPECT_EQ(304, res5->status);
  13524. svr.stop();
  13525. t.join();
  13526. std::remove(fname);
  13527. }
  13528. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13529. using namespace httplib;
  13530. Server svr;
  13531. svr.set_mount_point("/static", ".");
  13532. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13533. svr.wait_until_ready();
  13534. Client cli(HOST, PORT);
  13535. // Send If-None-Match: * to a non-existent file
  13536. Headers h = {{"If-None-Match", "*"}};
  13537. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13538. ASSERT_TRUE(res);
  13539. EXPECT_EQ(404, res->status);
  13540. svr.stop();
  13541. t.join();
  13542. }
  13543. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13544. using namespace httplib;
  13545. // Create a test file
  13546. const char *fname = "etag_boundary_testfile.txt";
  13547. const char *content = "boundary-test";
  13548. {
  13549. std::ofstream ofs(fname);
  13550. ofs << content;
  13551. ASSERT_TRUE(ofs.good());
  13552. }
  13553. Server svr;
  13554. svr.set_mount_point("/static", ".");
  13555. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13556. svr.wait_until_ready();
  13557. Client cli(HOST, PORT);
  13558. // Get the actual ETag
  13559. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13560. ASSERT_TRUE(res1);
  13561. ASSERT_EQ(200, res1->status);
  13562. ASSERT_TRUE(res1->has_header("ETag"));
  13563. std::string etag = res1->get_header_value("ETag");
  13564. // Test 1: Very long ETag value (longer than actual ETag)
  13565. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13566. Headers h1 = {{"If-None-Match", "W/"
  13567. "\"very-long-etag-value-that-is-much-longer-"
  13568. "than-the-actual-etag-value\""}};
  13569. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13570. ASSERT_TRUE(res2);
  13571. EXPECT_EQ(200, res2->status); // Should not match
  13572. // Test 2: Long string followed by wildcard
  13573. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13574. // string)
  13575. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13576. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13577. ASSERT_TRUE(res3);
  13578. EXPECT_EQ(304, res3->status); // Should match on "*"
  13579. // Test 3: Wildcard followed by long string
  13580. // Should match on "*" immediately and return 304
  13581. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13582. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13583. ASSERT_TRUE(res4);
  13584. EXPECT_EQ(304, res4->status); // Should match on "*"
  13585. // Test 4: Multiple long non-matching values
  13586. // Should NOT match and return 200 (test that all comparisons are safe)
  13587. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13588. "W/\"second-long-non-matching-value\", "
  13589. "W/\"third-long-non-matching-value\""}};
  13590. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13591. ASSERT_TRUE(res5);
  13592. EXPECT_EQ(200, res5->status); // Should not match
  13593. // Test 5: Single character that is not "*" (edge case)
  13594. Headers h5 = {{"If-None-Match", "X"}};
  13595. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13596. ASSERT_TRUE(res6);
  13597. EXPECT_EQ(200, res6->status); // Should not match
  13598. svr.stop();
  13599. t.join();
  13600. std::remove(fname);
  13601. }
  13602. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13603. using namespace httplib;
  13604. // Create a test file
  13605. const char *fname = "ims_testfile.txt";
  13606. const char *content = "if-modified-since-test";
  13607. {
  13608. std::ofstream ofs(fname);
  13609. ofs << content;
  13610. ASSERT_TRUE(ofs.good());
  13611. }
  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. // First request: should get 200 with Last-Modified header
  13618. auto res1 = cli.Get("/static/ims_testfile.txt");
  13619. ASSERT_TRUE(res1);
  13620. ASSERT_EQ(200, res1->status);
  13621. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13622. std::string last_modified = res1->get_header_value("Last-Modified");
  13623. EXPECT_FALSE(last_modified.empty());
  13624. // If-Modified-Since with same time: expect 304
  13625. Headers h2 = {{"If-Modified-Since", last_modified}};
  13626. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13627. ASSERT_TRUE(res2);
  13628. EXPECT_EQ(304, res2->status);
  13629. // If-Modified-Since with future time: expect 304
  13630. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13631. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13632. ASSERT_TRUE(res3);
  13633. EXPECT_EQ(304, res3->status);
  13634. // If-Modified-Since with past time: expect 200
  13635. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13636. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13637. ASSERT_TRUE(res4);
  13638. EXPECT_EQ(200, res4->status);
  13639. // If-None-Match takes precedence over If-Modified-Since
  13640. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13641. ASSERT_TRUE(res1->has_header("ETag"));
  13642. std::string etag = res1->get_header_value("ETag");
  13643. Headers h5 = {{"If-None-Match", etag},
  13644. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13645. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13646. ASSERT_TRUE(res5);
  13647. EXPECT_EQ(304, res5->status);
  13648. svr.stop();
  13649. t.join();
  13650. std::remove(fname);
  13651. }
  13652. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13653. using namespace httplib;
  13654. Server svr;
  13655. // Endpoint that returns compressible content
  13656. svr.Get("/compressible", [](const Request &, Response &res) {
  13657. // Return a large enough body to trigger compression
  13658. std::string body(1000, 'a');
  13659. res.set_content(body, "text/plain");
  13660. });
  13661. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13662. svr.wait_until_ready();
  13663. Client cli(HOST, PORT);
  13664. // Request with gzip support: should get Vary header when compressed
  13665. cli.set_compress(true);
  13666. auto res1 = cli.Get("/compressible");
  13667. ASSERT_TRUE(res1);
  13668. EXPECT_EQ(200, res1->status);
  13669. // If Content-Encoding is set, Vary should also be set
  13670. if (res1->has_header("Content-Encoding")) {
  13671. EXPECT_TRUE(res1->has_header("Vary"));
  13672. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13673. }
  13674. // Request without Accept-Encoding header: should not have compression
  13675. Headers h_no_compress;
  13676. auto res2 = cli.Get("/compressible", h_no_compress);
  13677. ASSERT_TRUE(res2);
  13678. EXPECT_EQ(200, res2->status);
  13679. // Verify Vary header is present when compression is applied
  13680. // (the exact behavior depends on server configuration)
  13681. svr.stop();
  13682. t.join();
  13683. }
  13684. TEST(ETagTest, IfRangeWithETag) {
  13685. using namespace httplib;
  13686. // Create a test file with known content
  13687. const char *fname = "if_range_testfile.txt";
  13688. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  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: get ETag
  13700. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13701. ASSERT_TRUE(res1);
  13702. ASSERT_EQ(200, res1->status);
  13703. ASSERT_TRUE(res1->has_header("ETag"));
  13704. std::string etag = res1->get_header_value("ETag");
  13705. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13706. // Since our server generates weak ETags (W/"..."), If-Range with our
  13707. // ETag should NOT result in partial content - it should return full content.
  13708. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13709. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13710. ASSERT_TRUE(res2);
  13711. // Weak ETag in If-Range -> full content (200), not partial (206)
  13712. EXPECT_EQ(200, res2->status);
  13713. EXPECT_EQ(content, res2->body);
  13714. EXPECT_FALSE(res2->has_header("Content-Range"));
  13715. // Range request with non-matching If-Range (ETag): should get 200 (full
  13716. // content)
  13717. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13718. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13719. ASSERT_TRUE(res3);
  13720. EXPECT_EQ(200, res3->status);
  13721. EXPECT_EQ(content, res3->body);
  13722. EXPECT_FALSE(res3->has_header("Content-Range"));
  13723. // Range request with strong ETag (hypothetical - our server doesn't generate
  13724. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13725. // should return full content)
  13726. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13727. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13728. ASSERT_TRUE(res4);
  13729. EXPECT_EQ(200, res4->status);
  13730. EXPECT_EQ(content, res4->body);
  13731. EXPECT_FALSE(res4->has_header("Content-Range"));
  13732. svr.stop();
  13733. t.join();
  13734. std::remove(fname);
  13735. }
  13736. TEST(ETagTest, IfRangeWithDate) {
  13737. using namespace httplib;
  13738. // Create a test file
  13739. const char *fname = "if_range_date_testfile.txt";
  13740. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13741. {
  13742. std::ofstream ofs(fname);
  13743. ofs << content;
  13744. ASSERT_TRUE(ofs.good());
  13745. }
  13746. Server svr;
  13747. svr.set_mount_point("/static", ".");
  13748. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13749. svr.wait_until_ready();
  13750. Client cli(HOST, PORT);
  13751. // First request: get Last-Modified
  13752. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13753. ASSERT_TRUE(res1);
  13754. ASSERT_EQ(200, res1->status);
  13755. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13756. std::string last_modified = res1->get_header_value("Last-Modified");
  13757. // Range request with matching If-Range (date): should get 206
  13758. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13759. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13760. ASSERT_TRUE(res2);
  13761. EXPECT_EQ(206, res2->status);
  13762. EXPECT_EQ("FGHIJ", res2->body);
  13763. // Range request with old If-Range date: should get 200 (full content)
  13764. Headers h3 = {{"Range", "bytes=5-9"},
  13765. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13766. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13767. ASSERT_TRUE(res3);
  13768. EXPECT_EQ(200, res3->status);
  13769. EXPECT_EQ(content, res3->body);
  13770. // Range request with future If-Range date: should get 206
  13771. Headers h4 = {{"Range", "bytes=0-4"},
  13772. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13773. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13774. ASSERT_TRUE(res4);
  13775. EXPECT_EQ(206, res4->status);
  13776. EXPECT_EQ("ABCDE", res4->body);
  13777. svr.stop();
  13778. t.join();
  13779. std::remove(fname);
  13780. }
  13781. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13782. using namespace httplib;
  13783. const char *fname = "etag_malformed.txt";
  13784. const char *content = "malformed-etag";
  13785. {
  13786. std::ofstream ofs(fname);
  13787. ofs << content;
  13788. ASSERT_TRUE(ofs.good());
  13789. }
  13790. Server svr;
  13791. svr.set_mount_point("/static", ".");
  13792. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13793. svr.wait_until_ready();
  13794. Client cli(HOST, PORT);
  13795. // baseline: should get 200 and an ETag
  13796. auto res1 = cli.Get("/static/etag_malformed.txt");
  13797. ASSERT_TRUE(res1);
  13798. ASSERT_EQ(200, res1->status);
  13799. ASSERT_TRUE(res1->has_header("ETag"));
  13800. // Malformed ETag value (missing quotes) should be treated as non-matching
  13801. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13802. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13803. ASSERT_TRUE(res_bad);
  13804. EXPECT_EQ(200, res_bad->status);
  13805. // Whitespace-only header value should be considered invalid / non-matching
  13806. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13807. "Host: localhost\r\n"
  13808. "If-None-Match: \r\n"
  13809. "Connection: close\r\n"
  13810. "\r\n";
  13811. std::string out;
  13812. ASSERT_TRUE(send_request(5, raw_req, &out));
  13813. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13814. svr.stop();
  13815. t.join();
  13816. std::remove(fname);
  13817. }
  13818. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13819. using namespace httplib;
  13820. const char *fname = "ims_invalid_format.txt";
  13821. const char *content = "ims-bad-format";
  13822. {
  13823. std::ofstream ofs(fname);
  13824. ofs << content;
  13825. ASSERT_TRUE(ofs.good());
  13826. }
  13827. Server svr;
  13828. svr.set_mount_point("/static", ".");
  13829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13830. svr.wait_until_ready();
  13831. Client cli(HOST, PORT);
  13832. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13833. ASSERT_TRUE(res1);
  13834. ASSERT_EQ(200, res1->status);
  13835. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13836. // If-Modified-Since with invalid format should not result in 304
  13837. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13838. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13839. ASSERT_TRUE(res_bad);
  13840. EXPECT_EQ(200, res_bad->status);
  13841. // If-Range with invalid date format should be treated as mismatch -> full
  13842. // content (200)
  13843. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13844. {"If-Range", "invalid-date"}};
  13845. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13846. ASSERT_TRUE(res_ifrange);
  13847. EXPECT_EQ(200, res_ifrange->status);
  13848. svr.stop();
  13849. t.join();
  13850. std::remove(fname);
  13851. }
  13852. TEST(ETagTest, IfRangeWithMalformedETag) {
  13853. using namespace httplib;
  13854. const char *fname = "ifrange_malformed.txt";
  13855. const std::string content = "0123456789";
  13856. {
  13857. std::ofstream ofs(fname);
  13858. ofs << content;
  13859. ASSERT_TRUE(ofs.good());
  13860. }
  13861. Server svr;
  13862. svr.set_mount_point("/static", ".");
  13863. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13864. svr.wait_until_ready();
  13865. Client cli(HOST, PORT);
  13866. // First request: get ETag
  13867. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13868. ASSERT_TRUE(res1);
  13869. ASSERT_EQ(200, res1->status);
  13870. ASSERT_TRUE(res1->has_header("ETag"));
  13871. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13872. // full content (200)
  13873. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13874. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13875. ASSERT_TRUE(res2);
  13876. EXPECT_EQ(200, res2->status);
  13877. EXPECT_EQ(content, res2->body);
  13878. svr.stop();
  13879. t.join();
  13880. std::remove(fname);
  13881. }
  13882. TEST(ETagTest, ExtremeLargeDateValues) {
  13883. using namespace httplib;
  13884. const char *fname = "ims_extreme_date.txt";
  13885. const char *content = "ims-extreme-date";
  13886. {
  13887. std::ofstream ofs(fname);
  13888. ofs << content;
  13889. ASSERT_TRUE(ofs.good());
  13890. }
  13891. Server svr;
  13892. svr.set_mount_point("/static", ".");
  13893. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13894. svr.wait_until_ready();
  13895. Client cli(HOST, PORT);
  13896. auto res1 = cli.Get(std::string("/static/") + fname);
  13897. ASSERT_TRUE(res1);
  13898. ASSERT_EQ(200, res1->status);
  13899. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13900. // Extremely large year that may overflow date parsing routines.
  13901. Headers h_large_date = {
  13902. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13903. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13904. ASSERT_TRUE(res_bad);
  13905. // Expect server to treat this as invalid/mismatch and return full content
  13906. EXPECT_EQ(200, res_bad->status);
  13907. // If-Range with extremely large date should be treated as mismatch -> full
  13908. // content (200)
  13909. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13910. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13911. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13912. ASSERT_TRUE(res_ifrange);
  13913. EXPECT_EQ(200, res_ifrange->status);
  13914. svr.stop();
  13915. t.join();
  13916. std::remove(fname);
  13917. }
  13918. TEST(ETagTest, NegativeFileModificationTime) {
  13919. using namespace httplib;
  13920. const char *fname = "ims_negative_mtime.txt";
  13921. const std::string content = "negative-mtime";
  13922. {
  13923. std::ofstream ofs(fname);
  13924. ofs << content;
  13925. ASSERT_TRUE(ofs.good());
  13926. }
  13927. // Try to set file mtime to a negative value. This may fail on some
  13928. // platforms/filesystems; if it fails, the test will still verify server
  13929. // behaves safely by performing a regular conditional request.
  13930. #if defined(__APPLE__) || defined(__linux__)
  13931. bool set_negative = false;
  13932. do {
  13933. struct timeval times[2];
  13934. // access time: now
  13935. times[0].tv_sec = time(nullptr);
  13936. times[0].tv_usec = 0;
  13937. // modification time: negative (e.g., -1)
  13938. times[1].tv_sec = -1;
  13939. times[1].tv_usec = 0;
  13940. if (utimes(fname, times) == 0) { set_negative = true; }
  13941. } while (0);
  13942. #else
  13943. bool set_negative = false;
  13944. #endif
  13945. Server svr;
  13946. svr.set_mount_point("/static", ".");
  13947. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13948. svr.wait_until_ready();
  13949. Client cli(HOST, PORT);
  13950. auto res1 = cli.Get(std::string("/static/") + fname);
  13951. ASSERT_TRUE(res1);
  13952. ASSERT_EQ(200, res1->status);
  13953. bool has_last_modified = res1->has_header("Last-Modified");
  13954. std::string last_modified;
  13955. if (has_last_modified) {
  13956. last_modified = res1->get_header_value("Last-Modified");
  13957. }
  13958. if (set_negative) {
  13959. // If we successfully set a negative mtime, ensure server returns a
  13960. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13961. // with an old date and ensure server handles it without crash.
  13962. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13963. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13964. ASSERT_TRUE(res2);
  13965. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13966. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13967. } else {
  13968. // Could not set negative mtime on this platform; fall back to verifying
  13969. // that normal invalid/malformed dates are treated safely (non-304).
  13970. Headers h_bad_date = {
  13971. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13972. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13973. ASSERT_TRUE(res_bad);
  13974. EXPECT_EQ(200, res_bad->status);
  13975. }
  13976. svr.stop();
  13977. t.join();
  13978. std::remove(fname);
  13979. }
  13980. //==============================================================================
  13981. // SSE Parsing Tests
  13982. //==============================================================================
  13983. class SSEParsingTest : public ::testing::Test {
  13984. protected:
  13985. // Test helper that mimics SSE parsing behavior
  13986. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13987. int &retry_ms) {
  13988. // Blank line signals end of event
  13989. if (line.empty() || line == "\r") { return true; }
  13990. // Lines starting with ':' are comments (ignored)
  13991. if (!line.empty() && line[0] == ':') { return false; }
  13992. // Find the colon separator
  13993. auto colon_pos = line.find(':');
  13994. if (colon_pos == std::string::npos) {
  13995. // Line with no colon is treated as field name with empty value
  13996. return false;
  13997. }
  13998. std::string field = line.substr(0, colon_pos);
  13999. std::string value;
  14000. // Value starts after colon, skip optional single space
  14001. if (colon_pos + 1 < line.size()) {
  14002. size_t value_start = colon_pos + 1;
  14003. if (line[value_start] == ' ') { value_start++; }
  14004. value = line.substr(value_start);
  14005. // Remove trailing \r if present
  14006. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14007. }
  14008. // Handle known fields
  14009. if (field == "event") {
  14010. msg.event = value;
  14011. } else if (field == "data") {
  14012. // Multiple data lines are concatenated with newlines
  14013. if (!msg.data.empty()) { msg.data += "\n"; }
  14014. msg.data += value;
  14015. } else if (field == "id") {
  14016. // Empty id is valid (clears the last event ID)
  14017. msg.id = value;
  14018. } else if (field == "retry") {
  14019. // Parse retry interval in milliseconds
  14020. {
  14021. int v = 0;
  14022. auto res =
  14023. detail::from_chars(value.data(), value.data() + value.size(), v);
  14024. if (res.ec == std::errc{}) { retry_ms = v; }
  14025. }
  14026. }
  14027. // Unknown fields are ignored per SSE spec
  14028. return false;
  14029. }
  14030. };
  14031. // Test: Single-line data
  14032. TEST_F(SSEParsingTest, SingleLineData) {
  14033. sse::SSEMessage msg;
  14034. int retry_ms = 3000;
  14035. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14036. EXPECT_EQ(msg.data, "hello");
  14037. EXPECT_EQ(msg.event, "message");
  14038. // Blank line ends event
  14039. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14040. }
  14041. // Test: Multi-line data
  14042. TEST_F(SSEParsingTest, MultiLineData) {
  14043. sse::SSEMessage msg;
  14044. int retry_ms = 3000;
  14045. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14046. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14047. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14048. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14049. }
  14050. // Test: Custom event types
  14051. TEST_F(SSEParsingTest, CustomEventType) {
  14052. sse::SSEMessage msg;
  14053. int retry_ms = 3000;
  14054. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14055. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14056. EXPECT_EQ(msg.event, "update");
  14057. EXPECT_EQ(msg.data, "payload");
  14058. }
  14059. // Test: Event ID handling
  14060. TEST_F(SSEParsingTest, EventIdHandling) {
  14061. sse::SSEMessage msg;
  14062. int retry_ms = 3000;
  14063. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14064. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14065. EXPECT_EQ(msg.id, "12345");
  14066. }
  14067. // Test: Empty event ID (clears last event ID)
  14068. TEST_F(SSEParsingTest, EmptyEventId) {
  14069. sse::SSEMessage msg;
  14070. msg.id = "previous";
  14071. int retry_ms = 3000;
  14072. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14073. EXPECT_EQ(msg.id, "");
  14074. }
  14075. // Test: Retry field parsing
  14076. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14077. sse::SSEMessage msg;
  14078. int retry_ms = 3000;
  14079. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14080. EXPECT_EQ(retry_ms, 5000);
  14081. }
  14082. // Test: Invalid retry value
  14083. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14084. sse::SSEMessage msg;
  14085. int retry_ms = 3000;
  14086. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14087. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14088. }
  14089. // Test: Comments (lines starting with :)
  14090. TEST_F(SSEParsingTest, CommentsIgnored) {
  14091. sse::SSEMessage msg;
  14092. int retry_ms = 3000;
  14093. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14094. EXPECT_EQ(msg.data, "");
  14095. EXPECT_EQ(msg.event, "message");
  14096. }
  14097. // Test: Colon in value
  14098. TEST_F(SSEParsingTest, ColonInValue) {
  14099. sse::SSEMessage msg;
  14100. int retry_ms = 3000;
  14101. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14102. EXPECT_EQ(msg.data, "hello:world:test");
  14103. }
  14104. // Test: Line with no colon (field name only)
  14105. TEST_F(SSEParsingTest, FieldNameOnly) {
  14106. sse::SSEMessage msg;
  14107. int retry_ms = 3000;
  14108. // According to SSE spec, this is treated as field name with empty value
  14109. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14110. // Since we don't recognize "data" without colon, data should be empty
  14111. EXPECT_EQ(msg.data, "");
  14112. }
  14113. // Test: Trailing \r handling
  14114. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14115. sse::SSEMessage msg;
  14116. int retry_ms = 3000;
  14117. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14118. EXPECT_EQ(msg.data, "hello");
  14119. }
  14120. // Test: Unknown fields ignored
  14121. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14122. sse::SSEMessage msg;
  14123. int retry_ms = 3000;
  14124. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14125. EXPECT_EQ(msg.data, "");
  14126. EXPECT_EQ(msg.event, "message");
  14127. }
  14128. // Test: Space after colon is optional
  14129. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14130. sse::SSEMessage msg1, msg2;
  14131. int retry_ms = 3000;
  14132. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14133. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14134. EXPECT_EQ(msg1.data, "hello");
  14135. EXPECT_EQ(msg2.data, "hello");
  14136. }
  14137. // Test: SSEMessage clear
  14138. TEST_F(SSEParsingTest, MessageClear) {
  14139. sse::SSEMessage msg;
  14140. msg.event = "custom";
  14141. msg.data = "some data";
  14142. msg.id = "123";
  14143. msg.clear();
  14144. EXPECT_EQ(msg.event, "message");
  14145. EXPECT_EQ(msg.data, "");
  14146. EXPECT_EQ(msg.id, "");
  14147. }
  14148. // Test: Complete event parsing
  14149. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14150. sse::SSEMessage msg;
  14151. int retry_ms = 3000;
  14152. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14153. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14154. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14155. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14156. // Blank line ends event
  14157. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14158. EXPECT_EQ(msg.event, "notification");
  14159. EXPECT_EQ(msg.id, "evt-42");
  14160. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14161. EXPECT_EQ(retry_ms, 1000);
  14162. }
  14163. //==============================================================================
  14164. // Integration Tests with Server
  14165. //==============================================================================
  14166. class SSEIntegrationTest : public ::testing::Test {
  14167. protected:
  14168. void SetUp() override {
  14169. stop_server_.store(false);
  14170. events_.clear();
  14171. server_ = httplib::detail::make_unique<Server>();
  14172. setup_server();
  14173. start_server();
  14174. }
  14175. void TearDown() override {
  14176. stop_server_.store(true);
  14177. event_cv_.notify_all();
  14178. server_->stop();
  14179. if (server_thread_.joinable()) { server_thread_.join(); }
  14180. }
  14181. void setup_server() {
  14182. // Simple SSE endpoint
  14183. server_->Get("/events", [this](const Request &req, Response &res) {
  14184. auto last_id = req.get_header_value("Last-Event-ID");
  14185. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14186. res.set_chunked_content_provider(
  14187. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14188. std::unique_lock<std::mutex> lock(event_mutex_);
  14189. if (event_cv_.wait_for(
  14190. lock, std::chrono::milliseconds(200), [this] {
  14191. return !events_.empty() || stop_server_.load();
  14192. })) {
  14193. if (stop_server_.load()) { return false; }
  14194. if (!events_.empty()) {
  14195. std::string event = events_.front();
  14196. events_.erase(events_.begin());
  14197. sink.write(event.data(), event.size());
  14198. return true;
  14199. }
  14200. }
  14201. return !stop_server_.load();
  14202. });
  14203. });
  14204. // Endpoint that returns error
  14205. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14206. res.status = 500;
  14207. res.set_content("Internal Server Error", "text/plain");
  14208. });
  14209. // Endpoint for custom event types
  14210. server_->Get("/custom-events", [](const Request &, Response &res) {
  14211. res.set_chunked_content_provider(
  14212. "text/event-stream", [](size_t offset, DataSink &sink) {
  14213. if (offset == 0) {
  14214. std::string event = "event: update\ndata: updated\n\n"
  14215. "event: delete\ndata: deleted\n\n";
  14216. sink.write(event.data(), event.size());
  14217. }
  14218. return false; // End stream after sending
  14219. });
  14220. });
  14221. }
  14222. void start_server() {
  14223. port_ = server_->bind_to_any_port(HOST);
  14224. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14225. // Wait for server to start
  14226. while (!server_->is_running()) {
  14227. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14228. }
  14229. }
  14230. int get_port() const { return port_; }
  14231. void send_event(const std::string &event) {
  14232. std::lock_guard<std::mutex> lock(event_mutex_);
  14233. events_.push_back(event);
  14234. event_cv_.notify_all();
  14235. }
  14236. std::unique_ptr<Server> server_;
  14237. std::thread server_thread_;
  14238. std::mutex event_mutex_;
  14239. std::condition_variable event_cv_;
  14240. std::vector<std::string> events_;
  14241. std::atomic<bool> stop_server_{false};
  14242. std::string last_received_event_id_;
  14243. int port_ = 0;
  14244. };
  14245. // Test: Successful connection and on_open callback
  14246. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14247. // Add a simple endpoint that sends one event and closes
  14248. server_->Get("/simple-event", [](const Request &, Response &res) {
  14249. res.set_chunked_content_provider(
  14250. "text/event-stream", [](size_t offset, DataSink &sink) {
  14251. if (offset == 0) {
  14252. std::string event = "data: hello\n\n";
  14253. sink.write(event.data(), event.size());
  14254. }
  14255. return false; // Close stream after sending
  14256. });
  14257. });
  14258. Client client("localhost", get_port());
  14259. sse::SSEClient sse(client, "/simple-event");
  14260. std::atomic<bool> open_called{false};
  14261. std::atomic<bool> message_received{false};
  14262. sse.on_open([&open_called]() { open_called.store(true); });
  14263. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14264. if (msg.data == "hello") { message_received.store(true); }
  14265. });
  14266. sse.set_reconnect_interval(100);
  14267. sse.set_max_reconnect_attempts(1);
  14268. // Start async
  14269. sse.start_async();
  14270. // Wait for message to be processed
  14271. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14272. sse.stop();
  14273. EXPECT_TRUE(open_called.load());
  14274. EXPECT_TRUE(message_received.load());
  14275. }
  14276. // Test: on_message callback
  14277. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14278. // Endpoint that sends multiple events then closes
  14279. server_->Get("/multi-event", [](const Request &, Response &res) {
  14280. res.set_chunked_content_provider(
  14281. "text/event-stream", [](size_t offset, DataSink &sink) {
  14282. if (offset == 0) {
  14283. std::string events = "data: message1\n\ndata: message2\n\n";
  14284. sink.write(events.data(), events.size());
  14285. }
  14286. return false;
  14287. });
  14288. });
  14289. Client client("localhost", get_port());
  14290. sse::SSEClient sse(client, "/multi-event");
  14291. std::vector<std::string> received_messages;
  14292. std::mutex messages_mutex;
  14293. sse.on_message([&](const sse::SSEMessage &msg) {
  14294. std::lock_guard<std::mutex> lock(messages_mutex);
  14295. received_messages.push_back(msg.data);
  14296. });
  14297. sse.set_reconnect_interval(100);
  14298. sse.set_max_reconnect_attempts(1);
  14299. sse.start_async();
  14300. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14301. sse.stop();
  14302. std::lock_guard<std::mutex> lock(messages_mutex);
  14303. EXPECT_GE(received_messages.size(), 2u);
  14304. if (received_messages.size() >= 2) {
  14305. EXPECT_EQ(received_messages[0], "message1");
  14306. EXPECT_EQ(received_messages[1], "message2");
  14307. }
  14308. }
  14309. // Test: on_event for specific types
  14310. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14311. Client client("localhost", get_port());
  14312. sse::SSEClient sse(client, "/custom-events");
  14313. std::atomic<bool> update_received{false};
  14314. std::atomic<bool> delete_received{false};
  14315. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14316. if (msg.data == "updated") { update_received.store(true); }
  14317. });
  14318. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14319. if (msg.data == "deleted") { delete_received.store(true); }
  14320. });
  14321. sse.set_max_reconnect_attempts(1);
  14322. sse.start_async();
  14323. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14324. sse.stop();
  14325. EXPECT_TRUE(update_received.load());
  14326. EXPECT_TRUE(delete_received.load());
  14327. }
  14328. // Test: on_error callback on connection failure
  14329. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14330. // Connect to a non-existent port
  14331. Client client("localhost", 59999);
  14332. sse::SSEClient sse(client, "/events");
  14333. std::atomic<bool> error_called{false};
  14334. Error received_error = Error::Success;
  14335. sse.on_error([&](Error err) {
  14336. error_called.store(true);
  14337. received_error = err;
  14338. });
  14339. sse.set_reconnect_interval(50);
  14340. sse.set_max_reconnect_attempts(1);
  14341. sse.start_async();
  14342. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14343. sse.stop();
  14344. EXPECT_TRUE(error_called.load());
  14345. EXPECT_NE(received_error, Error::Success);
  14346. }
  14347. // Test: Last-Event-ID header sent on reconnect
  14348. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14349. // Endpoint that sends event with ID
  14350. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14351. res.set_chunked_content_provider(
  14352. "text/event-stream", [](size_t offset, DataSink &sink) {
  14353. if (offset == 0) {
  14354. std::string event = "id: evt-123\ndata: test\n\n";
  14355. sink.write(event.data(), event.size());
  14356. }
  14357. return false;
  14358. });
  14359. });
  14360. Client client("localhost", get_port());
  14361. sse::SSEClient sse(client, "/event-with-id");
  14362. std::atomic<bool> id_received{false};
  14363. sse.on_message([&](const sse::SSEMessage &msg) {
  14364. if (!msg.id.empty()) { id_received.store(true); }
  14365. });
  14366. sse.set_reconnect_interval(100);
  14367. sse.set_max_reconnect_attempts(1);
  14368. sse.start_async();
  14369. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14370. sse.stop();
  14371. EXPECT_TRUE(id_received.load());
  14372. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14373. }
  14374. // Test: Manual stop
  14375. TEST_F(SSEIntegrationTest, ManualStop) {
  14376. // Endpoint that sends one event and stays open briefly
  14377. std::atomic<bool> handler_running{true};
  14378. server_->Get("/stay-open", [&handler_running](const Request &,
  14379. Response &res) {
  14380. res.set_chunked_content_provider(
  14381. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14382. if (offset == 0) {
  14383. std::string event = "data: connected\n\n";
  14384. sink.write(event.data(), event.size());
  14385. }
  14386. // Keep connection open while handler_running is true
  14387. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14388. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14389. }
  14390. return false;
  14391. });
  14392. });
  14393. Client client("localhost", get_port());
  14394. sse::SSEClient sse(client, "/stay-open");
  14395. std::atomic<bool> connected{false};
  14396. sse.on_open([&connected]() { connected.store(true); });
  14397. sse.set_reconnect_interval(100);
  14398. sse.set_max_reconnect_attempts(1);
  14399. sse.start_async();
  14400. // Wait for connection to establish
  14401. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14402. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14403. }
  14404. EXPECT_TRUE(connected.load());
  14405. EXPECT_TRUE(sse.is_connected());
  14406. // Signal handler to stop
  14407. handler_running.store(false);
  14408. // Stop SSE client
  14409. sse.stop();
  14410. EXPECT_FALSE(sse.is_connected());
  14411. }
  14412. // Test: SSEClient with custom headers
  14413. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14414. // Setup a server endpoint that checks for custom header
  14415. std::atomic<bool> header_received{false};
  14416. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14417. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14418. header_received.store(true);
  14419. }
  14420. res.set_chunked_content_provider("text/event-stream",
  14421. [](size_t, DataSink &) { return false; });
  14422. });
  14423. Client client("localhost", get_port());
  14424. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14425. sse::SSEClient sse(client, "/header-check", headers);
  14426. sse.set_max_reconnect_attempts(1);
  14427. sse.start_async();
  14428. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14429. sse.stop();
  14430. EXPECT_TRUE(header_received.load());
  14431. }
  14432. // Test: Reconnect interval configuration
  14433. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14434. Client client("localhost", get_port());
  14435. sse::SSEClient sse(client, "/events");
  14436. auto &result = sse.set_reconnect_interval(500);
  14437. // Builder pattern should return reference to self
  14438. EXPECT_EQ(&result, &sse);
  14439. }
  14440. // Test: Max reconnect attempts
  14441. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14442. // Connect to non-existent port to force reconnects
  14443. Client client("localhost", 59998);
  14444. sse::SSEClient sse(client, "/events");
  14445. std::atomic<int> error_count{0};
  14446. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14447. sse.set_reconnect_interval(50);
  14448. sse.set_max_reconnect_attempts(2);
  14449. auto start = std::chrono::steady_clock::now();
  14450. sse.start(); // Blocking call
  14451. auto end = std::chrono::steady_clock::now();
  14452. // Should have stopped after 2 failed attempts
  14453. EXPECT_GE(error_count.load(), 2);
  14454. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14455. auto duration =
  14456. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14457. #ifdef _WIN32
  14458. // Windows is much slower for socket connection failures
  14459. EXPECT_LT(duration.count(), 7000);
  14460. #else
  14461. EXPECT_LT(duration.count(), 1000);
  14462. #endif
  14463. }
  14464. // Test: Multi-line data in integration
  14465. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14466. // Endpoint with multi-line data
  14467. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14468. res.set_chunked_content_provider(
  14469. "text/event-stream", [](size_t offset, DataSink &sink) {
  14470. if (offset == 0) {
  14471. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14472. sink.write(event.data(), event.size());
  14473. }
  14474. return false;
  14475. });
  14476. });
  14477. Client client("localhost", get_port());
  14478. sse::SSEClient sse(client, "/multiline-data");
  14479. std::string received_data;
  14480. std::mutex data_mutex;
  14481. sse.on_message([&](const sse::SSEMessage &msg) {
  14482. std::lock_guard<std::mutex> lock(data_mutex);
  14483. received_data = msg.data;
  14484. });
  14485. sse.set_reconnect_interval(100);
  14486. sse.set_max_reconnect_attempts(1);
  14487. sse.start_async();
  14488. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14489. sse.stop();
  14490. std::lock_guard<std::mutex> lock(data_mutex);
  14491. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14492. }
  14493. // Test: Auto-reconnect after server disconnection
  14494. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14495. std::atomic<int> connection_count{0};
  14496. std::atomic<int> message_count{0};
  14497. // Endpoint that sends one event and closes, forcing reconnect
  14498. server_->Get("/reconnect-test",
  14499. [&connection_count](const Request &, Response &res) {
  14500. connection_count.fetch_add(1);
  14501. res.set_chunked_content_provider(
  14502. "text/event-stream", [](size_t offset, DataSink &sink) {
  14503. if (offset == 0) {
  14504. std::string event = "data: hello\n\n";
  14505. sink.write(event.data(), event.size());
  14506. }
  14507. return false; // Close connection after sending
  14508. });
  14509. });
  14510. Client client("localhost", get_port());
  14511. sse::SSEClient sse(client, "/reconnect-test");
  14512. sse.on_message([&message_count](const sse::SSEMessage &) {
  14513. message_count.fetch_add(1);
  14514. });
  14515. sse.set_reconnect_interval(100);
  14516. sse.set_max_reconnect_attempts(3);
  14517. sse.start_async();
  14518. // Wait long enough for multiple reconnects
  14519. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14520. sse.stop();
  14521. // Should have connected multiple times (initial + reconnects)
  14522. EXPECT_GE(connection_count.load(), 2);
  14523. // Should have received messages from multiple connections
  14524. EXPECT_GE(message_count.load(), 2);
  14525. }
  14526. // Test: Last-Event-ID sent on reconnect
  14527. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14528. std::atomic<int> connection_count{0};
  14529. std::vector<std::string> received_last_event_ids;
  14530. std::mutex id_mutex;
  14531. // Endpoint that checks Last-Event-ID header and sends event with ID
  14532. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14533. int conn = connection_count.fetch_add(1);
  14534. // Capture the Last-Event-ID header from each connection
  14535. {
  14536. std::lock_guard<std::mutex> lock(id_mutex);
  14537. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14538. }
  14539. res.set_chunked_content_provider(
  14540. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14541. if (offset == 0) {
  14542. std::string event =
  14543. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14544. sink.write(event.data(), event.size());
  14545. }
  14546. return false;
  14547. });
  14548. });
  14549. Client client("localhost", get_port());
  14550. sse::SSEClient sse(client, "/reconnect-with-id");
  14551. sse.set_reconnect_interval(100);
  14552. sse.set_max_reconnect_attempts(3);
  14553. sse.start_async();
  14554. // Wait for at least 2 connections
  14555. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14556. sse.stop();
  14557. // Verify behavior
  14558. std::lock_guard<std::mutex> lock(id_mutex);
  14559. EXPECT_GE(received_last_event_ids.size(), 2u);
  14560. // First connection should have no Last-Event-ID
  14561. if (!received_last_event_ids.empty()) {
  14562. EXPECT_EQ(received_last_event_ids[0], "");
  14563. }
  14564. // Second connection should have Last-Event-ID from first connection
  14565. if (received_last_event_ids.size() >= 2) {
  14566. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14567. }
  14568. }
  14569. // Test: set_headers updates headers used on reconnect
  14570. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14571. std::vector<std::string> received_tokens;
  14572. std::mutex token_mutex;
  14573. // Endpoint that captures Authorization header
  14574. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14575. {
  14576. std::lock_guard<std::mutex> lock(token_mutex);
  14577. received_tokens.push_back(req.get_header_value("Authorization"));
  14578. }
  14579. res.set_chunked_content_provider(
  14580. "text/event-stream", [](size_t offset, DataSink &sink) {
  14581. if (offset == 0) {
  14582. std::string event = "data: hello\n\n";
  14583. sink.write(event.data(), event.size());
  14584. }
  14585. return false; // Close connection to trigger reconnect
  14586. });
  14587. });
  14588. Client client("localhost", get_port());
  14589. Headers headers = {{"Authorization", "Bearer old-token"}};
  14590. sse::SSEClient sse(client, "/auth-check", headers);
  14591. // Update headers on each successful connection
  14592. sse.on_open(
  14593. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14594. sse.set_reconnect_interval(100);
  14595. sse.set_max_reconnect_attempts(3);
  14596. sse.start_async();
  14597. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14598. sse.stop();
  14599. std::lock_guard<std::mutex> lock(token_mutex);
  14600. ASSERT_GE(received_tokens.size(), 2u);
  14601. // First connection uses original header
  14602. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14603. // Second connection uses updated header from set_headers
  14604. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14605. }
  14606. // Test: 401 allows reconnection (so on_error can refresh headers)
  14607. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14608. std::atomic<int> connection_count{0};
  14609. // Endpoint: returns 401 on first attempt, 200 on second
  14610. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14611. int conn = connection_count.fetch_add(1);
  14612. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14613. res.status = StatusCode::Unauthorized_401;
  14614. res.set_content("Unauthorized", "text/plain");
  14615. return;
  14616. }
  14617. res.set_chunked_content_provider(
  14618. "text/event-stream", [](size_t offset, DataSink &sink) {
  14619. if (offset == 0) {
  14620. std::string event = "data: authenticated\n\n";
  14621. sink.write(event.data(), event.size());
  14622. }
  14623. return false;
  14624. });
  14625. });
  14626. Client client("localhost", get_port());
  14627. Headers headers = {{"Authorization", "Bearer expired"}};
  14628. sse::SSEClient sse(client, "/auth-retry", headers);
  14629. std::atomic<bool> message_received{false};
  14630. // Refresh token on error
  14631. sse.on_error(
  14632. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14633. sse.on_message([&](const sse::SSEMessage &msg) {
  14634. if (msg.data == "authenticated") { message_received.store(true); }
  14635. });
  14636. sse.set_reconnect_interval(100);
  14637. sse.set_max_reconnect_attempts(3);
  14638. sse.start_async();
  14639. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14640. sse.stop();
  14641. // Should have reconnected after 401 and succeeded with new token
  14642. EXPECT_GE(connection_count.load(), 2);
  14643. EXPECT_TRUE(message_received.load());
  14644. }
  14645. TEST(Issue2318Test, EmptyHostString) {
  14646. {
  14647. httplib::Client cli_empty("", PORT);
  14648. auto res = cli_empty.Get("/");
  14649. ASSERT_FALSE(res);
  14650. EXPECT_EQ(httplib::Error::Connection, res.error());
  14651. }
  14652. {
  14653. httplib::Client cli(" ", PORT);
  14654. auto res = cli.Get("/");
  14655. ASSERT_FALSE(res);
  14656. EXPECT_EQ(httplib::Error::Connection, res.error());
  14657. }
  14658. }
  14659. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14660. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14661. Server svr;
  14662. // Set a small payload limit (1KB)
  14663. svr.set_payload_max_length(1024);
  14664. svr.Post("/test", [&](const Request &req, Response &res) {
  14665. res.set_content("Body size: " + std::to_string(req.body.size()),
  14666. "text/plain");
  14667. });
  14668. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14669. auto se = detail::scope_exit([&] {
  14670. svr.stop();
  14671. listen_thread.join();
  14672. });
  14673. svr.wait_until_ready();
  14674. // Create data that compresses well but exceeds limit when decompressed
  14675. // 8KB of repeated null bytes compresses to a very small size
  14676. std::string original_data(8 * 1024, '\0');
  14677. // Compress the data using gzip
  14678. std::string compressed_data;
  14679. detail::gzip_compressor compressor;
  14680. compressor.compress(original_data.data(), original_data.size(), true,
  14681. [&](const char *data, size_t size) {
  14682. compressed_data.append(data, size);
  14683. return true;
  14684. });
  14685. // Verify compression worked (compressed should be much smaller)
  14686. ASSERT_LT(compressed_data.size(), original_data.size());
  14687. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14688. // Send compressed data with Content-Encoding: gzip
  14689. Client cli(HOST, PORT);
  14690. Headers headers = {{"Content-Encoding", "gzip"}};
  14691. auto res =
  14692. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14693. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14694. ASSERT_TRUE(res);
  14695. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14696. }
  14697. #endif
  14698. // ============================================================================
  14699. // OpenSSL-Specific Tests
  14700. // ============================================================================
  14701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14702. X509 *readCertificate(const std::string &strFileName) {
  14703. std::ifstream inStream(strFileName);
  14704. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14705. std::istreambuf_iterator<char>());
  14706. if (strCertPEM.empty()) return (nullptr);
  14707. BIO *pbCert = BIO_new(BIO_s_mem());
  14708. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14709. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14710. BIO_free(pbCert);
  14711. return (pCert);
  14712. }
  14713. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14714. std::ifstream inStream(strFileName);
  14715. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14716. std::istreambuf_iterator<char>());
  14717. if (strPrivateKeyPEM.empty()) return (nullptr);
  14718. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14719. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14720. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14721. BIO_free(pbPrivKey);
  14722. return (pPrivateKey);
  14723. }
  14724. TEST(BindServerTest, UpdateCerts) {
  14725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14726. int port = svr.bind_to_any_port("0.0.0.0");
  14727. ASSERT_TRUE(svr.is_valid());
  14728. ASSERT_TRUE(port > 0);
  14729. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14730. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14731. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14732. ASSERT_TRUE(cert != nullptr);
  14733. ASSERT_TRUE(ca_cert != nullptr);
  14734. ASSERT_TRUE(key != nullptr);
  14735. X509_STORE *cert_store = X509_STORE_new();
  14736. X509_STORE_add_cert(cert_store, ca_cert);
  14737. // svr.update_certs(cert, key, cert_store); // deprecated
  14738. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14739. CLIENT_CA_CERT_FILE);
  14740. ASSERT_TRUE(svr.is_valid());
  14741. svr.stop();
  14742. X509_STORE_free(cert_store);
  14743. X509_free(cert);
  14744. X509_free(ca_cert);
  14745. EVP_PKEY_free(key);
  14746. }
  14747. // Test that update_certs() updates client CA list correctly
  14748. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14749. // Start with file-based constructor
  14750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14751. ASSERT_TRUE(svr.is_valid());
  14752. // Initially no client CA list should be set
  14753. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14754. ASSERT_TRUE(ssl_ctx != nullptr);
  14755. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14756. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14757. EXPECT_EQ(0, count_before);
  14758. // Now update with client CA (PEM string)
  14759. std::string cert_pem, key_pem, ca_pem;
  14760. read_file(SERVER_CERT_FILE, cert_pem);
  14761. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14762. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14763. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14764. ASSERT_TRUE(svr.is_valid());
  14765. // Now client CA list should be set
  14766. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14767. ASSERT_TRUE(ca_list_after != nullptr);
  14768. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14769. }
  14770. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14771. // Test that the file-path SSLServer constructor properly sets the client CA
  14772. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14774. ASSERT_TRUE(svr.is_valid());
  14775. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14776. ASSERT_TRUE(ssl_ctx != nullptr);
  14777. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14778. ASSERT_TRUE(ca_list != nullptr);
  14779. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14780. }
  14781. #endif
  14782. // ============================================================================
  14783. // MbedTLS-Specific Tests
  14784. // ============================================================================
  14785. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14786. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14787. using namespace httplib::tls;
  14788. // Track if callback was invoked
  14789. bool callback_invoked = false;
  14790. // The callback receives void* ctx which is actually MbedTlsContext*
  14791. // We can access the mbedtls_ssl_config via the context
  14792. auto setup_callback = [&callback_invoked](void *ctx) {
  14793. callback_invoked = true;
  14794. // Cast to MbedTlsContext* to access the ssl config
  14795. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14796. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14797. // Use static variables to hold certificate data (simplified for test)
  14798. static mbedtls_x509_crt own_cert;
  14799. static mbedtls_pk_context own_key;
  14800. static mbedtls_x509_crt ca_chain;
  14801. static bool initialized = false;
  14802. if (!initialized) {
  14803. mbedtls_x509_crt_init(&own_cert);
  14804. mbedtls_pk_init(&own_key);
  14805. mbedtls_x509_crt_init(&ca_chain);
  14806. // Load server certificate
  14807. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14808. return false;
  14809. }
  14810. // Load server private key
  14811. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14812. #if MBEDTLS_VERSION_MAJOR >= 3
  14813. ,
  14814. mbedtls_ctr_drbg_random, nullptr
  14815. #endif
  14816. ) != 0) {
  14817. return false;
  14818. }
  14819. // Load CA chain for client verification
  14820. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14821. return false;
  14822. }
  14823. initialized = true;
  14824. }
  14825. // Configure the SSL config
  14826. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14827. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14828. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14829. // Set minimum TLS version using mbedTLS native API
  14830. #if MBEDTLS_VERSION_MAJOR >= 3
  14831. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14832. #else
  14833. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14834. MBEDTLS_SSL_MINOR_VERSION_3);
  14835. #endif
  14836. return true;
  14837. };
  14838. SSLServer svr(setup_callback);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. ASSERT_TRUE(callback_invoked);
  14841. svr.Get("/test", [&](const Request &req, Response &res) {
  14842. res.set_content("test", "text/plain");
  14843. auto cert = req.peer_cert();
  14844. ASSERT_TRUE(static_cast<bool>(cert));
  14845. auto common_name = cert.subject_cn();
  14846. EXPECT_EQ("Common Name", common_name);
  14847. });
  14848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14849. auto se = detail::scope_exit([&] {
  14850. svr.stop();
  14851. t.join();
  14852. ASSERT_FALSE(svr.is_running());
  14853. });
  14854. svr.wait_until_ready();
  14855. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14856. cli.enable_server_certificate_verification(false);
  14857. cli.set_connection_timeout(30);
  14858. auto res = cli.Get("/test");
  14859. ASSERT_TRUE(res);
  14860. ASSERT_EQ(StatusCode::OK_200, res->status);
  14861. }
  14862. #endif
  14863. // WebSocket Tests
  14864. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14865. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14866. // defining the meaning of these bits has been negotiated.
  14867. auto make_frame = [](uint8_t first_byte) {
  14868. std::string frame;
  14869. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14870. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14871. frame += "Hello";
  14872. return frame;
  14873. };
  14874. // RSV1 set (0x40)
  14875. {
  14876. detail::BufferStream strm;
  14877. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14878. ws::Opcode opcode;
  14879. std::string payload;
  14880. bool fin;
  14881. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14882. false, 1024));
  14883. }
  14884. // RSV2 set (0x20)
  14885. {
  14886. detail::BufferStream strm;
  14887. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14888. ws::Opcode opcode;
  14889. std::string payload;
  14890. bool fin;
  14891. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14892. false, 1024));
  14893. }
  14894. // RSV3 set (0x10)
  14895. {
  14896. detail::BufferStream strm;
  14897. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14898. ws::Opcode opcode;
  14899. std::string payload;
  14900. bool fin;
  14901. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14902. false, 1024));
  14903. }
  14904. // No RSV bits set - should succeed
  14905. {
  14906. detail::BufferStream strm;
  14907. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14908. ws::Opcode opcode;
  14909. std::string payload;
  14910. bool fin;
  14911. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14912. false, 1024));
  14913. EXPECT_EQ(ws::Opcode::Text, opcode);
  14914. EXPECT_EQ("Hello", payload);
  14915. EXPECT_TRUE(fin);
  14916. }
  14917. }
  14918. TEST(WebSocketTest, ControlFrameValidation) {
  14919. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14920. // payload length <= 125.
  14921. // Ping with FIN=0 - must be rejected
  14922. {
  14923. detail::BufferStream strm;
  14924. std::string frame;
  14925. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14926. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14927. strm.write(frame.data(), frame.size());
  14928. ws::Opcode opcode;
  14929. std::string payload;
  14930. bool fin;
  14931. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14932. false, 1024));
  14933. }
  14934. // Close with FIN=0 - must be rejected
  14935. {
  14936. detail::BufferStream strm;
  14937. std::string frame;
  14938. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14939. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14940. strm.write(frame.data(), frame.size());
  14941. ws::Opcode opcode;
  14942. std::string payload;
  14943. bool fin;
  14944. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14945. false, 1024));
  14946. }
  14947. // Ping with payload_len=126 (extended length) - must be rejected
  14948. {
  14949. detail::BufferStream strm;
  14950. std::string frame;
  14951. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14952. frame += static_cast<char>(126); // payload_len=126 (>125)
  14953. frame += static_cast<char>(0x00); // extended length high byte
  14954. frame += static_cast<char>(126); // extended length low byte
  14955. frame += std::string(126, 'x');
  14956. strm.write(frame.data(), frame.size());
  14957. ws::Opcode opcode;
  14958. std::string payload;
  14959. bool fin;
  14960. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14961. false, 1024));
  14962. }
  14963. // Ping with FIN=1 and payload_len=125 - should succeed
  14964. {
  14965. detail::BufferStream strm;
  14966. std::string frame;
  14967. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14968. frame += static_cast<char>(125); // payload_len=125
  14969. frame += std::string(125, 'x');
  14970. strm.write(frame.data(), frame.size());
  14971. ws::Opcode opcode;
  14972. std::string payload;
  14973. bool fin;
  14974. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14975. false, 1024));
  14976. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14977. EXPECT_EQ(125u, payload.size());
  14978. EXPECT_TRUE(fin);
  14979. }
  14980. }
  14981. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14982. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14983. // length MUST be 0.
  14984. // MSB set - must be rejected
  14985. {
  14986. detail::BufferStream strm;
  14987. std::string frame;
  14988. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14989. frame += static_cast<char>(127); // 64-bit extended length
  14990. frame += static_cast<char>(0x80); // MSB set (invalid)
  14991. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14992. strm.write(frame.data(), frame.size());
  14993. ws::Opcode opcode;
  14994. std::string payload;
  14995. bool fin;
  14996. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14997. false, 1024));
  14998. }
  14999. // MSB clear - should pass length parsing (will be rejected by max_len,
  15000. // but that's a different check; use a small length to verify)
  15001. {
  15002. detail::BufferStream strm;
  15003. std::string frame;
  15004. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15005. frame += static_cast<char>(127); // 64-bit extended length
  15006. frame += std::string(7, '\0'); // high bytes = 0
  15007. frame += static_cast<char>(0x03); // length = 3
  15008. frame += "abc";
  15009. strm.write(frame.data(), frame.size());
  15010. ws::Opcode opcode;
  15011. std::string payload;
  15012. bool fin;
  15013. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15014. false, 1024));
  15015. EXPECT_EQ(ws::Opcode::Text, opcode);
  15016. EXPECT_EQ("abc", payload);
  15017. }
  15018. }
  15019. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15020. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15021. // Valid UTF-8
  15022. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15023. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15024. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15025. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15026. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15027. // Invalid UTF-8
  15028. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15029. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15030. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15031. EXPECT_FALSE(
  15032. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15033. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15034. }
  15035. TEST(WebSocketTest, ConnectAndDisconnect) {
  15036. Server svr;
  15037. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15038. std::string msg;
  15039. while (ws.read(msg)) {}
  15040. });
  15041. auto port = svr.bind_to_any_port(HOST);
  15042. std::thread t([&]() { svr.listen_after_bind(); });
  15043. svr.wait_until_ready();
  15044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15045. ASSERT_TRUE(client.connect());
  15046. EXPECT_TRUE(client.is_open());
  15047. client.close();
  15048. EXPECT_FALSE(client.is_open());
  15049. svr.stop();
  15050. t.join();
  15051. }
  15052. TEST(WebSocketTest, ValidURL) {
  15053. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15054. EXPECT_TRUE(ws1.is_valid());
  15055. ws::WebSocketClient ws2("ws://example.com/path");
  15056. EXPECT_TRUE(ws2.is_valid());
  15057. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15058. EXPECT_TRUE(ws3.is_valid());
  15059. #ifdef CPPHTTPLIB_SSL_ENABLED
  15060. ws::WebSocketClient wss1("wss://example.com/path");
  15061. EXPECT_TRUE(wss1.is_valid());
  15062. ws::WebSocketClient wss2("wss://example.com:443/path");
  15063. EXPECT_TRUE(wss2.is_valid());
  15064. #endif
  15065. }
  15066. TEST(WebSocketTest, InvalidURL) {
  15067. // No scheme
  15068. ws::WebSocketClient ws1("localhost:8080/path");
  15069. EXPECT_FALSE(ws1.is_valid());
  15070. // No path
  15071. ws::WebSocketClient ws2("ws://localhost:8080");
  15072. EXPECT_FALSE(ws2.is_valid());
  15073. // Empty string
  15074. ws::WebSocketClient ws3("");
  15075. EXPECT_FALSE(ws3.is_valid());
  15076. // Missing host
  15077. ws::WebSocketClient ws4("ws://:8080/path");
  15078. EXPECT_FALSE(ws4.is_valid());
  15079. // Port number overflow — should not crash
  15080. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15081. EXPECT_FALSE(ws5.is_valid());
  15082. // Port out of range
  15083. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15084. EXPECT_FALSE(ws6.is_valid());
  15085. }
  15086. TEST(WebSocketTest, UnsupportedScheme) {
  15087. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15088. ws::WebSocketClient ws1("http://localhost:8080/path");
  15089. EXPECT_FALSE(ws1.is_valid());
  15090. ws::WebSocketClient ws2("https://localhost:8080/path");
  15091. EXPECT_FALSE(ws2.is_valid());
  15092. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15093. EXPECT_FALSE(ws3.is_valid());
  15094. #else
  15095. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15096. std::invalid_argument);
  15097. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15098. std::invalid_argument);
  15099. #endif
  15100. }
  15101. TEST(WebSocketTest, ConnectWhenInvalid) {
  15102. ws::WebSocketClient ws("not a valid url");
  15103. EXPECT_FALSE(ws.is_valid());
  15104. EXPECT_FALSE(ws.connect());
  15105. }
  15106. TEST(WebSocketTest, DefaultPort) {
  15107. ws::WebSocketClient ws1("ws://example.com/path");
  15108. EXPECT_TRUE(ws1.is_valid());
  15109. // ws:// defaults to port 80 (verified by successful parse)
  15110. #ifdef CPPHTTPLIB_SSL_ENABLED
  15111. ws::WebSocketClient ws2("wss://example.com/path");
  15112. EXPECT_TRUE(ws2.is_valid());
  15113. // wss:// defaults to port 443 (verified by successful parse)
  15114. #endif
  15115. }
  15116. TEST(WebSocketTest, IPv6LiteralAddress) {
  15117. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15118. EXPECT_TRUE(ws1.is_valid());
  15119. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15120. EXPECT_TRUE(ws2.is_valid());
  15121. }
  15122. TEST(WebSocketTest, ComplexPath) {
  15123. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15124. EXPECT_TRUE(ws1.is_valid());
  15125. ws::WebSocketClient ws2("ws://localhost:8080/");
  15126. EXPECT_TRUE(ws2.is_valid());
  15127. }
  15128. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15129. Server svr;
  15130. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15131. std::string msg;
  15132. while (ws.read(msg)) {}
  15133. });
  15134. auto port = svr.bind_to_any_port(HOST);
  15135. std::thread t([&]() { svr.listen_after_bind(); });
  15136. svr.wait_until_ready();
  15137. auto another_host = "example.com";
  15138. auto wrong_ip = "192.0.2.1";
  15139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15140. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15141. ASSERT_TRUE(client.connect());
  15142. EXPECT_TRUE(client.is_open());
  15143. client.close();
  15144. svr.stop();
  15145. t.join();
  15146. }
  15147. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15148. Server svr;
  15149. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15150. std::string msg;
  15151. while (ws.read(msg)) {}
  15152. });
  15153. auto port = svr.bind_to_any_port(HOST);
  15154. std::thread t([&]() { svr.listen_after_bind(); });
  15155. svr.wait_until_ready();
  15156. auto wrong_ip = "192.0.2.1";
  15157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15158. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15159. client.set_connection_timeout(1);
  15160. client.set_read_timeout(1);
  15161. client.set_write_timeout(1);
  15162. EXPECT_FALSE(client.connect());
  15163. EXPECT_FALSE(client.is_open());
  15164. svr.stop();
  15165. t.join();
  15166. }
  15167. class WebSocketIntegrationTest : public ::testing::Test {
  15168. protected:
  15169. void SetUp() override {
  15170. server_ = httplib::detail::make_unique<Server>();
  15171. setup_server();
  15172. start_server();
  15173. }
  15174. void TearDown() override {
  15175. server_->stop();
  15176. if (server_thread_.joinable()) { server_thread_.join(); }
  15177. }
  15178. void setup_server() {
  15179. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15180. std::string msg;
  15181. ws::ReadResult ret;
  15182. while ((ret = ws.read(msg))) {
  15183. if (ret == ws::Binary) {
  15184. ws.send(msg.data(), msg.size());
  15185. } else {
  15186. ws.send(msg);
  15187. }
  15188. }
  15189. });
  15190. server_->WebSocket("/ws-echo-string",
  15191. [](const Request &, ws::WebSocket &ws) {
  15192. std::string msg;
  15193. while (ws.read(msg)) {
  15194. ws.send("echo: " + msg);
  15195. }
  15196. });
  15197. server_->WebSocket(
  15198. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15199. // Echo back request metadata
  15200. ws.send("path:" + req.path);
  15201. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15202. std::string msg;
  15203. while (ws.read(msg)) {}
  15204. });
  15205. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15206. std::string msg;
  15207. ws.read(msg); // wait for a message
  15208. ws.close();
  15209. });
  15210. server_->WebSocket("/ws-close-status",
  15211. [](const Request &, ws::WebSocket &ws) {
  15212. std::string msg;
  15213. ws.read(msg); // wait for a message
  15214. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15215. });
  15216. server_->WebSocket(
  15217. "/ws-subprotocol",
  15218. [](const Request &, ws::WebSocket &ws) {
  15219. std::string msg;
  15220. while (ws.read(msg)) {
  15221. ws.send(msg);
  15222. }
  15223. },
  15224. [](const std::vector<std::string> &protocols) -> std::string {
  15225. for (const auto &p : protocols) {
  15226. if (p == "graphql-ws") { return p; }
  15227. }
  15228. return "";
  15229. });
  15230. }
  15231. void start_server() {
  15232. port_ = server_->bind_to_any_port(HOST);
  15233. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15234. server_->wait_until_ready();
  15235. }
  15236. std::unique_ptr<Server> server_;
  15237. std::thread server_thread_;
  15238. int port_ = 0;
  15239. };
  15240. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15242. "/ws-echo");
  15243. ASSERT_TRUE(client.connect());
  15244. ASSERT_TRUE(client.is_open());
  15245. ASSERT_TRUE(client.send("Hello WebSocket"));
  15246. std::string msg;
  15247. EXPECT_EQ(ws::Text, client.read(msg));
  15248. EXPECT_EQ("Hello WebSocket", msg);
  15249. client.close();
  15250. }
  15251. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15252. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15253. "/ws-echo");
  15254. ASSERT_TRUE(client.connect());
  15255. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15256. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15257. std::string msg;
  15258. EXPECT_EQ(ws::Binary, client.read(msg));
  15259. EXPECT_EQ(binary_data, msg);
  15260. client.close();
  15261. }
  15262. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15263. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15264. "/ws-echo");
  15265. ASSERT_TRUE(client.connect());
  15266. for (int i = 0; i < 10; i++) {
  15267. auto text = "message " + std::to_string(i);
  15268. ASSERT_TRUE(client.send(text));
  15269. std::string msg;
  15270. ASSERT_TRUE(client.read(msg));
  15271. EXPECT_EQ(text, msg);
  15272. }
  15273. client.close();
  15274. }
  15275. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15276. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15277. "/ws-close");
  15278. ASSERT_TRUE(client.connect());
  15279. // Send a message to trigger the server to close
  15280. ASSERT_TRUE(client.send("trigger close"));
  15281. // The server will close, so read should return false
  15282. std::string msg;
  15283. EXPECT_FALSE(client.read(msg));
  15284. EXPECT_FALSE(client.is_open());
  15285. }
  15286. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15288. "/ws-echo");
  15289. ASSERT_TRUE(client.connect());
  15290. // 128KB message
  15291. std::string large_data(128 * 1024, 'X');
  15292. ASSERT_TRUE(client.send(large_data));
  15293. std::string msg;
  15294. ASSERT_TRUE(client.read(msg));
  15295. EXPECT_EQ(large_data, msg);
  15296. client.close();
  15297. }
  15298. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15300. "/ws-echo");
  15301. ASSERT_TRUE(client.connect());
  15302. const int num_threads = 4;
  15303. std::vector<std::thread> threads;
  15304. std::atomic<int> send_count{0};
  15305. for (int t = 0; t < num_threads; t++) {
  15306. threads.emplace_back([&client, &send_count, t]() {
  15307. for (int i = 0; i < 5; i++) {
  15308. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15309. if (client.send(text)) { send_count++; }
  15310. }
  15311. });
  15312. }
  15313. for (auto &th : threads) {
  15314. th.join();
  15315. }
  15316. int received = 0;
  15317. std::string msg;
  15318. while (received < send_count.load()) {
  15319. if (!client.read(msg)) { break; }
  15320. received++;
  15321. }
  15322. EXPECT_EQ(send_count.load(), received);
  15323. client.close();
  15324. }
  15325. TEST_F(WebSocketIntegrationTest, ReadString) {
  15326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15327. "/ws-echo-string");
  15328. ASSERT_TRUE(client.connect());
  15329. ASSERT_TRUE(client.send("hello"));
  15330. std::string msg;
  15331. ASSERT_TRUE(client.read(msg));
  15332. EXPECT_EQ("echo: hello", msg);
  15333. ASSERT_TRUE(client.send("world"));
  15334. ASSERT_TRUE(client.read(msg));
  15335. EXPECT_EQ("echo: world", msg);
  15336. client.close();
  15337. }
  15338. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15339. Headers headers = {{"X-Test-Header", "test-value"}};
  15340. ws::WebSocketClient client(
  15341. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15342. ASSERT_TRUE(client.connect());
  15343. std::string msg;
  15344. ASSERT_TRUE(client.read(msg));
  15345. EXPECT_EQ("path:/ws-request-info", msg);
  15346. ASSERT_TRUE(client.read(msg));
  15347. EXPECT_EQ("header:test-value", msg);
  15348. client.close();
  15349. }
  15350. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15352. "/ws-echo");
  15353. client.set_read_timeout(1, 0); // 1 second
  15354. ASSERT_TRUE(client.connect());
  15355. // Don't send anything — server echo handler waits for a message,
  15356. // so read() should time out and return false.
  15357. std::string msg;
  15358. EXPECT_FALSE(client.read(msg));
  15359. }
  15360. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15362. "/ws-echo");
  15363. client.set_read_timeout(5, 0);
  15364. ASSERT_TRUE(client.connect());
  15365. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15366. // The server should reject it and close the connection.
  15367. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15368. client.send(oversized);
  15369. // The server's read() should have failed due to payload limit,
  15370. // so our read() should return false (connection closed).
  15371. std::string msg;
  15372. EXPECT_FALSE(client.read(msg));
  15373. }
  15374. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15375. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15376. "/ws-echo");
  15377. client.set_read_timeout(10, 0);
  15378. ASSERT_TRUE(client.connect());
  15379. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15380. // This should succeed.
  15381. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15382. ASSERT_TRUE(client.send(at_limit));
  15383. std::string msg;
  15384. ASSERT_TRUE(client.read(msg));
  15385. EXPECT_EQ(at_limit.size(), msg.size());
  15386. client.close();
  15387. }
  15388. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15390. "/nonexistent");
  15391. EXPECT_FALSE(client.connect());
  15392. EXPECT_FALSE(client.is_open());
  15393. }
  15394. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15395. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15396. "/ws-echo");
  15397. ASSERT_TRUE(client.connect());
  15398. ASSERT_TRUE(client.send(""));
  15399. std::string msg;
  15400. EXPECT_EQ(ws::Text, client.read(msg));
  15401. EXPECT_EQ("", msg);
  15402. client.close();
  15403. }
  15404. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15405. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15406. "/ws-echo");
  15407. // First connection
  15408. ASSERT_TRUE(client.connect());
  15409. ASSERT_TRUE(client.send("first"));
  15410. std::string msg;
  15411. ASSERT_TRUE(client.read(msg));
  15412. EXPECT_EQ("first", msg);
  15413. client.close();
  15414. EXPECT_FALSE(client.is_open());
  15415. // Reconnect using the same client object
  15416. ASSERT_TRUE(client.connect());
  15417. ASSERT_TRUE(client.is_open());
  15418. ASSERT_TRUE(client.send("second"));
  15419. ASSERT_TRUE(client.read(msg));
  15420. EXPECT_EQ("second", msg);
  15421. client.close();
  15422. }
  15423. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15424. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15425. "/ws-close-status");
  15426. ASSERT_TRUE(client.connect());
  15427. // Trigger the server to close with GoingAway status
  15428. ASSERT_TRUE(client.send("trigger"));
  15429. // read() should return false after receiving the close frame
  15430. std::string msg;
  15431. EXPECT_FALSE(client.read(msg));
  15432. EXPECT_FALSE(client.is_open());
  15433. }
  15434. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15435. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15436. "/ws-echo");
  15437. ASSERT_TRUE(client.connect());
  15438. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15439. EXPECT_FALSE(client.is_open());
  15440. }
  15441. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15442. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15443. ws::WebSocketClient client(
  15444. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15445. ASSERT_TRUE(client.connect());
  15446. // Server should have selected graphql-ws
  15447. EXPECT_EQ("graphql-ws", client.subprotocol());
  15448. client.close();
  15449. }
  15450. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15451. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15452. ws::WebSocketClient client(
  15453. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15454. ASSERT_TRUE(client.connect());
  15455. // Server should not have selected any subprotocol
  15456. EXPECT_TRUE(client.subprotocol().empty());
  15457. client.close();
  15458. }
  15459. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15460. // Connect without requesting any subprotocol
  15461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15462. "/ws-subprotocol");
  15463. ASSERT_TRUE(client.connect());
  15464. EXPECT_TRUE(client.subprotocol().empty());
  15465. client.close();
  15466. }
  15467. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15469. "/ws-echo");
  15470. client.set_tcp_nodelay(true);
  15471. client.set_connection_timeout(3, 0);
  15472. bool socket_options_called = false;
  15473. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15474. ASSERT_TRUE(client.connect());
  15475. ASSERT_TRUE(client.is_open());
  15476. EXPECT_TRUE(socket_options_called);
  15477. ASSERT_TRUE(client.send("hello"));
  15478. std::string msg;
  15479. auto result = client.read(msg);
  15480. EXPECT_EQ(result, ws::ReadResult::Text);
  15481. EXPECT_EQ(msg, "hello");
  15482. client.close();
  15483. }
  15484. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15485. Server svr;
  15486. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15487. if (!req.has_header("Authorization")) {
  15488. res.status = StatusCode::Unauthorized_401;
  15489. res.set_content("Unauthorized", "text/plain");
  15490. return Server::HandlerResponse::Handled;
  15491. }
  15492. return Server::HandlerResponse::Unhandled;
  15493. });
  15494. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15495. std::string msg;
  15496. while (ws.read(msg)) {
  15497. ws.send(msg);
  15498. }
  15499. });
  15500. auto port = svr.bind_to_any_port("localhost");
  15501. std::thread t([&]() { svr.listen_after_bind(); });
  15502. svr.wait_until_ready();
  15503. // Without Authorization header - should be rejected before upgrade
  15504. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15505. EXPECT_FALSE(client1.connect());
  15506. // With Authorization header - should succeed
  15507. Headers headers = {{"Authorization", "Bearer token123"}};
  15508. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15509. headers);
  15510. ASSERT_TRUE(client2.connect());
  15511. ASSERT_TRUE(client2.send("hello"));
  15512. std::string msg;
  15513. ASSERT_TRUE(client2.read(msg));
  15514. EXPECT_EQ("hello", msg);
  15515. client2.close();
  15516. svr.stop();
  15517. t.join();
  15518. }
  15519. TEST(WebSocketTest, QueryStringInHandshake) {
  15520. Server svr;
  15521. std::mutex mtx;
  15522. std::string received_target;
  15523. std::string received_token;
  15524. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15525. {
  15526. std::lock_guard<std::mutex> lock(mtx);
  15527. received_target = req.target;
  15528. if (req.has_param("token")) {
  15529. received_token = req.get_param_value("token");
  15530. }
  15531. }
  15532. std::string msg;
  15533. while (ws.read(msg)) {
  15534. ws.send(msg);
  15535. }
  15536. });
  15537. auto port = svr.bind_to_any_port("localhost");
  15538. std::thread t([&]() { svr.listen_after_bind(); });
  15539. svr.wait_until_ready();
  15540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15541. "/ws?token=ABC&session=123");
  15542. ASSERT_TRUE(client.connect());
  15543. // Round-trip ensures the handler has run and captured the request.
  15544. ASSERT_TRUE(client.send("hello"));
  15545. std::string msg;
  15546. ASSERT_TRUE(client.read(msg));
  15547. EXPECT_EQ("hello", msg);
  15548. client.close();
  15549. {
  15550. std::lock_guard<std::mutex> lock(mtx);
  15551. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15552. EXPECT_EQ("ABC", received_token);
  15553. }
  15554. svr.stop();
  15555. t.join();
  15556. }
  15557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15558. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15559. protected:
  15560. void SetUp() override {
  15561. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15562. SERVER_PRIVATE_KEY_FILE);
  15563. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15564. std::string msg;
  15565. ws::ReadResult ret;
  15566. while ((ret = ws.read(msg))) {
  15567. if (ret == ws::Binary) {
  15568. ws.send(msg.data(), msg.size());
  15569. } else {
  15570. ws.send(msg);
  15571. }
  15572. }
  15573. });
  15574. port_ = server_->bind_to_any_port(HOST);
  15575. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15576. server_->wait_until_ready();
  15577. }
  15578. void TearDown() override {
  15579. server_->stop();
  15580. if (server_thread_.joinable()) { server_thread_.join(); }
  15581. }
  15582. std::unique_ptr<SSLServer> server_;
  15583. std::thread server_thread_;
  15584. int port_ = 0;
  15585. };
  15586. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15587. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15588. "/ws-echo");
  15589. client.enable_server_certificate_verification(false);
  15590. ASSERT_TRUE(client.connect());
  15591. ASSERT_TRUE(client.is_open());
  15592. ASSERT_TRUE(client.send("Hello WSS"));
  15593. std::string msg;
  15594. EXPECT_EQ(ws::Text, client.read(msg));
  15595. EXPECT_EQ("Hello WSS", msg);
  15596. client.close();
  15597. }
  15598. #endif
  15599. #ifdef CPPHTTPLIB_SSL_ENABLED
  15600. class WebSocketSSLCATest : public ::testing::Test {
  15601. protected:
  15602. void SetUp() override {
  15603. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15604. SERVER_PRIVATE_KEY_FILE);
  15605. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15606. std::string msg;
  15607. while (ws.read(msg)) {
  15608. ws.send(msg);
  15609. }
  15610. });
  15611. port_ = server_->bind_to_any_port("127.0.0.1");
  15612. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15613. server_->wait_until_ready();
  15614. }
  15615. void TearDown() override {
  15616. server_->stop();
  15617. if (server_thread_.joinable()) { server_thread_.join(); }
  15618. }
  15619. std::string url() const {
  15620. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15621. }
  15622. std::unique_ptr<SSLServer> server_;
  15623. std::thread server_thread_;
  15624. int port_ = 0;
  15625. };
  15626. // A custom CA loaded as PEM verifies the server with full certificate
  15627. // verification enabled
  15628. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15629. ws::WebSocketClient client(url());
  15630. std::string cert;
  15631. read_file(SERVER_CERT2_FILE, cert);
  15632. client.load_ca_cert_store(cert.c_str(), cert.size());
  15633. ASSERT_TRUE(client.connect());
  15634. ASSERT_TRUE(client.send("hello"));
  15635. std::string msg;
  15636. EXPECT_EQ(ws::Text, client.read(msg));
  15637. EXPECT_EQ("hello", msg);
  15638. client.close();
  15639. }
  15640. // A custom CA that does not cover the server must fail verification (the
  15641. // custom CA is exclusive; system certs are not loaded alongside it)
  15642. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15643. ws::WebSocketClient client(url());
  15644. std::string cert;
  15645. read_file(CLIENT_CA_CERT_FILE, cert);
  15646. client.load_ca_cert_store(cert.c_str(), cert.size());
  15647. ASSERT_FALSE(client.connect());
  15648. }
  15649. // Regression test: reconnecting with a native custom CA store used to reuse
  15650. // a store handle the previous TLS context had already freed (use-after-free
  15651. // under the OpenSSL backend). The context now lives as long as the client.
  15652. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15653. ws::WebSocketClient client(url());
  15654. std::string cert;
  15655. read_file(SERVER_CERT2_FILE, cert);
  15656. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15657. ASSERT_TRUE(client.connect());
  15658. client.close();
  15659. ASSERT_TRUE(client.connect());
  15660. ASSERT_TRUE(client.send("again"));
  15661. std::string msg;
  15662. EXPECT_EQ(ws::Text, client.read(msg));
  15663. EXPECT_EQ("again", msg);
  15664. client.close();
  15665. }
  15666. // Regression test: a certificate with a trusted chain but no identity match
  15667. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15668. // verification entirely for IP hosts, so this connection succeeded there.
  15669. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15670. // chain verification while the identity check must still fail.
  15671. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15673. ASSERT_TRUE(svr.is_valid());
  15674. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15675. std::string msg;
  15676. while (ws.read(msg)) {
  15677. ws.send(msg);
  15678. }
  15679. });
  15680. auto port = svr.bind_to_any_port("127.0.0.1");
  15681. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15682. auto se = detail::scope_exit([&] {
  15683. svr.stop();
  15684. t.join();
  15685. });
  15686. svr.wait_until_ready();
  15687. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  15688. "/echo");
  15689. std::string cert;
  15690. read_file(SERVER_CERT_FILE, cert);
  15691. client.load_ca_cert_store(cert.c_str(), cert.size());
  15692. ASSERT_FALSE(client.connect());
  15693. }
  15694. #endif
  15695. #if !defined(_WIN32)
  15696. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15697. auto secret_dir = std::string("./symlink_test_secret");
  15698. auto served_dir = std::string("./symlink_test_served");
  15699. auto secret_file = secret_dir + "/secret.txt";
  15700. auto symlink_path = served_dir + "/escape";
  15701. // Setup: create directories and files
  15702. mkdir(secret_dir.c_str(), 0755);
  15703. mkdir(served_dir.c_str(), 0755);
  15704. {
  15705. std::ofstream ofs(secret_file);
  15706. ofs << "SECRET_DATA";
  15707. }
  15708. // Create symlink using absolute path so it resolves correctly
  15709. #ifdef PATH_MAX
  15710. char abs_secret[PATH_MAX];
  15711. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15712. #else
  15713. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15714. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15715. ASSERT_NE(nullptr, abs_secret);
  15716. #endif
  15717. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15718. auto se = detail::scope_exit([&] {
  15719. unlink(symlink_path.c_str());
  15720. unlink(secret_file.c_str());
  15721. rmdir(served_dir.c_str());
  15722. rmdir(secret_dir.c_str());
  15723. });
  15724. Server svr;
  15725. svr.set_mount_point("/", served_dir);
  15726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15727. auto se2 = detail::scope_exit([&] {
  15728. svr.stop();
  15729. listen_thread.join();
  15730. });
  15731. svr.wait_until_ready();
  15732. Client cli("localhost", PORT);
  15733. // Symlink pointing outside base dir should be blocked
  15734. auto res = cli.Get("/escape/secret.txt");
  15735. ASSERT_TRUE(res);
  15736. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15737. }
  15738. #endif
  15739. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15740. // A GET request with Content-Length to a static file handler must have its
  15741. // body drained before the keep-alive connection is reused. Otherwise the
  15742. // unread body bytes are interpreted as the next HTTP request.
  15743. //
  15744. // The body is sent AFTER receiving the first response (as in the original
  15745. // PoC) so that the stream_line_reader cannot buffer it together with the
  15746. // headers of the first request.
  15747. Server svr;
  15748. svr.set_mount_point("/", "./www");
  15749. std::atomic<int> smuggled_count(0);
  15750. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15751. smuggled_count++;
  15752. res.set_content("oops", "text/plain");
  15753. });
  15754. auto port = svr.bind_to_any_port("localhost");
  15755. thread t = thread([&] { svr.listen_after_bind(); });
  15756. auto se = detail::scope_exit([&] {
  15757. svr.stop();
  15758. t.join();
  15759. });
  15760. svr.wait_until_ready();
  15761. auto error = Error::Success;
  15762. auto sock = detail::create_client_socket(
  15763. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15764. /*connection_timeout_sec=*/2, 0,
  15765. /*read_timeout_sec=*/2, 0,
  15766. /*write_timeout_sec=*/2, 0, std::string(), error);
  15767. ASSERT_NE(INVALID_SOCKET, sock);
  15768. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15769. // The "smuggled" request will be sent as the body of the outer GET
  15770. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15771. "Host: localhost\r\n"
  15772. "Connection: close\r\n"
  15773. "\r\n";
  15774. // Step 1: Send only the outer request headers (no body yet)
  15775. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15776. "Host: localhost\r\n"
  15777. "Content-Length: " +
  15778. std::to_string(smuggled.size()) +
  15779. "\r\n"
  15780. "\r\n";
  15781. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15782. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15783. // Step 2: Read the first response (server serves file without reading body)
  15784. std::string first_response;
  15785. char buf[4096];
  15786. for (;;) {
  15787. auto n = recv(sock, buf, sizeof(buf), 0);
  15788. if (n <= 0) break;
  15789. first_response.append(buf, static_cast<size_t>(n));
  15790. // Stop once we have a complete response (headers + body)
  15791. auto hdr_end = first_response.find("\r\n\r\n");
  15792. if (hdr_end != std::string::npos) {
  15793. // Check for Content-Length to know when the body is complete
  15794. auto cl_pos = first_response.find("Content-Length:");
  15795. if (cl_pos != std::string::npos) {
  15796. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15797. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15798. auto cl = std::stoul(
  15799. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15800. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15801. } else {
  15802. break; // No Content-Length, assume headers-only response
  15803. }
  15804. }
  15805. }
  15806. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15807. // Step 3: Now send the body, which looks like a new HTTP request.
  15808. // On a vulnerable server the keep-alive loop reads this as a second request.
  15809. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15810. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15811. // Step 4: Try to read a second response (should NOT exist after fix)
  15812. std::string second_response;
  15813. for (;;) {
  15814. auto n = recv(sock, buf, sizeof(buf), 0);
  15815. if (n <= 0) break;
  15816. second_response.append(buf, static_cast<size_t>(n));
  15817. }
  15818. // The smuggled request must NOT have been processed
  15819. EXPECT_EQ(0, smuggled_count.load());
  15820. }
  15821. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15822. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15823. // must be rejected with 400 Bad Request.
  15824. Server svr;
  15825. svr.Post("/test", [&](const Request &, Response &res) {
  15826. res.set_content("ok", "text/plain");
  15827. });
  15828. thread t = thread([&] { svr.listen(HOST, PORT); });
  15829. auto se = detail::scope_exit([&] {
  15830. svr.stop();
  15831. t.join();
  15832. ASSERT_FALSE(svr.is_running());
  15833. });
  15834. svr.wait_until_ready();
  15835. // Exact "chunked"
  15836. {
  15837. auto req = "POST /test HTTP/1.1\r\n"
  15838. "Host: localhost\r\n"
  15839. "Content-Length: 5\r\n"
  15840. "Transfer-Encoding: chunked\r\n"
  15841. "Connection: close\r\n"
  15842. "\r\n"
  15843. "hello";
  15844. std::string response;
  15845. ASSERT_TRUE(send_request(1, req, &response));
  15846. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15847. response.substr(0, response.find("\r\n")));
  15848. }
  15849. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15850. {
  15851. auto req = "POST /test HTTP/1.1\r\n"
  15852. "Host: localhost\r\n"
  15853. "Content-Length: 5\r\n"
  15854. "Transfer-Encoding: gzip, chunked\r\n"
  15855. "Connection: close\r\n"
  15856. "\r\n"
  15857. "hello";
  15858. std::string response;
  15859. ASSERT_TRUE(send_request(1, req, &response));
  15860. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15861. response.substr(0, response.find("\r\n")));
  15862. }
  15863. }
  15864. // Regression for issue #2450: a DELETE without Content-Length on a
  15865. // keep-alive connection must not let the post-response drain consume the
  15866. // next request's bytes.
  15867. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15868. Server svr;
  15869. std::atomic<int> delete_count(0);
  15870. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15871. delete_count++;
  15872. res.status = StatusCode::NoContent_204;
  15873. });
  15874. auto port = svr.bind_to_any_port(HOST);
  15875. thread t = thread([&] { svr.listen_after_bind(); });
  15876. auto se = detail::scope_exit([&] {
  15877. svr.stop();
  15878. t.join();
  15879. });
  15880. svr.wait_until_ready();
  15881. auto error = Error::Success;
  15882. auto sock = detail::create_client_socket(
  15883. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15884. /*connection_timeout_sec=*/2, 0,
  15885. /*read_timeout_sec=*/2, 0,
  15886. /*write_timeout_sec=*/2, 0, std::string(), error);
  15887. ASSERT_NE(INVALID_SOCKET, sock);
  15888. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15889. auto send_request_and_read_response = [&](const std::string &req,
  15890. std::string &out) -> bool {
  15891. auto sent = send(sock, req.data(), req.size(), 0);
  15892. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15893. char buf[4096];
  15894. for (;;) {
  15895. auto n = recv(sock, buf, sizeof(buf), 0);
  15896. if (n <= 0) { return !out.empty(); }
  15897. out.append(buf, static_cast<size_t>(n));
  15898. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15899. }
  15900. };
  15901. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15902. "Host: localhost\r\n"
  15903. "\r\n";
  15904. std::string resp1;
  15905. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15906. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15907. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15908. "Host: localhost\r\n"
  15909. "Connection: close\r\n"
  15910. "\r\n";
  15911. std::string resp2;
  15912. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15913. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15914. EXPECT_EQ(2, delete_count.load());
  15915. }
  15916. namespace no_proxy_test {
  15917. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15918. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15919. // calling listen().
  15920. class ScopedServer {
  15921. public:
  15922. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15923. ~ScopedServer() {
  15924. svr_.stop();
  15925. if (th_.joinable()) { th_.join(); }
  15926. }
  15927. Server &svr() { return svr_; }
  15928. int port() const { return port_; }
  15929. void listen() {
  15930. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15931. svr_.wait_until_ready();
  15932. }
  15933. private:
  15934. Server svr_;
  15935. std::thread th_;
  15936. int port_ = 0;
  15937. };
  15938. class ProxyAndTargetServers {
  15939. public:
  15940. ProxyAndTargetServers() {
  15941. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15942. proxy_hits_++;
  15943. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15944. res.set_content("via-proxy", "text/plain");
  15945. });
  15946. target_.Get(".*", [this](const Request &req, Response &res) {
  15947. target_hits_++;
  15948. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15949. res.set_content("direct", "text/plain");
  15950. });
  15951. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15952. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15953. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15954. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15955. proxy_mock_.wait_until_ready();
  15956. target_.wait_until_ready();
  15957. }
  15958. ~ProxyAndTargetServers() {
  15959. proxy_mock_.stop();
  15960. target_.stop();
  15961. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15962. if (target_thread_.joinable()) { target_thread_.join(); }
  15963. }
  15964. Server &proxy_mock() { return proxy_mock_; }
  15965. Server &target() { return target_; }
  15966. int proxy_port() const { return proxy_port_; }
  15967. int target_port() const { return target_port_; }
  15968. int proxy_hits() const { return proxy_hits_.load(); }
  15969. int target_hits() const { return target_hits_.load(); }
  15970. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15971. void reset_counters() {
  15972. proxy_hits_ = 0;
  15973. target_hits_ = 0;
  15974. last_had_proxy_authz_ = false;
  15975. }
  15976. private:
  15977. Server proxy_mock_;
  15978. Server target_;
  15979. std::thread proxy_thread_;
  15980. std::thread target_thread_;
  15981. int proxy_port_ = 0;
  15982. int target_port_ = 0;
  15983. std::atomic<int> proxy_hits_{0};
  15984. std::atomic<int> target_hits_{0};
  15985. std::atomic<bool> last_had_proxy_authz_{false};
  15986. };
  15987. inline std::unique_ptr<Client> make_client(const std::string &host,
  15988. ProxyAndTargetServers &s) {
  15989. auto cli = detail::make_unique<Client>(host, s.target_port());
  15990. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15991. cli->set_proxy("127.0.0.1", s.proxy_port());
  15992. return cli;
  15993. }
  15994. } // namespace no_proxy_test
  15995. using no_proxy_test::make_client;
  15996. using no_proxy_test::ProxyAndTargetServers;
  15997. TEST(NoProxyTest, ExactHostnameBypasses) {
  15998. ProxyAndTargetServers s;
  15999. auto cli = make_client("example.com", s);
  16000. cli->set_no_proxy({"example.com"});
  16001. auto res = cli->Get("/");
  16002. ASSERT_TRUE(res);
  16003. EXPECT_EQ(0, s.proxy_hits());
  16004. EXPECT_EQ(1, s.target_hits());
  16005. }
  16006. TEST(NoProxyTest, SubdomainBypasses) {
  16007. ProxyAndTargetServers s;
  16008. auto cli = make_client("foo.example.com", s);
  16009. cli->set_no_proxy({"example.com"});
  16010. auto res = cli->Get("/");
  16011. ASSERT_TRUE(res);
  16012. EXPECT_EQ(0, s.proxy_hits());
  16013. EXPECT_EQ(1, s.target_hits());
  16014. }
  16015. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16016. // Regression guard: "evilexample.com" must not be considered a subdomain
  16017. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16018. // check would let traffic bypass the proxy and leak credentials direct
  16019. // to the attacker host.
  16020. ProxyAndTargetServers s;
  16021. auto cli = make_client("evilexample.com", s);
  16022. cli->set_no_proxy({"example.com"});
  16023. auto res = cli->Get("/");
  16024. ASSERT_TRUE(res);
  16025. EXPECT_GE(s.proxy_hits(), 1);
  16026. EXPECT_EQ(0, s.target_hits());
  16027. }
  16028. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16029. ProxyAndTargetServers s;
  16030. auto cli = make_client("example.com.evil.com", s);
  16031. cli->set_no_proxy({"example.com"});
  16032. auto res = cli->Get("/");
  16033. ASSERT_TRUE(res);
  16034. EXPECT_GE(s.proxy_hits(), 1);
  16035. EXPECT_EQ(0, s.target_hits());
  16036. }
  16037. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16038. ProxyAndTargetServers s;
  16039. auto cli = make_client("example.com", s);
  16040. cli->set_no_proxy({".example.com"});
  16041. auto res = cli->Get("/");
  16042. ASSERT_TRUE(res);
  16043. EXPECT_EQ(0, s.proxy_hits());
  16044. EXPECT_EQ(1, s.target_hits());
  16045. }
  16046. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16047. ProxyAndTargetServers s;
  16048. auto cli = make_client("Example.COM", s);
  16049. cli->set_no_proxy({"EXAMPLE.com"});
  16050. auto res = cli->Get("/");
  16051. ASSERT_TRUE(res);
  16052. EXPECT_EQ(0, s.proxy_hits());
  16053. EXPECT_EQ(1, s.target_hits());
  16054. }
  16055. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16056. ProxyAndTargetServers s;
  16057. auto cli = make_client("example.com.", s);
  16058. cli->set_no_proxy({"example.com"});
  16059. auto res = cli->Get("/");
  16060. ASSERT_TRUE(res);
  16061. EXPECT_EQ(0, s.proxy_hits());
  16062. EXPECT_EQ(1, s.target_hits());
  16063. }
  16064. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16065. // Trailing dots must be normalized on BOTH sides — host and entry.
  16066. // An implementation that only strips the host-side trailing dot would
  16067. // fail to match host "example.com" against entry "example.com." because
  16068. // a literal substring search would compare 11 chars against 12.
  16069. ProxyAndTargetServers s;
  16070. auto cli = make_client("example.com", s);
  16071. cli->set_no_proxy({"example.com."});
  16072. auto res = cli->Get("/");
  16073. ASSERT_TRUE(res);
  16074. EXPECT_EQ(0, s.proxy_hits());
  16075. EXPECT_EQ(1, s.target_hits());
  16076. }
  16077. TEST(NoProxyTest, WildcardBypassesEverything) {
  16078. ProxyAndTargetServers s;
  16079. auto cli = make_client("anything.invalid.test", s);
  16080. cli->set_no_proxy({"*"});
  16081. auto res = cli->Get("/");
  16082. ASSERT_TRUE(res);
  16083. EXPECT_EQ(0, s.proxy_hits());
  16084. EXPECT_EQ(1, s.target_hits());
  16085. }
  16086. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16087. ProxyAndTargetServers s;
  16088. Client cli("127.0.0.1", s.target_port());
  16089. cli.set_proxy("127.0.0.1", s.proxy_port());
  16090. cli.set_no_proxy({"127.0.0.1"});
  16091. auto res = cli.Get("/");
  16092. ASSERT_TRUE(res);
  16093. EXPECT_EQ(0, s.proxy_hits());
  16094. EXPECT_EQ(1, s.target_hits());
  16095. }
  16096. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16097. ProxyAndTargetServers s;
  16098. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16099. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16100. cli.set_proxy("127.0.0.1", s.proxy_port());
  16101. cli.set_no_proxy({"::1"});
  16102. auto res = cli.Get("/");
  16103. ASSERT_TRUE(res);
  16104. EXPECT_EQ(0, s.proxy_hits());
  16105. EXPECT_EQ(1, s.target_hits());
  16106. }
  16107. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16108. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16109. // must still be recognized as IPv6 for CIDR matching. Implementations
  16110. // that detect IPv6 only when the host begins with '[' would parse the
  16111. // host as a hostname and miss the match.
  16112. ProxyAndTargetServers s;
  16113. Client cli("fe80::1", s.target_port());
  16114. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16115. cli.set_proxy("127.0.0.1", s.proxy_port());
  16116. cli.set_no_proxy({"fe80::/10"});
  16117. auto res = cli.Get("/");
  16118. ASSERT_TRUE(res);
  16119. EXPECT_EQ(0, s.proxy_hits());
  16120. EXPECT_EQ(1, s.target_hits());
  16121. }
  16122. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16123. ProxyAndTargetServers s;
  16124. Client cli("::1", s.target_port());
  16125. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16126. cli.set_proxy("127.0.0.1", s.proxy_port());
  16127. cli.set_no_proxy({"[::1]"});
  16128. auto res = cli.Get("/");
  16129. ASSERT_TRUE(res);
  16130. EXPECT_EQ(0, s.proxy_hits());
  16131. EXPECT_EQ(1, s.target_hits());
  16132. }
  16133. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16134. ProxyAndTargetServers s;
  16135. Client cli("fe80::1", s.target_port());
  16136. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16137. cli.set_proxy("127.0.0.1", s.proxy_port());
  16138. cli.set_no_proxy({"[fe80::]/10"});
  16139. auto res = cli.Get("/");
  16140. ASSERT_TRUE(res);
  16141. EXPECT_EQ(0, s.proxy_hits());
  16142. EXPECT_EQ(1, s.target_hits());
  16143. }
  16144. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16145. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16146. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16147. // tricks via address-family conversion.
  16148. ProxyAndTargetServers s;
  16149. Client cli("::ffff:127.0.0.1", s.target_port());
  16150. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16151. cli.set_proxy("127.0.0.1", s.proxy_port());
  16152. cli.set_no_proxy({"127.0.0.1"});
  16153. auto res = cli.Get("/");
  16154. ASSERT_TRUE(res);
  16155. EXPECT_GE(s.proxy_hits(), 1);
  16156. EXPECT_EQ(0, s.target_hits());
  16157. }
  16158. TEST(NoProxyTest, IPv4CidrMatch) {
  16159. ProxyAndTargetServers s;
  16160. Client cli("127.0.0.1", s.target_port());
  16161. cli.set_proxy("127.0.0.1", s.proxy_port());
  16162. cli.set_no_proxy({"127.0.0.0/8"});
  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, IPv4CidrNonMatch) {
  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({"10.0.0.0/8"});
  16173. auto res = cli.Get("/");
  16174. ASSERT_TRUE(res);
  16175. EXPECT_GE(s.proxy_hits(), 1);
  16176. EXPECT_EQ(0, s.target_hits());
  16177. }
  16178. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16179. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16180. // IPv4 target matches.
  16181. ProxyAndTargetServers s;
  16182. Client cli("127.0.0.1", s.target_port());
  16183. cli.set_proxy("127.0.0.1", s.proxy_port());
  16184. cli.set_no_proxy({"0.0.0.0/0"});
  16185. auto res = cli.Get("/");
  16186. ASSERT_TRUE(res);
  16187. EXPECT_EQ(0, s.proxy_hits());
  16188. EXPECT_EQ(1, s.target_hits());
  16189. }
  16190. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16191. ProxyAndTargetServers s;
  16192. Client cli("127.0.0.1", s.target_port());
  16193. cli.set_proxy("127.0.0.1", s.proxy_port());
  16194. cli.set_no_proxy({"127.0.0.1"});
  16195. auto res = cli.Get("/");
  16196. ASSERT_TRUE(res);
  16197. EXPECT_EQ(0, s.proxy_hits());
  16198. EXPECT_EQ(1, s.target_hits());
  16199. }
  16200. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16201. ProxyAndTargetServers s;
  16202. Client cli("127.0.0.1", s.target_port());
  16203. cli.set_proxy("127.0.0.1", s.proxy_port());
  16204. cli.set_no_proxy({"127.0.0.0/33"});
  16205. auto res = cli.Get("/");
  16206. ASSERT_TRUE(res);
  16207. EXPECT_GE(s.proxy_hits(), 1);
  16208. EXPECT_EQ(0, s.target_hits());
  16209. }
  16210. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16211. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16212. ProxyAndTargetServers s;
  16213. Client cli("127.0.0.1", s.target_port());
  16214. cli.set_proxy("127.0.0.1", s.proxy_port());
  16215. cli.set_no_proxy({"127.0.0.1/"});
  16216. auto res = cli.Get("/");
  16217. ASSERT_TRUE(res);
  16218. EXPECT_GE(s.proxy_hits(), 1);
  16219. EXPECT_EQ(0, s.target_hits());
  16220. }
  16221. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16222. ProxyAndTargetServers s;
  16223. auto cli = make_client("internal.corp", s);
  16224. cli->set_proxy_basic_auth("u", "p");
  16225. cli->set_no_proxy({"internal.corp"});
  16226. auto res = cli->Get("/");
  16227. ASSERT_TRUE(res);
  16228. EXPECT_EQ(1, s.target_hits());
  16229. EXPECT_EQ(0, s.proxy_hits());
  16230. EXPECT_FALSE(s.last_had_proxy_authz())
  16231. << "Proxy-Authorization must not be sent direct to the target";
  16232. }
  16233. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16234. ProxyAndTargetServers s;
  16235. auto cli = make_client("public.example", s);
  16236. cli->set_proxy_basic_auth("u", "p");
  16237. cli->set_no_proxy({"internal.corp"}); // does not match
  16238. auto res = cli->Get("/");
  16239. ASSERT_TRUE(res);
  16240. EXPECT_GE(s.proxy_hits(), 1);
  16241. EXPECT_TRUE(s.last_had_proxy_authz());
  16242. }
  16243. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16244. ProxyAndTargetServers s;
  16245. auto cli = make_client("anything.test", s);
  16246. auto res = cli->Get("/");
  16247. ASSERT_TRUE(res);
  16248. EXPECT_GE(s.proxy_hits(), 1);
  16249. EXPECT_EQ(0, s.target_hits());
  16250. }
  16251. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16252. ProxyAndTargetServers s;
  16253. auto cli = make_client("example.com", s);
  16254. cli->set_no_proxy({"example.com:8080"});
  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, EmptyAndWhitespaceEntriesDropped) {
  16261. ProxyAndTargetServers s;
  16262. auto cli = make_client("anything.test", s);
  16263. cli->set_no_proxy({"", " ", "\t"});
  16264. auto res = cli->Get("/");
  16265. ASSERT_TRUE(res);
  16266. EXPECT_GE(s.proxy_hits(), 1);
  16267. EXPECT_EQ(0, s.target_hits());
  16268. }
  16269. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16270. // An entry with leading/trailing whitespace must still match — env-style
  16271. // values are commonly pasted with stray spaces and an implementation
  16272. // that feeds the raw token directly to inet_pton would fail to match
  16273. // valid CIDRs because of the spaces.
  16274. ProxyAndTargetServers s;
  16275. Client cli("127.0.0.1", s.target_port());
  16276. cli.set_proxy("127.0.0.1", s.proxy_port());
  16277. cli.set_no_proxy({" 127.0.0.0/8 "});
  16278. auto res = cli.Get("/");
  16279. ASSERT_TRUE(res);
  16280. EXPECT_EQ(0, s.proxy_hits());
  16281. EXPECT_EQ(1, s.target_hits());
  16282. }
  16283. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16284. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16285. // go direct and must NOT carry Proxy-Authorization.
  16286. std::atomic<int> proxy_hits{0};
  16287. std::atomic<int> target_hits{0};
  16288. std::atomic<bool> target_saw_authz{false};
  16289. no_proxy_test::ScopedServer proxy_mock, target;
  16290. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16291. proxy_hits++;
  16292. res.status = 302;
  16293. res.set_header("Location", "http://127.0.0.1:" +
  16294. std::to_string(target.port()) + "/landed");
  16295. });
  16296. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16297. target_hits++;
  16298. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16299. res.set_content("direct", "text/plain");
  16300. });
  16301. proxy_mock.listen();
  16302. target.listen();
  16303. Client cli("public.example", target.port());
  16304. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16305. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16306. cli.set_proxy_basic_auth("u", "p");
  16307. cli.set_no_proxy({"127.0.0.1"});
  16308. cli.set_follow_location(true);
  16309. auto res = cli.Get("/redir");
  16310. ASSERT_TRUE(res);
  16311. EXPECT_GE(proxy_hits.load(), 1);
  16312. EXPECT_GE(target_hits.load(), 1);
  16313. EXPECT_FALSE(target_saw_authz.load());
  16314. }
  16315. #ifdef CPPHTTPLIB_SSL_ENABLED
  16316. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16317. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16318. // proxy creds would be sent to the (possibly hostile) origin.
  16319. std::atomic<int> target_hits{0};
  16320. std::atomic<bool> target_saw_proxy_authz{false};
  16321. no_proxy_test::ScopedServer target;
  16322. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16323. target_hits++;
  16324. if (req.has_header("Proxy-Authorization")) {
  16325. target_saw_proxy_authz = true;
  16326. }
  16327. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16328. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16329. "nonce=\"abc\", algorithm=MD5");
  16330. });
  16331. target.listen();
  16332. // The proxy address is set to the target's port: the bypass MUST kick in;
  16333. // if it doesn't, the test still routes "via proxy" to the same server and
  16334. // the Proxy-Authorization assertion below catches the leak.
  16335. Client cli("evil.example", target.port());
  16336. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16337. cli.set_proxy("127.0.0.1", target.port());
  16338. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16339. cli.set_no_proxy({"evil.example"});
  16340. auto res = cli.Get("/x");
  16341. ASSERT_TRUE(res);
  16342. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16343. EXPECT_EQ(1, target_hits.load());
  16344. EXPECT_FALSE(target_saw_proxy_authz.load());
  16345. }
  16346. #endif
  16347. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16348. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16349. std::atomic<int> proxy_hits{0};
  16350. std::atomic<int> bypass_hits{0};
  16351. std::atomic<bool> proxy_saw_c_url{false};
  16352. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16353. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16354. proxy_hits++;
  16355. if (req.path.find("/start") != std::string::npos) {
  16356. res.status = 302;
  16357. res.set_header("Location", "http://127.0.0.1:" +
  16358. std::to_string(bypass_server.port()) +
  16359. "/middle");
  16360. return;
  16361. }
  16362. if (req.path.find("/end") != std::string::npos) {
  16363. proxy_saw_c_url = true;
  16364. res.set_content("c-via-proxy", "text/plain");
  16365. return;
  16366. }
  16367. res.set_content("unexpected", "text/plain");
  16368. });
  16369. // public.example's "advertised" port is arbitrary (the request never lands
  16370. // there — it goes through the proxy), but use a dynamic value to stay
  16371. // friendly with sharded parallel runs.
  16372. int public_port = bypass_server.port();
  16373. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16374. bypass_hits++;
  16375. res.status = 302;
  16376. res.set_header("Location", "http://public.example:" +
  16377. std::to_string(public_port) + "/end");
  16378. });
  16379. proxy_mock.listen();
  16380. bypass_server.listen();
  16381. Client cli("public.example", public_port);
  16382. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16383. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16384. cli.set_no_proxy({"127.0.0.1"});
  16385. cli.set_follow_location(true);
  16386. auto res = cli.Get("/start");
  16387. ASSERT_TRUE(res);
  16388. EXPECT_EQ(StatusCode::OK_200, res->status);
  16389. EXPECT_EQ("c-via-proxy", res->body);
  16390. EXPECT_GE(proxy_hits.load(), 2);
  16391. EXPECT_GE(bypass_hits.load(), 1);
  16392. EXPECT_TRUE(proxy_saw_c_url.load());
  16393. }
  16394. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16395. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16396. // request reconnects to the correct endpoint.
  16397. std::atomic<int> proxy_hits{0};
  16398. std::atomic<int> target_hits{0};
  16399. no_proxy_test::ScopedServer proxy_mock, target;
  16400. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16401. proxy_hits++;
  16402. res.set_content("via-proxy", "text/plain");
  16403. });
  16404. target.svr().Get(".*", [&](const Request &, Response &res) {
  16405. target_hits++;
  16406. res.set_content("direct", "text/plain");
  16407. });
  16408. proxy_mock.listen();
  16409. target.listen();
  16410. Client cli("public.example", target.port());
  16411. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16412. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16413. cli.set_keep_alive(true);
  16414. auto res1 = cli.Get("/a");
  16415. ASSERT_TRUE(res1);
  16416. EXPECT_EQ("via-proxy", res1->body);
  16417. EXPECT_EQ(1, proxy_hits.load());
  16418. EXPECT_EQ(0, target_hits.load());
  16419. cli.set_no_proxy({"public.example"});
  16420. auto res2 = cli.Get("/b");
  16421. ASSERT_TRUE(res2);
  16422. EXPECT_EQ("direct", res2->body);
  16423. EXPECT_EQ(1, proxy_hits.load());
  16424. EXPECT_EQ(1, target_hits.load());
  16425. }
  16426. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16427. namespace proxy_tunnel_test {
  16428. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16429. class ScopedSSLServer {
  16430. public:
  16431. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16432. port_ = svr_.bind_to_any_port("127.0.0.1");
  16433. }
  16434. ~ScopedSSLServer() {
  16435. svr_.stop();
  16436. if (th_.joinable()) { th_.join(); }
  16437. }
  16438. SSLServer &svr() { return svr_; }
  16439. int port() const { return port_; }
  16440. void listen() {
  16441. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16442. svr_.wait_until_ready();
  16443. }
  16444. private:
  16445. SSLServer svr_;
  16446. std::thread th_;
  16447. int port_ = 0;
  16448. };
  16449. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16450. class ScopedConnectProxy {
  16451. public:
  16452. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16453. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16454. if (listen_fd_ < 0) { return; }
  16455. int yes = 1;
  16456. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16457. sockaddr_in a{};
  16458. a.sin_family = AF_INET;
  16459. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16460. a.sin_port = 0;
  16461. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16462. return;
  16463. }
  16464. socklen_t alen = sizeof(a);
  16465. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16466. 0) {
  16467. return;
  16468. }
  16469. port_ = ntohs(a.sin_port);
  16470. if (::listen(listen_fd_, 1) != 0) { return; }
  16471. th_ = std::thread([this] { run(); });
  16472. }
  16473. ~ScopedConnectProxy() {
  16474. stop_ = true;
  16475. if (listen_fd_ >= 0) {
  16476. ::shutdown(listen_fd_, SHUT_RDWR);
  16477. ::close(listen_fd_);
  16478. }
  16479. if (th_.joinable()) { th_.join(); }
  16480. }
  16481. int port() const { return port_; }
  16482. int connect_hits() const { return connect_hits_.load(); }
  16483. private:
  16484. void run() {
  16485. while (!stop_.load()) {
  16486. fd_set rfds;
  16487. FD_ZERO(&rfds);
  16488. FD_SET(listen_fd_, &rfds);
  16489. timeval tv{0, 100 * 1000};
  16490. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16491. if (sel <= 0) { continue; }
  16492. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16493. if (client_fd < 0) { continue; }
  16494. std::string req;
  16495. char buf[2048];
  16496. while (req.find("\r\n\r\n") == std::string::npos) {
  16497. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16498. if (n <= 0) { break; }
  16499. req.append(buf, static_cast<size_t>(n));
  16500. }
  16501. if (req.compare(0, 7, "CONNECT") != 0) {
  16502. ::close(client_fd);
  16503. continue;
  16504. }
  16505. connect_hits_++;
  16506. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16507. ::send(client_fd, ok, std::strlen(ok), 0);
  16508. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16509. sockaddr_in o{};
  16510. o.sin_family = AF_INET;
  16511. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16512. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16513. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16514. 0) {
  16515. ::close(client_fd);
  16516. ::close(origin_fd);
  16517. continue;
  16518. }
  16519. auto forward = [](int from, int to) {
  16520. char b[8192];
  16521. for (;;) {
  16522. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16523. if (n <= 0) { break; }
  16524. ssize_t off = 0;
  16525. while (off < n) {
  16526. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16527. if (s <= 0) {
  16528. off = n;
  16529. break;
  16530. }
  16531. off += s;
  16532. }
  16533. }
  16534. ::shutdown(to, SHUT_WR);
  16535. };
  16536. std::thread t1([&] { forward(client_fd, origin_fd); });
  16537. std::thread t2([&] { forward(origin_fd, client_fd); });
  16538. t1.join();
  16539. t2.join();
  16540. ::close(client_fd);
  16541. ::close(origin_fd);
  16542. }
  16543. }
  16544. int forward_port_ = -1;
  16545. int listen_fd_ = -1;
  16546. int port_ = 0;
  16547. std::thread th_;
  16548. std::atomic<bool> stop_{false};
  16549. std::atomic<int> connect_hits_{0};
  16550. };
  16551. } // namespace proxy_tunnel_test
  16552. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16553. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16554. // retry; otherwise proxy creds would be sent to the origin.
  16555. std::atomic<int> origin_hits{0};
  16556. std::atomic<bool> origin_saw_proxy_authz{false};
  16557. proxy_tunnel_test::ScopedSSLServer origin;
  16558. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16559. origin_hits++;
  16560. if (req.has_header("Proxy-Authorization")) {
  16561. origin_saw_proxy_authz = true;
  16562. }
  16563. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16564. res.set_header("Proxy-Authenticate",
  16565. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16566. "algorithm=MD5");
  16567. });
  16568. origin.listen();
  16569. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16570. ASSERT_NE(0, proxy.port());
  16571. SSLClient cli(HOST, origin.port());
  16572. cli.enable_server_certificate_verification(false);
  16573. cli.set_proxy(HOST, proxy.port());
  16574. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16575. auto res = cli.Get("/x");
  16576. ASSERT_TRUE(res);
  16577. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16578. EXPECT_EQ(1, origin_hits.load());
  16579. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16580. EXPECT_EQ(1, proxy.connect_hits());
  16581. }
  16582. #endif