test.cc 607 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727
  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(SanitizeFilenameTest, VariousPatterns) {
  329. // Path traversal
  330. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  331. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  332. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  333. // Normal and edge cases
  334. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  335. EXPECT_EQ("filename.txt",
  336. httplib::sanitize_filename("/path/to/filename.txt"));
  337. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  338. EXPECT_EQ("", httplib::sanitize_filename(".."));
  339. EXPECT_EQ("", httplib::sanitize_filename(""));
  340. // Null bytes stripped
  341. EXPECT_EQ("safe.txt",
  342. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  343. // Whitespace-only rejected
  344. EXPECT_EQ("", httplib::sanitize_filename(" "));
  345. }
  346. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  347. string unescapedCharacters = "-_.!~*'()";
  348. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  349. }
  350. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  351. string reservedCharacters = ";,/?:@&=+$";
  352. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  353. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  354. }
  355. TEST(ClientQueryOrder, PreserveOrder) {
  356. // This test reproduces Issue #2259: client may reorder query parameters
  357. // when sending a GET request. The expected behavior is that the client
  358. // preserves the original query string order when the caller supplied it
  359. // as part of the path.
  360. Server svr;
  361. svr.Get("/", [&](const Request &req, Response &res) {
  362. // Echo back the raw target so the test can assert ordering
  363. res.set_content(req.target, "text/plain");
  364. });
  365. std::thread t{[&] { svr.listen(HOST, PORT); }};
  366. auto se = detail::scope_exit([&] {
  367. svr.stop();
  368. t.join();
  369. ASSERT_FALSE(svr.is_running());
  370. });
  371. svr.wait_until_ready();
  372. Client cli(HOST, PORT);
  373. ASSERT_TRUE(cli.is_valid());
  374. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  375. auto res = cli.Get(original);
  376. ASSERT_TRUE(res);
  377. // Expect the echoed target to exactly match the original path (order
  378. // preserved)
  379. EXPECT_EQ(res->body, original);
  380. }
  381. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  382. string chineseCharacters = U8("中国語");
  383. string russianCharacters = U8("дом");
  384. string brazilianCharacters = U8("óculos");
  385. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  386. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  387. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  388. "%D0%B4%D0%BE%D0%BC");
  389. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  390. }
  391. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  392. string unescapedCharacters = "-_.!~*'()";
  393. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  394. }
  395. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  396. string reservedCharacters = ";,/?:@&=+$";
  397. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  398. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  399. }
  400. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  401. string chineseCharacters = U8("中国語");
  402. string russianCharacters = U8("дом");
  403. string brazilianCharacters = U8("óculos");
  404. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  405. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  406. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  407. "%D0%B4%D0%BE%D0%BC");
  408. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  409. }
  410. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  411. // Issue #2082 use case: encoding path component with ampersand
  412. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  413. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  414. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  415. }
  416. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'()";
  418. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  419. }
  420. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  421. string reservedCharacters = ";,/?:@&=+$#";
  422. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  423. }
  424. TEST(EncodeUriTest, TestUTF8Characters) {
  425. string chineseCharacters = U8("中国語");
  426. string russianCharacters = U8("дом");
  427. string brazilianCharacters = U8("óculos");
  428. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  429. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  430. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  431. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  432. }
  433. TEST(EncodeUriTest, TestCompleteUri) {
  434. string uri =
  435. "https://example.com/path/to/resource?query=value&param=test#fragment";
  436. EXPECT_EQ(
  437. httplib::encode_uri(uri),
  438. "https://example.com/path/to/resource?query=value&param=test#fragment");
  439. }
  440. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  441. string uri =
  442. "https://example.com/path with spaces/file name.html?q=hello world";
  443. EXPECT_EQ(httplib::encode_uri(uri),
  444. "https://example.com/path%20with%20spaces/"
  445. "file%20name.html?q=hello%20world");
  446. }
  447. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  449. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  450. }
  451. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'()";
  453. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  454. }
  455. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  464. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  465. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  466. "Piri Tommy Villiers - on & on");
  467. }
  468. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  469. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  470. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  471. }
  472. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  473. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  474. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  475. }
  476. TEST(DecodeUriTest, TestUTF8Characters) {
  477. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  478. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  479. string encodedBrazilian = "%C3%B3culos";
  480. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  481. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  482. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  483. }
  484. TEST(DecodeUriTest, TestCompleteUri) {
  485. string encodedUri = "https://example.com/path%20with%20spaces/"
  486. "file%20name.html?q=hello%20world";
  487. EXPECT_EQ(
  488. httplib::decode_uri(encodedUri),
  489. "https://example.com/path with spaces/file name.html?q=hello world");
  490. }
  491. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  492. string original =
  493. "https://example.com/path with spaces/file name.html?q=hello world";
  494. string encoded = httplib::encode_uri(original);
  495. string decoded = httplib::decode_uri(encoded);
  496. EXPECT_EQ(decoded, original);
  497. }
  498. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  499. string original = "Piri Tommy Villiers - on & on";
  500. string encoded = httplib::encode_uri_component(original);
  501. string decoded = httplib::decode_uri_component(encoded);
  502. EXPECT_EQ(decoded, original);
  503. }
  504. TEST(TrimTests, TrimStringTests) {
  505. EXPECT_EQ("abc", detail::trim_copy("abc"));
  506. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  507. EXPECT_TRUE(detail::trim_copy("").empty());
  508. }
  509. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  510. // Simple case without quality values
  511. std::vector<std::string> result1;
  512. EXPECT_TRUE(detail::parse_accept_header(
  513. "text/html,application/json,text/plain", result1));
  514. EXPECT_EQ(result1.size(), 3U);
  515. EXPECT_EQ(result1[0], "text/html");
  516. EXPECT_EQ(result1[1], "application/json");
  517. EXPECT_EQ(result1[2], "text/plain");
  518. // With quality values
  519. std::vector<std::string> result2;
  520. EXPECT_TRUE(detail::parse_accept_header(
  521. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  522. EXPECT_EQ(result2.size(), 3U);
  523. EXPECT_EQ(result2[0], "application/json"); // highest q value
  524. EXPECT_EQ(result2[1], "text/html");
  525. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  526. }
  527. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  528. // Mixed with and without quality values
  529. std::vector<std::string> result;
  530. EXPECT_TRUE(detail::parse_accept_header(
  531. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  532. EXPECT_EQ(result.size(), 3U);
  533. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  534. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  535. EXPECT_EQ(result[2], "application/json"); // q=0.5
  536. }
  537. TEST(ParseAcceptHeaderTest, EdgeCases) {
  538. // Empty header
  539. std::vector<std::string> empty_result;
  540. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  541. EXPECT_TRUE(empty_result.empty());
  542. // Single type
  543. std::vector<std::string> single_result;
  544. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  545. EXPECT_EQ(single_result.size(), 1U);
  546. EXPECT_EQ(single_result[0], "application/json");
  547. // Wildcard types
  548. std::vector<std::string> wildcard_result;
  549. EXPECT_TRUE(detail::parse_accept_header(
  550. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  551. EXPECT_EQ(wildcard_result.size(), 3U);
  552. EXPECT_EQ(wildcard_result[0], "application/json");
  553. EXPECT_EQ(wildcard_result[1], "text/*");
  554. EXPECT_EQ(wildcard_result[2], "*/*");
  555. }
  556. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  557. // Common browser Accept header
  558. std::vector<std::string> browser_result;
  559. EXPECT_TRUE(
  560. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  561. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  562. browser_result));
  563. EXPECT_EQ(browser_result.size(), 6U);
  564. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  565. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  566. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  567. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  568. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  569. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  570. // API client header
  571. std::vector<std::string> api_result;
  572. EXPECT_TRUE(detail::parse_accept_header(
  573. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  574. api_result));
  575. EXPECT_EQ(api_result.size(), 3U);
  576. EXPECT_EQ(api_result[0], "application/json");
  577. EXPECT_EQ(api_result[1], "application/xml");
  578. EXPECT_EQ(api_result[2], "text/plain");
  579. }
  580. TEST(ParseAcceptHeaderTest, SpecialCases) {
  581. // Quality value with 3 decimal places
  582. std::vector<std::string> decimal_result;
  583. EXPECT_TRUE(detail::parse_accept_header(
  584. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  585. EXPECT_EQ(decimal_result.size(), 2U);
  586. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  587. EXPECT_EQ(decimal_result[1], "text/html");
  588. // Zero quality (should still be included but with lowest priority)
  589. std::vector<std::string> zero_q_result;
  590. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  591. zero_q_result));
  592. EXPECT_EQ(zero_q_result.size(), 2U);
  593. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  594. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  595. // No spaces around commas
  596. std::vector<std::string> no_space_result;
  597. EXPECT_TRUE(detail::parse_accept_header(
  598. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  599. no_space_result));
  600. EXPECT_EQ(no_space_result.size(), 3U);
  601. EXPECT_EQ(no_space_result[0], "text/html");
  602. EXPECT_EQ(no_space_result[1], "application/json");
  603. EXPECT_EQ(no_space_result[2], "text/plain");
  604. }
  605. TEST(ParseAcceptHeaderTest, InvalidCases) {
  606. std::vector<std::string> result;
  607. // Invalid quality value (> 1.0)
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  610. // Invalid quality value (< 0.0)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  613. // Invalid quality value (not a number)
  614. EXPECT_FALSE(detail::parse_accept_header(
  615. "text/html;q=invalid,application/json", result));
  616. // Empty quality value
  617. EXPECT_FALSE(
  618. detail::parse_accept_header("text/html;q=,application/json", result));
  619. // Invalid media type format (no slash and not wildcard)
  620. EXPECT_FALSE(
  621. detail::parse_accept_header("invalidtype,application/json", result));
  622. // Empty media type
  623. result.clear();
  624. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  625. // Only commas
  626. result.clear();
  627. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  628. // Valid cases should still work
  629. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "*/*");
  632. EXPECT_TRUE(detail::parse_accept_header("*", result));
  633. EXPECT_EQ(result.size(), 1U);
  634. EXPECT_EQ(result[0], "*");
  635. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  636. EXPECT_EQ(result.size(), 1U);
  637. EXPECT_EQ(result[0], "text/*");
  638. }
  639. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  640. Server svr;
  641. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  642. EXPECT_EQ(req.accept_content_types.size(), 3U);
  643. EXPECT_EQ(req.accept_content_types[0], "application/json");
  644. EXPECT_EQ(req.accept_content_types[1], "text/html");
  645. EXPECT_EQ(req.accept_content_types[2], "*/*");
  646. res.set_content("ok", "text/plain");
  647. });
  648. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  649. EXPECT_TRUE(false);
  650. res.set_content("bad request", "text/plain");
  651. });
  652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  653. auto se = detail::scope_exit([&] {
  654. svr.stop();
  655. listen_thread.join();
  656. ASSERT_FALSE(svr.is_running());
  657. });
  658. svr.wait_until_ready();
  659. Client cli("localhost", PORT);
  660. {
  661. auto res =
  662. cli.Get("/accept_ok",
  663. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(StatusCode::OK_200, res->status);
  666. }
  667. {
  668. auto res = cli.Get("/accept_bad_request",
  669. {{"Accept", "text/html;q=abc,application/json"}});
  670. ASSERT_TRUE(res);
  671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  672. }
  673. }
  674. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  675. Server svr;
  676. svr.Get("/", [](const Request & /*req*/, Response &res) {
  677. res.set_content("ok", "text/plain");
  678. });
  679. std::atomic<int> start_count{0};
  680. std::atomic<bool> running_when_called{false};
  681. svr.set_start_handler([&]() {
  682. running_when_called = svr.is_running();
  683. start_count++;
  684. });
  685. auto port = svr.bind_to_any_port(HOST);
  686. std::thread t([&]() { svr.listen_after_bind(); });
  687. auto se = detail::scope_exit([&] {
  688. svr.stop();
  689. t.join();
  690. ASSERT_FALSE(svr.is_running());
  691. });
  692. svr.wait_until_ready();
  693. // A successful request proves the accept loop is running, which the start
  694. // handler precedes; so by now the handler must have run exactly once.
  695. Client cli(HOST, port);
  696. cli.set_connection_timeout(std::chrono::seconds(5));
  697. auto res = cli.Get("/");
  698. ASSERT_TRUE(res);
  699. EXPECT_EQ(StatusCode::OK_200, res->status);
  700. EXPECT_EQ(1, start_count.load());
  701. EXPECT_TRUE(running_when_called.load());
  702. }
  703. TEST(DivideTest, DivideStringTests) {
  704. auto divide = [](const std::string &str, char d) {
  705. std::string lhs;
  706. std::string rhs;
  707. detail::divide(str, d,
  708. [&](const char *lhs_data, std::size_t lhs_size,
  709. const char *rhs_data, std::size_t rhs_size) {
  710. lhs.assign(lhs_data, lhs_size);
  711. rhs.assign(rhs_data, rhs_size);
  712. });
  713. return std::make_pair(std::move(lhs), std::move(rhs));
  714. };
  715. {
  716. const auto res = divide("", '=');
  717. EXPECT_EQ(res.first, "");
  718. EXPECT_EQ(res.second, "");
  719. }
  720. {
  721. const auto res = divide("=", '=');
  722. EXPECT_EQ(res.first, "");
  723. EXPECT_EQ(res.second, "");
  724. }
  725. {
  726. const auto res = divide(" ", '=');
  727. EXPECT_EQ(res.first, " ");
  728. EXPECT_EQ(res.second, "");
  729. }
  730. {
  731. const auto res = divide("a", '=');
  732. EXPECT_EQ(res.first, "a");
  733. EXPECT_EQ(res.second, "");
  734. }
  735. {
  736. const auto res = divide("a=", '=');
  737. EXPECT_EQ(res.first, "a");
  738. EXPECT_EQ(res.second, "");
  739. }
  740. {
  741. const auto res = divide("=b", '=');
  742. EXPECT_EQ(res.first, "");
  743. EXPECT_EQ(res.second, "b");
  744. }
  745. {
  746. const auto res = divide("a=b", '=');
  747. EXPECT_EQ(res.first, "a");
  748. EXPECT_EQ(res.second, "b");
  749. }
  750. {
  751. const auto res = divide("a=b=", '=');
  752. EXPECT_EQ(res.first, "a");
  753. EXPECT_EQ(res.second, "b=");
  754. }
  755. {
  756. const auto res = divide("a=b=c", '=');
  757. EXPECT_EQ(res.first, "a");
  758. EXPECT_EQ(res.second, "b=c");
  759. }
  760. }
  761. TEST(SplitTest, ParseQueryString) {
  762. string s = "key1=val1&key2=val2&key3=val3";
  763. Params dic;
  764. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  765. [&](const char *b, const char *e) {
  766. string key, val;
  767. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  768. if (key.empty()) {
  769. key.assign(b2, e2);
  770. } else {
  771. val.assign(b2, e2);
  772. }
  773. });
  774. dic.emplace(key, val);
  775. });
  776. EXPECT_EQ("val1", dic.find("key1")->second);
  777. EXPECT_EQ("val2", dic.find("key2")->second);
  778. EXPECT_EQ("val3", dic.find("key3")->second);
  779. }
  780. TEST(SplitTest, ParseInvalidQueryTests) {
  781. {
  782. string s = " ";
  783. Params dict;
  784. detail::parse_query_text(s, dict);
  785. EXPECT_TRUE(dict.empty());
  786. }
  787. {
  788. string s = " = =";
  789. Params dict;
  790. detail::parse_query_text(s, dict);
  791. EXPECT_TRUE(dict.empty());
  792. }
  793. }
  794. TEST(ParseQueryTest, ParseQueryString) {
  795. {
  796. std::string s = "key1=val1&key2=val2&key3=val3";
  797. Params dic;
  798. detail::parse_query_text(s, dic);
  799. EXPECT_EQ("val1", dic.find("key1")->second);
  800. EXPECT_EQ("val2", dic.find("key2")->second);
  801. EXPECT_EQ("val3", dic.find("key3")->second);
  802. }
  803. {
  804. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  805. Params dic;
  806. detail::parse_query_text(s, dic);
  807. EXPECT_EQ("", dic.find("key1")->second);
  808. EXPECT_EQ("val1", dic.find("key2")->second);
  809. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  810. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  811. }
  812. }
  813. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  814. Params dic;
  815. EXPECT_EQ(detail::params_to_query_str(dic), "");
  816. dic.emplace("key1", "val1");
  817. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  818. dic.emplace("key2", "val2");
  819. dic.emplace("key3", "val3");
  820. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  821. }
  822. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  823. string content_type = "multipart/form-data; boundary=something";
  824. string boundary;
  825. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  826. EXPECT_TRUE(ret);
  827. EXPECT_EQ(boundary, "something");
  828. }
  829. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  830. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  831. string boundary;
  832. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  833. EXPECT_TRUE(ret);
  834. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  835. }
  836. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  837. string content_type =
  838. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  839. string boundary;
  840. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  841. EXPECT_TRUE(ret);
  842. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  843. }
  844. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  845. string content_type =
  846. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  847. string boundary;
  848. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  849. EXPECT_TRUE(ret);
  850. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  851. }
  852. TEST(GetHeaderValueTest, DefaultValue) {
  853. Headers headers = {{"Dummy", "Dummy"}};
  854. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  855. EXPECT_STREQ("text/plain", val);
  856. }
  857. TEST(GetHeaderValueTest, DefaultValueInt) {
  858. Headers headers = {{"Dummy", "Dummy"}};
  859. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  860. EXPECT_EQ(100ull, val);
  861. }
  862. TEST(GetHeaderValueTest, RegularValue) {
  863. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  864. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  865. EXPECT_STREQ("text/html", val);
  866. }
  867. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  868. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  869. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  870. EXPECT_STREQ("text/html", val);
  871. }
  872. TEST(GetHeaderValueTest, SetContent) {
  873. Response res;
  874. res.set_content("html", "text/html");
  875. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  876. res.set_content("text", "text/plain");
  877. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  878. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  879. }
  880. TEST(GetHeaderValueTest, RegularValueInt) {
  881. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  882. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  883. EXPECT_EQ(100ull, val);
  884. }
  885. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  886. Headers headers = {{"Content-Length", "x"}};
  887. auto is_invalid_value = false;
  888. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  889. is_invalid_value);
  890. EXPECT_EQ(0ull, val);
  891. EXPECT_TRUE(is_invalid_value);
  892. }
  893. TEST(GetHeaderValueTest, Range) {
  894. {
  895. Headers headers = {make_range_header({{1, -1}})};
  896. auto val = detail::get_header_value(headers, "Range", 0, 0);
  897. EXPECT_STREQ("bytes=1-", val);
  898. }
  899. {
  900. Headers headers = {make_range_header({{-1, 1}})};
  901. auto val = detail::get_header_value(headers, "Range", 0, 0);
  902. EXPECT_STREQ("bytes=-1", val);
  903. }
  904. {
  905. Headers headers = {make_range_header({{1, 10}})};
  906. auto val = detail::get_header_value(headers, "Range", 0, 0);
  907. EXPECT_STREQ("bytes=1-10", val);
  908. }
  909. {
  910. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  911. auto val = detail::get_header_value(headers, "Range", 0, 0);
  912. EXPECT_STREQ("bytes=1-10, 100-", val);
  913. }
  914. {
  915. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  916. auto val = detail::get_header_value(headers, "Range", 0, 0);
  917. EXPECT_STREQ("bytes=1-10, 100-200", val);
  918. }
  919. {
  920. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  921. auto val = detail::get_header_value(headers, "Range", 0, 0);
  922. EXPECT_STREQ("bytes=0-0, -1", val);
  923. }
  924. }
  925. TEST(ParseHeaderValueTest, Range) {
  926. {
  927. Ranges ranges;
  928. auto ret = detail::parse_range_header("bytes=1-", ranges);
  929. EXPECT_TRUE(ret);
  930. EXPECT_EQ(1u, ranges.size());
  931. EXPECT_EQ(1u, ranges[0].first);
  932. EXPECT_EQ(-1, ranges[0].second);
  933. }
  934. {
  935. Ranges ranges;
  936. auto ret = detail::parse_range_header("bytes=-1", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(1u, ranges.size());
  939. EXPECT_EQ(-1, ranges[0].first);
  940. EXPECT_EQ(1u, ranges[0].second);
  941. }
  942. {
  943. Ranges ranges;
  944. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  945. EXPECT_TRUE(ret);
  946. EXPECT_EQ(1u, ranges.size());
  947. EXPECT_EQ(1u, ranges[0].first);
  948. EXPECT_EQ(10u, ranges[0].second);
  949. }
  950. {
  951. Ranges ranges;
  952. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  953. EXPECT_FALSE(ret);
  954. }
  955. {
  956. Ranges ranges;
  957. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  958. EXPECT_TRUE(ret);
  959. EXPECT_EQ(2u, ranges.size());
  960. EXPECT_EQ(1u, ranges[0].first);
  961. EXPECT_EQ(10u, ranges[0].second);
  962. EXPECT_EQ(100u, ranges[1].first);
  963. EXPECT_EQ(-1, ranges[1].second);
  964. }
  965. {
  966. Ranges ranges;
  967. auto ret =
  968. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  969. EXPECT_TRUE(ret);
  970. EXPECT_EQ(3u, ranges.size());
  971. EXPECT_EQ(1u, ranges[0].first);
  972. EXPECT_EQ(10u, ranges[0].second);
  973. EXPECT_EQ(100u, ranges[1].first);
  974. EXPECT_EQ(200u, ranges[1].second);
  975. EXPECT_EQ(300u, ranges[2].first);
  976. EXPECT_EQ(400u, ranges[2].second);
  977. }
  978. {
  979. Ranges ranges;
  980. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  991. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  992. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  993. EXPECT_TRUE(ranges.empty());
  994. }
  995. }
  996. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  997. Request req;
  998. req.set_header("Accept-Encoding", "gzip");
  999. Response res;
  1000. res.set_header("Content-Type", "text/plain");
  1001. auto ret = detail::encoding_type(req, res);
  1002. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1003. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1004. #else
  1005. EXPECT_TRUE(ret == detail::EncodingType::None);
  1006. #endif
  1007. }
  1008. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1009. Request req;
  1010. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1011. Response res;
  1012. res.set_header("Content-Type", "text/plain");
  1013. auto ret = detail::encoding_type(req, res);
  1014. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1016. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1018. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1019. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1020. #else
  1021. EXPECT_TRUE(ret == detail::EncodingType::None);
  1022. #endif
  1023. }
  1024. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1025. Request req;
  1026. req.set_header("Accept-Encoding",
  1027. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1028. Response res;
  1029. res.set_header("Content-Type", "text/plain");
  1030. auto ret = detail::encoding_type(req, res);
  1031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1037. #else
  1038. EXPECT_TRUE(ret == detail::EncodingType::None);
  1039. #endif
  1040. }
  1041. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1042. // All supported encodings rejected with q=0 should return None
  1043. Request req;
  1044. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1045. Response res;
  1046. res.set_header("Content-Type", "text/plain");
  1047. auto ret = detail::encoding_type(req, res);
  1048. EXPECT_TRUE(ret == detail::EncodingType::None);
  1049. }
  1050. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1051. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1052. Request req;
  1053. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1054. Response res;
  1055. res.set_header("Content-Type", "text/plain");
  1056. auto ret = detail::encoding_type(req, res);
  1057. EXPECT_TRUE(ret == detail::EncodingType::None);
  1058. }
  1059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1061. Request req;
  1062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1063. Response res;
  1064. res.set_header("Content-Type", "text/plain");
  1065. auto ret = detail::encoding_type(req, res);
  1066. EXPECT_TRUE(ret == detail::EncodingType::None);
  1067. }
  1068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1069. // RFC 7231: Accept-Encoding values are case-insensitive
  1070. Request req;
  1071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1072. Response res;
  1073. res.set_header("Content-Type", "text/plain");
  1074. auto ret = detail::encoding_type(req, res);
  1075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1081. #else
  1082. EXPECT_TRUE(ret == detail::EncodingType::None);
  1083. #endif
  1084. }
  1085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1086. // q value should determine priority, not hardcoded order
  1087. Request req;
  1088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1089. Response res;
  1090. res.set_header("Content-Type", "text/plain");
  1091. auto ret = detail::encoding_type(req, res);
  1092. // gzip has highest q=1.0, so it should be selected even though
  1093. // br and zstd are also supported
  1094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1100. #else
  1101. EXPECT_TRUE(ret == detail::EncodingType::None);
  1102. #endif
  1103. }
  1104. TEST(BufferStreamTest, read) {
  1105. detail::BufferStream strm1;
  1106. Stream &strm = strm1;
  1107. EXPECT_EQ(5, strm.write("hello"));
  1108. char buf[512];
  1109. EXPECT_EQ(2, strm.read(buf, 2));
  1110. EXPECT_EQ('h', buf[0]);
  1111. EXPECT_EQ('e', buf[1]);
  1112. EXPECT_EQ(2, strm.read(buf, 2));
  1113. EXPECT_EQ('l', buf[0]);
  1114. EXPECT_EQ('l', buf[1]);
  1115. EXPECT_EQ(1, strm.read(buf, 1));
  1116. EXPECT_EQ('o', buf[0]);
  1117. EXPECT_EQ(0, strm.read(buf, 1));
  1118. }
  1119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1120. auto host = "www.httpwatch.com";
  1121. auto ip = hosted_at(host);
  1122. EXPECT_EQ("23.96.13.243", ip);
  1123. std::vector<std::string> addrs;
  1124. hosted_at(host, addrs);
  1125. EXPECT_EQ(1u, addrs.size());
  1126. }
  1127. #if 0 // It depends on each test environment...
  1128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1129. auto host = "www.youtube.com";
  1130. std::vector<std::string> addrs;
  1131. hosted_at(host, addrs);
  1132. EXPECT_EQ(20u, addrs.size());
  1133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1134. EXPECT_TRUE(it != addrs.end());
  1135. }
  1136. #endif
  1137. class ChunkedEncodingTest : public ::testing::Test {
  1138. protected:
  1139. ChunkedEncodingTest()
  1140. : cli_(HOST, PORT)
  1141. #ifdef CPPHTTPLIB_SSL_ENABLED
  1142. ,
  1143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1144. #endif
  1145. {
  1146. cli_.set_connection_timeout(2);
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. cli_.enable_server_certificate_verification(false);
  1149. #endif
  1150. }
  1151. virtual void SetUp() {
  1152. read_file("./image.jpg", image_data_);
  1153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1154. res.set_content("Hello World!", "text/plain");
  1155. });
  1156. svr_.Get(
  1157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1158. res.set_chunked_content_provider(
  1159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1160. size_t remaining = image_data_.size() - offset;
  1161. if (remaining == 0) {
  1162. sink.done();
  1163. } else {
  1164. constexpr size_t CHUNK_SIZE = 1024;
  1165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1166. sink.write(&image_data_[offset], send_size);
  1167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1168. }
  1169. return true;
  1170. });
  1171. });
  1172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1173. svr_.wait_until_ready();
  1174. }
  1175. virtual void TearDown() {
  1176. svr_.stop();
  1177. if (!request_threads_.empty()) {
  1178. std::this_thread::sleep_for(std::chrono::seconds(1));
  1179. for (auto &t : request_threads_) {
  1180. t.join();
  1181. }
  1182. }
  1183. t_.join();
  1184. }
  1185. #ifdef CPPHTTPLIB_SSL_ENABLED
  1186. SSLClient cli_;
  1187. SSLServer svr_;
  1188. #else
  1189. Client cli_;
  1190. Server svr_;
  1191. #endif
  1192. thread t_;
  1193. std::vector<thread> request_threads_;
  1194. std::string image_data_;
  1195. };
  1196. TEST_F(ChunkedEncodingTest, NormalGet) {
  1197. auto res = cli_.Get("/chunked");
  1198. ASSERT_TRUE(res);
  1199. std::string out;
  1200. read_file("./image.jpg", out);
  1201. EXPECT_EQ(StatusCode::OK_200, res->status);
  1202. EXPECT_EQ(out, res->body);
  1203. }
  1204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1205. std::string body;
  1206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1207. body.append(data, data_length);
  1208. return true;
  1209. });
  1210. ASSERT_TRUE(res);
  1211. std::string out;
  1212. read_file("./image.jpg", out);
  1213. EXPECT_EQ(StatusCode::OK_200, res->status);
  1214. EXPECT_EQ(out, body);
  1215. }
  1216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1217. std::string body;
  1218. auto res = cli_.Get(
  1219. "/chunked",
  1220. [&](const Response &response) {
  1221. EXPECT_EQ(StatusCode::OK_200, response.status);
  1222. return true;
  1223. },
  1224. [&](const char *data, size_t data_length) {
  1225. body.append(data, data_length);
  1226. return true;
  1227. });
  1228. ASSERT_TRUE(res);
  1229. std::string out;
  1230. read_file("./image.jpg", out);
  1231. EXPECT_EQ(StatusCode::OK_200, res->status);
  1232. EXPECT_EQ(out, body);
  1233. }
  1234. TEST(RangeTest, FromHTTPBin_Online) {
  1235. auto host = "httpbingo.org";
  1236. auto path = std::string{"/range/32"};
  1237. #ifdef CPPHTTPLIB_SSL_ENABLED
  1238. auto port = 443;
  1239. SSLClient cli(host, port);
  1240. #else
  1241. auto port = 80;
  1242. Client cli(host, port);
  1243. #endif
  1244. cli.set_connection_timeout(5);
  1245. {
  1246. auto res = cli.Get(path);
  1247. ASSERT_TRUE(res);
  1248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1249. EXPECT_EQ(StatusCode::OK_200, res->status);
  1250. }
  1251. {
  1252. Headers headers = {make_range_header({{1, -1}})};
  1253. auto res = cli.Get(path, headers);
  1254. ASSERT_TRUE(res);
  1255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1257. }
  1258. {
  1259. Headers headers = {make_range_header({{1, 10}})};
  1260. auto res = cli.Get(path, headers);
  1261. ASSERT_TRUE(res);
  1262. EXPECT_EQ("bcdefghijk", res->body);
  1263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1264. }
  1265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1266. // entire resource, while the original httpbin returned 200. Both are
  1267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1268. {
  1269. Headers headers = {make_range_header({{0, 31}})};
  1270. auto res = cli.Get(path, headers);
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1274. res->status == StatusCode::PartialContent_206);
  1275. }
  1276. {
  1277. Headers headers = {make_range_header({{0, -1}})};
  1278. auto res = cli.Get(path, headers);
  1279. ASSERT_TRUE(res);
  1280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1282. res->status == StatusCode::PartialContent_206);
  1283. }
  1284. // go-httpbin returns 206 with clamped range for over-range requests,
  1285. // while the original httpbin returned 416. Both behaviors are observed
  1286. // in real servers, so we only verify the request succeeds.
  1287. {
  1288. Headers headers = {make_range_header({{0, 32}})};
  1289. auto res = cli.Get(path, headers);
  1290. ASSERT_TRUE(res);
  1291. }
  1292. }
  1293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1294. auto host = "unresolvableaddress.local";
  1295. auto path = std::string{"/"};
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. cli.set_connection_timeout(1);
  1304. {
  1305. auto res = cli.Get(path);
  1306. ASSERT_FALSE(res);
  1307. }
  1308. std::this_thread::sleep_for(std::chrono::seconds(8));
  1309. }
  1310. #if defined(__linux__) && defined(__GLIBC__) && \
  1311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1312. // Forward declaration: in split builds split.py strips `inline` and moves the
  1313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1315. // against the symbol in both header-only and split builds.
  1316. namespace httplib {
  1317. namespace detail {
  1318. int getaddrinfo_with_timeout(const char *node, const char *service,
  1319. const struct addrinfo *hints,
  1320. struct addrinfo **res, time_t timeout_sec);
  1321. } // namespace detail
  1322. } // namespace httplib
  1323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1324. //
  1325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1327. // gai_suspend() call hits the connection timeout the function calls
  1328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1330. // still alive and still references the now-destroyed stack frame.
  1331. //
  1332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1335. // and runs them in a container.
  1336. namespace {
  1337. bool should_run_issue_2431_tests() {
  1338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1339. return v && *v && std::string(v) != "0";
  1340. }
  1341. std::string unique_unresolvable_host(int n) {
  1342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1343. // glibc still asks the configured nameserver — which is exactly the path
  1344. // we want to exercise. A unique label per call avoids the resolver cache.
  1345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1347. std::to_string(n) + ".invalid";
  1348. }
  1349. } // namespace
  1350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1351. if (!should_run_issue_2431_tests()) {
  1352. GTEST_SKIP()
  1353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1354. }
  1355. for (int i = 0; i < 8; ++i) {
  1356. struct addrinfo hints;
  1357. memset(&hints, 0, sizeof(hints));
  1358. hints.ai_family = AF_UNSPEC;
  1359. hints.ai_socktype = SOCK_STREAM;
  1360. auto host = unique_unresolvable_host(i);
  1361. struct addrinfo *result = nullptr;
  1362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1363. &result, /*timeout_sec=*/1);
  1364. if (rc == 0 && result) { freeaddrinfo(result); }
  1365. }
  1366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1367. // stack region they still believe holds their gaicb.
  1368. std::this_thread::sleep_for(std::chrono::seconds(3));
  1369. }
  1370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1371. if (!should_run_issue_2431_tests()) {
  1372. GTEST_SKIP()
  1373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1374. }
  1375. std::atomic<bool> stop{false};
  1376. std::vector<std::thread> threads;
  1377. for (int t = 0; t < 8; ++t) {
  1378. threads.emplace_back([t, &stop] {
  1379. int i = 0;
  1380. while (!stop.load(std::memory_order_relaxed)) {
  1381. struct addrinfo hints;
  1382. memset(&hints, 0, sizeof(hints));
  1383. hints.ai_family = AF_UNSPEC;
  1384. hints.ai_socktype = SOCK_STREAM;
  1385. auto host = unique_unresolvable_host(t * 100000 + i++);
  1386. struct addrinfo *result = nullptr;
  1387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1388. &result, /*timeout_sec=*/1);
  1389. if (rc == 0 && result) { freeaddrinfo(result); }
  1390. }
  1391. });
  1392. }
  1393. std::this_thread::sleep_for(std::chrono::seconds(8));
  1394. stop.store(true, std::memory_order_relaxed);
  1395. for (auto &th : threads) {
  1396. th.join();
  1397. }
  1398. std::this_thread::sleep_for(std::chrono::seconds(3));
  1399. }
  1400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1401. if (!should_run_issue_2431_tests()) {
  1402. GTEST_SKIP()
  1403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1404. }
  1405. std::atomic<bool> stop{false};
  1406. std::vector<std::thread> threads;
  1407. for (int t = 0; t < 8; ++t) {
  1408. threads.emplace_back([t, &stop] {
  1409. int i = 0;
  1410. while (!stop.load(std::memory_order_relaxed)) {
  1411. auto host = unique_unresolvable_host(t * 100000 + i++);
  1412. Client cli(host, 80);
  1413. cli.set_connection_timeout(1, 0);
  1414. cli.set_read_timeout(1, 0);
  1415. cli.set_write_timeout(1, 0);
  1416. (void)cli.Get("/");
  1417. }
  1418. });
  1419. }
  1420. std::this_thread::sleep_for(std::chrono::seconds(8));
  1421. stop.store(true, std::memory_order_relaxed);
  1422. for (auto &th : threads) {
  1423. th.join();
  1424. }
  1425. std::this_thread::sleep_for(std::chrono::seconds(3));
  1426. }
  1427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1428. TEST(ConnectionErrorTest, InvalidHost) {
  1429. auto host = "-abcde.com";
  1430. #ifdef CPPHTTPLIB_SSL_ENABLED
  1431. auto port = 443;
  1432. SSLClient cli(host, port);
  1433. #else
  1434. auto port = 80;
  1435. Client cli(host, port);
  1436. #endif
  1437. cli.set_connection_timeout(std::chrono::seconds(2));
  1438. auto res = cli.Get("/");
  1439. ASSERT_TRUE(!res);
  1440. EXPECT_EQ(Error::Connection, res.error());
  1441. }
  1442. TEST(ConnectionErrorTest, InvalidHost2) {
  1443. auto host = "httpcan.org/";
  1444. #ifdef CPPHTTPLIB_SSL_ENABLED
  1445. SSLClient cli(host);
  1446. #else
  1447. Client cli(host);
  1448. #endif
  1449. cli.set_connection_timeout(std::chrono::seconds(2));
  1450. auto res = cli.Get("/");
  1451. ASSERT_TRUE(!res);
  1452. EXPECT_EQ(Error::Connection, res.error());
  1453. }
  1454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1455. auto host = "httpcan.org/";
  1456. #ifdef CPPHTTPLIB_SSL_ENABLED
  1457. SSLClient cli(host);
  1458. #else
  1459. Client cli(host);
  1460. #endif
  1461. cli.set_connection_timeout(std::chrono::seconds(2));
  1462. auto res = cli.Get("/");
  1463. ASSERT_TRUE(!res);
  1464. stringstream s;
  1465. s << "error code: " << res.error();
  1466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1467. }
  1468. TEST(ConnectionErrorTest, InvalidPort) {
  1469. auto host = "localhost";
  1470. auto port = 44380;
  1471. #ifdef CPPHTTPLIB_SSL_ENABLED
  1472. SSLClient cli(host, port);
  1473. #else
  1474. Client cli(host, port);
  1475. #endif
  1476. cli.set_connection_timeout(std::chrono::seconds(2));
  1477. auto res = cli.Get("/");
  1478. ASSERT_TRUE(!res);
  1479. EXPECT_TRUE(Error::Connection == res.error() ||
  1480. Error::ConnectionTimeout == res.error());
  1481. }
  1482. TEST(ConnectionErrorTest, Timeout_Online) {
  1483. auto host = "google.com";
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 44380;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 8080;
  1489. Client cli(host, port);
  1490. #endif
  1491. cli.set_connection_timeout(std::chrono::seconds(2));
  1492. // only probe one address type so that the error reason
  1493. // correlates to the timed-out IPv4, not the unsupported
  1494. // IPv6 connection attempt
  1495. cli.set_address_family(AF_INET);
  1496. auto res = cli.Get("/");
  1497. ASSERT_TRUE(!res);
  1498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1499. }
  1500. TEST(CancelTest, NoCancel_Online) {
  1501. auto host = "httpbingo.org";
  1502. auto path = std::string{"/range/32"};
  1503. #ifdef CPPHTTPLIB_SSL_ENABLED
  1504. auto port = 443;
  1505. SSLClient cli(host, port);
  1506. #else
  1507. auto port = 80;
  1508. Client cli(host, port);
  1509. #endif
  1510. cli.set_connection_timeout(std::chrono::seconds(5));
  1511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1512. ASSERT_TRUE(res);
  1513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1514. EXPECT_EQ(StatusCode::OK_200, res->status);
  1515. }
  1516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1517. // Use /bytes with a large payload so that the DownloadProgress callback
  1518. // (which only fires for Content-Length responses) is invoked before the
  1519. // entire body is received, giving cancellation a chance to fire.
  1520. auto host = "httpbingo.org";
  1521. auto path = std::string{"/bytes/524288"};
  1522. #ifdef CPPHTTPLIB_SSL_ENABLED
  1523. auto port = 443;
  1524. SSLClient cli(host, port);
  1525. #else
  1526. auto port = 80;
  1527. Client cli(host, port);
  1528. #endif
  1529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1530. cli.set_connection_timeout(std::chrono::seconds(5));
  1531. ASSERT_TRUE(!res);
  1532. EXPECT_EQ(Error::Canceled, res.error());
  1533. }
  1534. TEST(CancelTest, WithCancelLargePayload_Online) {
  1535. auto host = "httpbingo.org";
  1536. auto path = std::string{"/bytes/524288"};
  1537. #ifdef CPPHTTPLIB_SSL_ENABLED
  1538. auto port = 443;
  1539. SSLClient cli(host, port);
  1540. #else
  1541. auto port = 80;
  1542. Client cli(host, port);
  1543. #endif
  1544. cli.set_connection_timeout(std::chrono::seconds(5));
  1545. uint32_t count = 0;
  1546. auto res =
  1547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1548. ASSERT_TRUE(!res);
  1549. EXPECT_EQ(Error::Canceled, res.error());
  1550. }
  1551. TEST(CancelTest, NoCancelPost) {
  1552. Server svr;
  1553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1554. res.set_content("Hello World!", "text/plain");
  1555. });
  1556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1557. auto se = detail::scope_exit([&] {
  1558. svr.stop();
  1559. thread.join();
  1560. ASSERT_FALSE(svr.is_running());
  1561. });
  1562. svr.wait_until_ready();
  1563. Client cli(HOST, PORT);
  1564. cli.set_connection_timeout(std::chrono::seconds(5));
  1565. auto res =
  1566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1567. "application/json", [](uint64_t, uint64_t) { return true; });
  1568. ASSERT_TRUE(res);
  1569. EXPECT_EQ("Hello World!", res->body);
  1570. EXPECT_EQ(StatusCode::OK_200, res->status);
  1571. }
  1572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1573. Server svr;
  1574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1575. res.set_content("Hello World!", "text/plain");
  1576. });
  1577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1578. auto se = detail::scope_exit([&] {
  1579. svr.stop();
  1580. thread.join();
  1581. ASSERT_FALSE(svr.is_running());
  1582. });
  1583. svr.wait_until_ready();
  1584. Client cli(HOST, PORT);
  1585. cli.set_connection_timeout(std::chrono::seconds(5));
  1586. auto res =
  1587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1588. "application/json", [](uint64_t, uint64_t) { return false; });
  1589. ASSERT_TRUE(!res);
  1590. EXPECT_EQ(Error::Canceled, res.error());
  1591. }
  1592. TEST(CancelTest, WithCancelLargePayloadPost) {
  1593. Server svr;
  1594. svr.set_payload_max_length(200 * 1024 * 1024);
  1595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1596. res.set_content(LARGE_DATA, "text/plain");
  1597. });
  1598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1599. auto se = detail::scope_exit([&] {
  1600. svr.stop();
  1601. thread.join();
  1602. ASSERT_FALSE(svr.is_running());
  1603. });
  1604. svr.wait_until_ready();
  1605. Client cli(HOST, PORT);
  1606. cli.set_payload_max_length(200 * 1024 * 1024);
  1607. cli.set_connection_timeout(std::chrono::seconds(5));
  1608. auto res =
  1609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1610. "application/json", [](uint64_t, uint64_t) { return false; });
  1611. ASSERT_TRUE(!res);
  1612. EXPECT_EQ(Error::Canceled, res.error());
  1613. }
  1614. TEST(CancelTest, NoCancelPut) {
  1615. Server svr;
  1616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1617. res.set_content("Hello World!", "text/plain");
  1618. });
  1619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1620. auto se = detail::scope_exit([&] {
  1621. svr.stop();
  1622. thread.join();
  1623. ASSERT_FALSE(svr.is_running());
  1624. });
  1625. svr.wait_until_ready();
  1626. Client cli(HOST, PORT);
  1627. cli.set_connection_timeout(std::chrono::seconds(5));
  1628. auto res =
  1629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1630. "application/json", [](uint64_t, uint64_t) { return true; });
  1631. ASSERT_TRUE(res);
  1632. EXPECT_EQ("Hello World!", res->body);
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. }
  1635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1636. Server svr;
  1637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1638. res.set_content("Hello World!", "text/plain");
  1639. });
  1640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1641. auto se = detail::scope_exit([&] {
  1642. svr.stop();
  1643. thread.join();
  1644. ASSERT_FALSE(svr.is_running());
  1645. });
  1646. svr.wait_until_ready();
  1647. Client cli(HOST, PORT);
  1648. cli.set_connection_timeout(std::chrono::seconds(5));
  1649. auto res =
  1650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1651. "application/json", [](uint64_t, uint64_t) { return false; });
  1652. ASSERT_TRUE(!res);
  1653. EXPECT_EQ(Error::Canceled, res.error());
  1654. }
  1655. TEST(CancelTest, WithCancelLargePayloadPut) {
  1656. Server svr;
  1657. svr.set_payload_max_length(200 * 1024 * 1024);
  1658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1659. res.set_content(LARGE_DATA, "text/plain");
  1660. });
  1661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1662. auto se = detail::scope_exit([&] {
  1663. svr.stop();
  1664. thread.join();
  1665. ASSERT_FALSE(svr.is_running());
  1666. });
  1667. svr.wait_until_ready();
  1668. Client cli(HOST, PORT);
  1669. cli.set_payload_max_length(200 * 1024 * 1024);
  1670. cli.set_connection_timeout(std::chrono::seconds(5));
  1671. auto res =
  1672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1673. "application/json", [](uint64_t, uint64_t) { return false; });
  1674. ASSERT_TRUE(!res);
  1675. EXPECT_EQ(Error::Canceled, res.error());
  1676. }
  1677. TEST(CancelTest, NoCancelPatch) {
  1678. Server svr;
  1679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1680. res.set_content("Hello World!", "text/plain");
  1681. });
  1682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1683. auto se = detail::scope_exit([&] {
  1684. svr.stop();
  1685. thread.join();
  1686. ASSERT_FALSE(svr.is_running());
  1687. });
  1688. svr.wait_until_ready();
  1689. Client cli(HOST, PORT);
  1690. cli.set_connection_timeout(std::chrono::seconds(5));
  1691. auto res =
  1692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1693. "application/json", [](uint64_t, uint64_t) { return true; });
  1694. ASSERT_TRUE(res);
  1695. EXPECT_EQ("Hello World!", res->body);
  1696. EXPECT_EQ(StatusCode::OK_200, res->status);
  1697. }
  1698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1699. Server svr;
  1700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1701. res.set_content("Hello World!", "text/plain");
  1702. });
  1703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1704. auto se = detail::scope_exit([&] {
  1705. svr.stop();
  1706. thread.join();
  1707. ASSERT_FALSE(svr.is_running());
  1708. });
  1709. svr.wait_until_ready();
  1710. Client cli(HOST, PORT);
  1711. cli.set_connection_timeout(std::chrono::seconds(5));
  1712. auto res =
  1713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1714. "application/json", [](uint64_t, uint64_t) { return false; });
  1715. ASSERT_TRUE(!res);
  1716. EXPECT_EQ(Error::Canceled, res.error());
  1717. }
  1718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1719. Server svr;
  1720. svr.set_payload_max_length(200 * 1024 * 1024);
  1721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1722. res.set_content(LARGE_DATA, "text/plain");
  1723. });
  1724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1725. auto se = detail::scope_exit([&] {
  1726. svr.stop();
  1727. thread.join();
  1728. ASSERT_FALSE(svr.is_running());
  1729. });
  1730. svr.wait_until_ready();
  1731. Client cli(HOST, PORT);
  1732. cli.set_payload_max_length(200 * 1024 * 1024);
  1733. cli.set_connection_timeout(std::chrono::seconds(5));
  1734. auto res =
  1735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1736. "application/json", [](uint64_t, uint64_t) { return false; });
  1737. ASSERT_TRUE(!res);
  1738. EXPECT_EQ(Error::Canceled, res.error());
  1739. }
  1740. TEST(CancelTest, NoCancelDelete) {
  1741. Server svr;
  1742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1743. res.set_content("Hello World!", "text/plain");
  1744. });
  1745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1746. auto se = detail::scope_exit([&] {
  1747. svr.stop();
  1748. thread.join();
  1749. ASSERT_FALSE(svr.is_running());
  1750. });
  1751. svr.wait_until_ready();
  1752. Client cli(HOST, PORT);
  1753. cli.set_connection_timeout(std::chrono::seconds(5));
  1754. auto res =
  1755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1756. "application/json", [](uint64_t, uint64_t) { return true; });
  1757. ASSERT_TRUE(res);
  1758. EXPECT_EQ("Hello World!", res->body);
  1759. EXPECT_EQ(StatusCode::OK_200, res->status);
  1760. }
  1761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1762. Server svr;
  1763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1764. res.set_content("Hello World!", "text/plain");
  1765. });
  1766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1767. auto se = detail::scope_exit([&] {
  1768. svr.stop();
  1769. thread.join();
  1770. ASSERT_FALSE(svr.is_running());
  1771. });
  1772. svr.wait_until_ready();
  1773. Client cli(HOST, PORT);
  1774. cli.set_connection_timeout(std::chrono::seconds(5));
  1775. auto res =
  1776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1777. "application/json", [](uint64_t, uint64_t) { return false; });
  1778. ASSERT_TRUE(!res);
  1779. EXPECT_EQ(Error::Canceled, res.error());
  1780. }
  1781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1782. Server svr;
  1783. svr.set_payload_max_length(200 * 1024 * 1024);
  1784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1785. res.set_content(LARGE_DATA, "text/plain");
  1786. });
  1787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1788. auto se = detail::scope_exit([&] {
  1789. svr.stop();
  1790. thread.join();
  1791. ASSERT_FALSE(svr.is_running());
  1792. });
  1793. svr.wait_until_ready();
  1794. Client cli(HOST, PORT);
  1795. cli.set_payload_max_length(200 * 1024 * 1024);
  1796. cli.set_connection_timeout(std::chrono::seconds(5));
  1797. auto res =
  1798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1799. "application/json", [](uint64_t, uint64_t) { return false; });
  1800. ASSERT_TRUE(!res);
  1801. EXPECT_EQ(Error::Canceled, res.error());
  1802. }
  1803. static std::string remove_whitespace(const std::string &input) {
  1804. std::string output;
  1805. output.reserve(input.size());
  1806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1807. [](unsigned char c) { return !std::isspace(c); });
  1808. return output;
  1809. }
  1810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1811. auto host = "httpbingo.org";
  1812. auto path = std::string{"/basic-auth/hello/world"};
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. auto port = 443;
  1815. SSLClient cli(host, port);
  1816. #else
  1817. auto port = 80;
  1818. Client cli(host, port);
  1819. #endif
  1820. {
  1821. auto res = cli.Get(path);
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1824. }
  1825. {
  1826. auto res =
  1827. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1828. ASSERT_TRUE(res);
  1829. auto body = remove_whitespace(res->body);
  1830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1832. EXPECT_EQ(StatusCode::OK_200, res->status);
  1833. }
  1834. {
  1835. cli.set_basic_auth("hello", "world");
  1836. auto res = cli.Get(path);
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. {
  1844. cli.set_basic_auth("hello", "bad");
  1845. auto res = cli.Get(path);
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. {
  1850. cli.set_basic_auth("bad", "world");
  1851. auto res = cli.Get(path);
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1854. }
  1855. }
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1858. auto host = "httpbingo.org";
  1859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1860. auto paths = std::vector<std::string>{
  1861. "/digest-auth/auth/hello/world/MD5",
  1862. "/digest-auth/auth/hello/world/SHA-256",
  1863. };
  1864. auto port = 443;
  1865. SSLClient cli(host, port);
  1866. {
  1867. auto res = cli.Get(unauth_path);
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1870. }
  1871. {
  1872. cli.set_digest_auth("hello", "world");
  1873. for (const auto &path : paths) {
  1874. auto res = cli.Get(path.c_str());
  1875. ASSERT_TRUE(res);
  1876. auto body = remove_whitespace(res->body);
  1877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1879. EXPECT_EQ(StatusCode::OK_200, res->status);
  1880. }
  1881. cli.set_digest_auth("hello", "bad");
  1882. for (const auto &path : paths) {
  1883. auto res = cli.Get(path.c_str());
  1884. ASSERT_TRUE(res);
  1885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1886. }
  1887. }
  1888. }
  1889. #endif
  1890. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1891. auto host = "google.com";
  1892. auto another_host = "example.com";
  1893. auto wrong_ip = "0.0.0.0";
  1894. #ifdef CPPHTTPLIB_SSL_ENABLED
  1895. SSLClient cli(host);
  1896. #else
  1897. Client cli(host);
  1898. #endif
  1899. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1900. auto res = cli.Get("/");
  1901. ASSERT_TRUE(res);
  1902. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1903. }
  1904. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1905. auto host = "google.com";
  1906. auto wrong_ip = "0.0.0.0";
  1907. #ifdef CPPHTTPLIB_SSL_ENABLED
  1908. SSLClient cli(host);
  1909. #else
  1910. Client cli(host);
  1911. #endif
  1912. cli.set_hostname_addr_map({{host, wrong_ip}});
  1913. auto res = cli.Get("/");
  1914. ASSERT_TRUE(!res);
  1915. EXPECT_EQ(Error::Connection, res.error());
  1916. }
  1917. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1918. auto host = "httpbingo.org";
  1919. auto path = std::string{"/absolute-redirect/3"};
  1920. #ifdef CPPHTTPLIB_SSL_ENABLED
  1921. SSLClient cli(host);
  1922. #else
  1923. Client cli(host);
  1924. #endif
  1925. cli.set_follow_location(true);
  1926. auto res = cli.Get(path);
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::OK_200, res->status);
  1929. }
  1930. TEST(RedirectTest, Redirect_Online) {
  1931. auto host = "httpbingo.org";
  1932. auto path = std::string{"/redirect/3"};
  1933. #ifdef CPPHTTPLIB_SSL_ENABLED
  1934. SSLClient cli(host);
  1935. #else
  1936. Client cli(host);
  1937. #endif
  1938. cli.set_follow_location(true);
  1939. auto res = cli.Get(path);
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::OK_200, res->status);
  1942. }
  1943. TEST(RelativeRedirectTest, Redirect_Online) {
  1944. auto host = "httpbingo.org";
  1945. auto path = std::string{"/relative-redirect/3"};
  1946. #ifdef CPPHTTPLIB_SSL_ENABLED
  1947. SSLClient cli(host);
  1948. #else
  1949. Client cli(host);
  1950. #endif
  1951. cli.set_follow_location(true);
  1952. auto res = cli.Get(path);
  1953. ASSERT_TRUE(res);
  1954. EXPECT_EQ(StatusCode::OK_200, res->status);
  1955. }
  1956. TEST(TooManyRedirectTest, Redirect_Online) {
  1957. auto host = "httpbingo.org";
  1958. auto path = std::string{"/redirect/21"};
  1959. #ifdef CPPHTTPLIB_SSL_ENABLED
  1960. SSLClient cli(host);
  1961. #else
  1962. Client cli(host);
  1963. #endif
  1964. cli.set_follow_location(true);
  1965. auto res = cli.Get(path);
  1966. ASSERT_TRUE(!res);
  1967. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1968. }
  1969. #ifdef CPPHTTPLIB_SSL_ENABLED
  1970. TEST(YahooRedirectTest, Redirect_Online) {
  1971. Client cli("yahoo.com");
  1972. auto res = cli.Get("/");
  1973. ASSERT_TRUE(res);
  1974. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1975. cli.set_follow_location(true);
  1976. res = cli.Get("/");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1980. }
  1981. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1982. #define REDIR_HOST "httpbingo.org"
  1983. #define REDIR_PATH "/redirect-to"
  1984. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1985. SSLClient cli(REDIR_HOST);
  1986. cli.set_follow_location(true);
  1987. auto res =
  1988. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. }
  1992. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1993. SSLClient cli(REDIR_HOST);
  1994. cli.set_follow_location(true);
  1995. Params params;
  1996. params.emplace("url", "http://example.com");
  1997. params.emplace("status_code", "302");
  1998. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(StatusCode::OK_200, res->status);
  2001. }
  2002. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2003. SSLClient cli(REDIR_HOST);
  2004. cli.set_follow_location(true);
  2005. Params params;
  2006. params.emplace("url", "http://example.com");
  2007. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2008. ASSERT_TRUE(res);
  2009. EXPECT_EQ(StatusCode::OK_200, res->status);
  2010. }
  2011. TEST(UrlWithSpace, Redirect_Online) {
  2012. SSLClient cli("edge.forgecdn.net");
  2013. cli.set_follow_location(true);
  2014. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2015. ASSERT_TRUE(res);
  2016. EXPECT_EQ(StatusCode::OK_200, res->status);
  2017. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2018. }
  2019. #endif
  2020. #if !defined(_WIN32) && !defined(_WIN64)
  2021. TEST(ReceiveSignals, Signal) {
  2022. auto setupSignalHandlers = []() {
  2023. struct sigaction act;
  2024. sigemptyset(&act.sa_mask);
  2025. act.sa_flags = SA_SIGINFO;
  2026. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2027. switch (sig) {
  2028. case SIGINT:
  2029. default: break;
  2030. }
  2031. };
  2032. ::sigaction(SIGINT, &act, nullptr);
  2033. };
  2034. Server svr;
  2035. int port = 0;
  2036. auto thread = std::thread([&]() {
  2037. setupSignalHandlers();
  2038. port = svr.bind_to_any_port(HOST);
  2039. svr.listen_after_bind();
  2040. });
  2041. auto se = detail::scope_exit([&] {
  2042. svr.stop();
  2043. thread.join();
  2044. ASSERT_FALSE(svr.is_running());
  2045. });
  2046. svr.wait_until_ready();
  2047. ASSERT_TRUE(svr.is_running());
  2048. pthread_kill(thread.native_handle(), SIGINT);
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2050. ASSERT_TRUE(svr.is_running());
  2051. }
  2052. #endif
  2053. TEST(RedirectToDifferentPort, Redirect) {
  2054. Server svr1;
  2055. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2056. res.set_content("Hello World!", "text/plain");
  2057. });
  2058. int svr1_port = 0;
  2059. auto thread1 = std::thread([&]() {
  2060. svr1_port = svr1.bind_to_any_port(HOST);
  2061. svr1.listen_after_bind();
  2062. });
  2063. Server svr2;
  2064. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2065. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2066. });
  2067. int svr2_port = 0;
  2068. auto thread2 = std::thread([&]() {
  2069. svr2_port = svr2.bind_to_any_port(HOST);
  2070. svr2.listen_after_bind();
  2071. });
  2072. auto se = detail::scope_exit([&] {
  2073. svr2.stop();
  2074. thread2.join();
  2075. svr1.stop();
  2076. thread1.join();
  2077. ASSERT_FALSE(svr2.is_running());
  2078. ASSERT_FALSE(svr1.is_running());
  2079. });
  2080. svr1.wait_until_ready();
  2081. svr2.wait_until_ready();
  2082. Client cli("localhost", svr2_port);
  2083. cli.set_follow_location(true);
  2084. auto res = cli.Get("/2");
  2085. ASSERT_TRUE(res);
  2086. EXPECT_EQ(StatusCode::OK_200, res->status);
  2087. EXPECT_EQ("Hello World!", res->body);
  2088. }
  2089. static void
  2090. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2091. Server svr1;
  2092. std::string captured_authorization;
  2093. svr1.Get("/target", [&](const Request &req, Response &res) {
  2094. captured_authorization = req.get_header_value("Authorization");
  2095. res.set_content("OK", "text/plain");
  2096. });
  2097. int svr1_port = 0;
  2098. auto thread1 = std::thread([&]() {
  2099. svr1_port = svr1.bind_to_any_port(HOST);
  2100. svr1.listen_after_bind();
  2101. });
  2102. Server svr2;
  2103. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. res.set_redirect(
  2105. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2106. });
  2107. int svr2_port = 0;
  2108. auto thread2 = std::thread([&]() {
  2109. svr2_port = svr2.bind_to_any_port(HOST);
  2110. svr2.listen_after_bind();
  2111. });
  2112. auto se = detail::scope_exit([&] {
  2113. svr2.stop();
  2114. thread2.join();
  2115. svr1.stop();
  2116. thread1.join();
  2117. ASSERT_FALSE(svr2.is_running());
  2118. ASSERT_FALSE(svr1.is_running());
  2119. });
  2120. svr1.wait_until_ready();
  2121. svr2.wait_until_ready();
  2122. Client cli("localhost", svr2_port);
  2123. cli.set_follow_location(true);
  2124. set_auth(cli);
  2125. auto res = cli.Get("/redir");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2129. EXPECT_TRUE(captured_authorization.empty());
  2130. }
  2131. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2132. TestDoNotForwardCredentialsOnRedirect(
  2133. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2134. }
  2135. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2136. TestDoNotForwardCredentialsOnRedirect(
  2137. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2138. }
  2139. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2140. Server svr;
  2141. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2142. // Port number that overflows int — should not crash
  2143. res.set_redirect("http://localhost:99999999999999999999/target");
  2144. });
  2145. auto port = svr.bind_to_any_port(HOST);
  2146. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2147. auto se = detail::scope_exit([&] {
  2148. svr.stop();
  2149. thread.join();
  2150. ASSERT_FALSE(svr.is_running());
  2151. });
  2152. svr.wait_until_ready();
  2153. Client cli(HOST, port);
  2154. cli.set_follow_location(true);
  2155. auto res = cli.Get("/redir");
  2156. // Should fail gracefully, not crash (no valid response due to bad port)
  2157. EXPECT_FALSE(res);
  2158. }
  2159. TEST(RedirectFromPageWithContent, Redirect) {
  2160. Server svr;
  2161. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2162. res.set_content("___", "text/plain");
  2163. res.set_redirect("/2");
  2164. });
  2165. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2166. res.set_content("Hello World!", "text/plain");
  2167. });
  2168. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. th.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. {
  2176. Client cli("localhost", PORT);
  2177. cli.set_follow_location(true);
  2178. std::string body;
  2179. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2180. body.append(data, data_length);
  2181. return true;
  2182. });
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::OK_200, res->status);
  2185. EXPECT_EQ("Hello World!", body);
  2186. }
  2187. {
  2188. Client cli("localhost", PORT);
  2189. std::string body;
  2190. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2191. body.append(data, data_length);
  2192. return true;
  2193. });
  2194. ASSERT_TRUE(res);
  2195. EXPECT_EQ(StatusCode::Found_302, res->status);
  2196. EXPECT_EQ("___", body);
  2197. }
  2198. }
  2199. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2200. Server svr;
  2201. auto port_str = std::to_string(PORT);
  2202. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2203. auto expected_host = "[::1]:" + port_str;
  2204. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2205. res.set_content("___", "text/plain");
  2206. // res.set_redirect("/2");
  2207. res.set_redirect(redirect_url);
  2208. });
  2209. svr.Get("/2", [&](const Request &req, Response &res) {
  2210. auto host_header = req.headers.find("Host");
  2211. ASSERT_TRUE(host_header != req.headers.end());
  2212. EXPECT_EQ(expected_host, host_header->second);
  2213. res.set_content("Hello World!", "text/plain");
  2214. });
  2215. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. th.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2222. // actually starts anything, so the condition !svr.is_running() will
  2223. // always remain true, and the loop never stops.
  2224. // This basically counts how many milliseconds have passed since the
  2225. // call to svr.listen(), and if after 5 seconds nothing started yet
  2226. // aborts the test.
  2227. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2228. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2229. ASSERT_LT(milliseconds, 5000U);
  2230. }
  2231. {
  2232. Client cli("::1", PORT);
  2233. cli.set_follow_location(true);
  2234. std::string body;
  2235. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2236. body.append(data, data_length);
  2237. return true;
  2238. });
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ("Hello World!", body);
  2242. }
  2243. {
  2244. Client cli("::1", PORT);
  2245. std::string body;
  2246. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2247. body.append(data, data_length);
  2248. return true;
  2249. });
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(StatusCode::Found_302, res->status);
  2252. EXPECT_EQ("___", body);
  2253. }
  2254. }
  2255. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2256. Server svr;
  2257. svr.Get("/foo", [](const Request &req, Response &res) {
  2258. auto a = req.params.find("a");
  2259. if (a != req.params.end()) {
  2260. res.set_content((*a).second, "text/plain");
  2261. res.status = StatusCode::OK_200;
  2262. } else {
  2263. res.status = StatusCode::BadRequest_400;
  2264. }
  2265. });
  2266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2267. auto se = detail::scope_exit([&] {
  2268. svr.stop();
  2269. thread.join();
  2270. ASSERT_FALSE(svr.is_running());
  2271. });
  2272. svr.wait_until_ready();
  2273. {
  2274. Client cli(HOST, PORT);
  2275. cli.set_path_encode(false);
  2276. auto res = cli.Get("/foo?a=explicitly+encoded");
  2277. ASSERT_TRUE(res);
  2278. EXPECT_EQ(StatusCode::OK_200, res->status);
  2279. // This expects it back with a space, as the `+` won't have been
  2280. // url-encoded, and server-side the params get decoded turning `+`
  2281. // into spaces.
  2282. EXPECT_EQ("explicitly encoded", res->body);
  2283. }
  2284. }
  2285. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2286. Server svr;
  2287. svr.Get("/", [](const Request &req, Response &) {
  2288. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2289. });
  2290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2291. auto se = detail::scope_exit([&] {
  2292. svr.stop();
  2293. thread.join();
  2294. ASSERT_FALSE(svr.is_running());
  2295. });
  2296. svr.wait_until_ready();
  2297. {
  2298. Client cli(HOST, PORT);
  2299. cli.set_path_encode(false);
  2300. auto res = cli.Get("/?something=%0A");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::OK_200, res->status);
  2303. }
  2304. }
  2305. TEST(BindServerTest, BindDualStack) {
  2306. Server svr;
  2307. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("Hello World!", "text/plain");
  2309. });
  2310. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2311. auto se = detail::scope_exit([&] {
  2312. svr.stop();
  2313. thread.join();
  2314. ASSERT_FALSE(svr.is_running());
  2315. });
  2316. svr.wait_until_ready();
  2317. {
  2318. Client cli("127.0.0.1", PORT);
  2319. auto res = cli.Get("/1");
  2320. ASSERT_TRUE(res);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. EXPECT_EQ("Hello World!", res->body);
  2323. }
  2324. {
  2325. Client cli("::1", PORT);
  2326. auto res = cli.Get("/1");
  2327. ASSERT_TRUE(res);
  2328. EXPECT_EQ(StatusCode::OK_200, res->status);
  2329. EXPECT_EQ("Hello World!", res->body);
  2330. }
  2331. }
  2332. TEST(BindServerTest, BindAndListenSeparately) {
  2333. Server svr;
  2334. int port = svr.bind_to_any_port("0.0.0.0");
  2335. ASSERT_TRUE(svr.is_valid());
  2336. ASSERT_TRUE(port > 0);
  2337. svr.stop();
  2338. }
  2339. #ifdef CPPHTTPLIB_SSL_ENABLED
  2340. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2342. CLIENT_CA_CERT_DIR);
  2343. int port = svr.bind_to_any_port("0.0.0.0");
  2344. ASSERT_TRUE(svr.is_valid());
  2345. ASSERT_TRUE(port > 0);
  2346. svr.stop();
  2347. }
  2348. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2349. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2350. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2351. int port = svr.bind_to_any_port("0.0.0.0");
  2352. ASSERT_TRUE(svr.is_valid());
  2353. ASSERT_TRUE(port > 0);
  2354. svr.stop();
  2355. }
  2356. TEST(BindServerTest, UpdateCertsPem) {
  2357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2358. int port = svr.bind_to_any_port("0.0.0.0");
  2359. ASSERT_TRUE(svr.is_valid());
  2360. ASSERT_TRUE(port > 0);
  2361. // Read PEM files
  2362. std::string cert_pem, key_pem, ca_pem;
  2363. read_file(SERVER_CERT_FILE, cert_pem);
  2364. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2365. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2366. // Update server certificates using PEM API
  2367. ASSERT_TRUE(
  2368. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2369. ASSERT_TRUE(svr.is_valid());
  2370. svr.stop();
  2371. }
  2372. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2373. // Start server with client CA (enables client auth)
  2374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2375. ASSERT_TRUE(svr.is_valid());
  2376. bool handler_called = false;
  2377. svr.Get("/test", [&](const Request &req, Response &res) {
  2378. handler_called = true;
  2379. // Verify client certificate is present
  2380. auto cert = req.peer_cert();
  2381. EXPECT_TRUE(static_cast<bool>(cert));
  2382. res.set_content("ok", "text/plain");
  2383. });
  2384. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2385. auto se = detail::scope_exit([&] {
  2386. svr.stop();
  2387. t.join();
  2388. ASSERT_FALSE(svr.is_running());
  2389. });
  2390. svr.wait_until_ready();
  2391. // Read PEM files
  2392. std::string cert_pem, key_pem, ca_pem;
  2393. read_file(SERVER_CERT_FILE, cert_pem);
  2394. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2395. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2396. // Update server certificates and client CA using PEM API while server running
  2397. ASSERT_TRUE(
  2398. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2399. // Connect with client certificate
  2400. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2401. cli.enable_server_certificate_verification(false);
  2402. cli.set_connection_timeout(30);
  2403. auto res = cli.Get("/test");
  2404. ASSERT_TRUE(res);
  2405. ASSERT_EQ(StatusCode::OK_200, res->status);
  2406. ASSERT_TRUE(handler_called);
  2407. EXPECT_EQ("ok", res->body);
  2408. }
  2409. #endif
  2410. TEST(ErrorHandlerTest, ContentLength) {
  2411. Server svr;
  2412. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2413. res.status = StatusCode::OK_200;
  2414. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2415. "text/html"); // <= Content-Length still 13
  2416. });
  2417. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2418. res.set_content("Hello World!\n", "text/plain");
  2419. res.status = 524;
  2420. });
  2421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. {
  2429. Client cli(HOST, PORT);
  2430. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2431. ASSERT_TRUE(res);
  2432. EXPECT_EQ(StatusCode::OK_200, res->status);
  2433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2434. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2435. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2436. }
  2437. }
  2438. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2439. TEST(ExceptionTest, WithoutExceptionHandler) {
  2440. Server svr;
  2441. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2442. throw std::runtime_error("exception...");
  2443. });
  2444. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2445. throw std::runtime_error("exception\r\n...");
  2446. });
  2447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2448. auto se = detail::scope_exit([&] {
  2449. svr.stop();
  2450. listen_thread.join();
  2451. ASSERT_FALSE(svr.is_running());
  2452. });
  2453. svr.wait_until_ready();
  2454. Client cli("localhost", PORT);
  2455. {
  2456. auto res = cli.Get("/exception");
  2457. ASSERT_TRUE(res);
  2458. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2459. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2460. }
  2461. {
  2462. auto res = cli.Get("/unknown");
  2463. ASSERT_TRUE(res);
  2464. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2465. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2466. }
  2467. }
  2468. TEST(ExceptionTest, WithExceptionHandler) {
  2469. Server svr;
  2470. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2471. std::exception_ptr ep) {
  2472. EXPECT_FALSE(ep == nullptr);
  2473. try {
  2474. std::rethrow_exception(ep);
  2475. } catch (std::exception &e) {
  2476. EXPECT_EQ("abc", std::string(e.what()));
  2477. } catch (...) {}
  2478. res.status = StatusCode::InternalServerError_500;
  2479. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2480. "text/html"); // <= Content-Length still 13 at this point
  2481. });
  2482. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2483. res.set_content("Hello World!\n", "text/plain");
  2484. throw std::runtime_error("abc");
  2485. });
  2486. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2487. auto se = detail::scope_exit([&] {
  2488. svr.stop();
  2489. thread.join();
  2490. ASSERT_FALSE(svr.is_running());
  2491. });
  2492. svr.wait_until_ready();
  2493. for (size_t i = 0; i < 10; i++) {
  2494. Client cli(HOST, PORT);
  2495. for (size_t j = 0; j < 100; j++) {
  2496. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2497. ASSERT_TRUE(res);
  2498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2501. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2502. }
  2503. cli.set_keep_alive(true);
  2504. for (size_t j = 0; j < 100; j++) {
  2505. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2506. ASSERT_TRUE(res);
  2507. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2508. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2509. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2510. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2511. }
  2512. }
  2513. }
  2514. TEST(ExceptionTest, AndErrorHandler) {
  2515. Server svr;
  2516. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2517. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2518. });
  2519. svr.set_exception_handler(
  2520. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2521. EXPECT_FALSE(ep == nullptr);
  2522. try {
  2523. std::rethrow_exception(ep);
  2524. } catch (std::exception &e) {
  2525. res.set_content(e.what(), "text/html");
  2526. } catch (...) {}
  2527. res.status = StatusCode::InternalServerError_500;
  2528. });
  2529. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2530. throw std::runtime_error("EXCEPTION");
  2531. });
  2532. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2533. res.set_content("ERROR", "text/html");
  2534. res.status = StatusCode::InternalServerError_500;
  2535. });
  2536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2537. auto se = detail::scope_exit([&] {
  2538. svr.stop();
  2539. thread.join();
  2540. ASSERT_FALSE(svr.is_running());
  2541. });
  2542. svr.wait_until_ready();
  2543. Client cli(HOST, PORT);
  2544. {
  2545. auto res = cli.Get("/exception");
  2546. ASSERT_TRUE(res);
  2547. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2548. EXPECT_EQ("EXCEPTION", res->body);
  2549. }
  2550. {
  2551. auto res = cli.Get("/error");
  2552. ASSERT_TRUE(res);
  2553. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2554. EXPECT_EQ("ERROR", res->body);
  2555. }
  2556. {
  2557. auto res = cli.Get("/invalid");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2560. EXPECT_EQ("NOT_FOUND", res->body);
  2561. }
  2562. }
  2563. #endif
  2564. TEST(NoContentTest, ContentLength) {
  2565. Server svr;
  2566. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2567. res.status = StatusCode::NoContent_204;
  2568. });
  2569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2570. auto se = detail::scope_exit([&] {
  2571. svr.stop();
  2572. thread.join();
  2573. ASSERT_FALSE(svr.is_running());
  2574. });
  2575. svr.wait_until_ready();
  2576. {
  2577. Client cli(HOST, PORT);
  2578. auto res = cli.Get("/hi");
  2579. ASSERT_TRUE(res);
  2580. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2581. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2582. }
  2583. }
  2584. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2585. #ifdef CPPHTTPLIB_SSL_ENABLED
  2586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2587. ASSERT_TRUE(svr.is_valid());
  2588. #else
  2589. Server svr;
  2590. #endif
  2591. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2592. if (req.path == "/routing_handler") {
  2593. res.set_header("PRE_ROUTING", "on");
  2594. res.set_content("Routing Handler", "text/plain");
  2595. return httplib::Server::HandlerResponse::Handled;
  2596. }
  2597. return httplib::Server::HandlerResponse::Unhandled;
  2598. });
  2599. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2600. res.set_content("Error", "text/html");
  2601. });
  2602. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2603. if (req.path == "/routing_handler") {
  2604. res.set_header("POST_ROUTING", "on");
  2605. }
  2606. });
  2607. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2608. res.set_content("Hello World!\n", "text/plain");
  2609. });
  2610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2611. auto se = detail::scope_exit([&] {
  2612. svr.stop();
  2613. thread.join();
  2614. ASSERT_FALSE(svr.is_running());
  2615. });
  2616. svr.wait_until_ready();
  2617. {
  2618. #ifdef CPPHTTPLIB_SSL_ENABLED
  2619. SSLClient cli(HOST, PORT);
  2620. cli.enable_server_certificate_verification(false);
  2621. #else
  2622. Client cli(HOST, PORT);
  2623. #endif
  2624. auto res = cli.Get("/routing_handler");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("Routing Handler", res->body);
  2628. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2629. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2630. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2631. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2632. }
  2633. {
  2634. #ifdef CPPHTTPLIB_SSL_ENABLED
  2635. SSLClient cli(HOST, PORT);
  2636. cli.enable_server_certificate_verification(false);
  2637. #else
  2638. Client cli(HOST, PORT);
  2639. #endif
  2640. auto res = cli.Get("/hi");
  2641. ASSERT_TRUE(res);
  2642. EXPECT_EQ(StatusCode::OK_200, res->status);
  2643. EXPECT_EQ("Hello World!\n", res->body);
  2644. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2645. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2646. }
  2647. {
  2648. #ifdef CPPHTTPLIB_SSL_ENABLED
  2649. SSLClient cli(HOST, PORT);
  2650. cli.enable_server_certificate_verification(false);
  2651. #else
  2652. Client cli(HOST, PORT);
  2653. #endif
  2654. auto res = cli.Get("/aaa");
  2655. ASSERT_TRUE(res);
  2656. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2657. EXPECT_EQ("Error", res->body);
  2658. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2659. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2660. }
  2661. }
  2662. TEST(RequestHandlerTest, PreRequestHandler) {
  2663. auto route_path = "/user/:user";
  2664. Server svr;
  2665. svr.Get("/hi", [](const Request &, Response &res) {
  2666. res.set_content("hi", "text/plain");
  2667. });
  2668. svr.Get(route_path, [](const Request &req, Response &res) {
  2669. res.set_content(req.path_params.at("user"), "text/plain");
  2670. });
  2671. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2672. if (req.matched_route == route_path) {
  2673. auto user = req.path_params.at("user");
  2674. if (user != "john") {
  2675. res.status = StatusCode::Forbidden_403;
  2676. res.set_content("error", "text/html");
  2677. return Server::HandlerResponse::Handled;
  2678. }
  2679. }
  2680. return Server::HandlerResponse::Unhandled;
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. {
  2691. auto res = cli.Get("/hi");
  2692. ASSERT_TRUE(res);
  2693. EXPECT_EQ(StatusCode::OK_200, res->status);
  2694. EXPECT_EQ("hi", res->body);
  2695. }
  2696. {
  2697. auto res = cli.Get("/user/john");
  2698. ASSERT_TRUE(res);
  2699. EXPECT_EQ(StatusCode::OK_200, res->status);
  2700. EXPECT_EQ("john", res->body);
  2701. }
  2702. {
  2703. auto res = cli.Get("/user/invalid-user");
  2704. ASSERT_TRUE(res);
  2705. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2706. EXPECT_EQ("error", res->body);
  2707. }
  2708. }
  2709. // The pre-request handler must run before the request body is read, so a
  2710. // rejected request never forces the server to buffer a (potentially large)
  2711. // body. Here the posted body is larger than the payload limit: if the body
  2712. // were read first the server would answer 413, but because the pre-request
  2713. // handler runs first it answers 403 and the body is never read.
  2714. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2715. Server svr;
  2716. svr.set_payload_max_length(8);
  2717. auto handler_ran = false;
  2718. svr.Post("/reject", [&](const Request &req, Response &res) {
  2719. handler_ran = true;
  2720. res.set_content(req.body, "text/plain");
  2721. });
  2722. svr.Post("/accept", [](const Request &req, Response &res) {
  2723. res.set_content(req.body, "text/plain");
  2724. });
  2725. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2726. if (req.matched_route == "/reject") {
  2727. res.status = StatusCode::Forbidden_403;
  2728. res.set_content("denied", "text/plain");
  2729. return Server::HandlerResponse::Handled;
  2730. }
  2731. return Server::HandlerResponse::Unhandled;
  2732. });
  2733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2734. auto se = detail::scope_exit([&] {
  2735. svr.stop();
  2736. thread.join();
  2737. ASSERT_FALSE(svr.is_running());
  2738. });
  2739. svr.wait_until_ready();
  2740. Client cli(HOST, PORT);
  2741. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2742. // rejects with 403 before the body is read, so 413 is never reached.
  2743. {
  2744. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2745. ASSERT_TRUE(res);
  2746. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2747. EXPECT_EQ("denied", res->body);
  2748. EXPECT_FALSE(handler_ran);
  2749. }
  2750. // An approved route still reads the body and enforces the payload limit.
  2751. {
  2752. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2753. ASSERT_TRUE(res);
  2754. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2755. }
  2756. }
  2757. TEST(UserDataTest, BasicOperations) {
  2758. httplib::UserData ud;
  2759. // Initially empty
  2760. EXPECT_FALSE(ud.has("key"));
  2761. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2762. // set and get
  2763. ud.set("key", 42);
  2764. EXPECT_TRUE(ud.has("key"));
  2765. auto *p = ud.get<int>("key");
  2766. ASSERT_NE(nullptr, p);
  2767. EXPECT_EQ(42, *p);
  2768. // Type mismatch → nullptr
  2769. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2770. // Overwrite with different type
  2771. ud.set("key", std::string("hello"));
  2772. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2773. auto *s = ud.get<std::string>("key");
  2774. ASSERT_NE(nullptr, s);
  2775. EXPECT_EQ("hello", *s);
  2776. // erase
  2777. ud.erase("key");
  2778. EXPECT_FALSE(ud.has("key"));
  2779. // clear
  2780. ud.set("a", 1);
  2781. ud.set("b", 2);
  2782. ud.clear();
  2783. EXPECT_FALSE(ud.has("a"));
  2784. EXPECT_FALSE(ud.has("b"));
  2785. }
  2786. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2787. struct AuthCtx {
  2788. std::string user_id;
  2789. };
  2790. Server svr;
  2791. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2792. res.user_data.set("auth", AuthCtx{"alice"});
  2793. return Server::HandlerResponse::Unhandled;
  2794. });
  2795. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2796. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2797. ASSERT_NE(nullptr, ctx);
  2798. res.set_content("Hello " + ctx->user_id, "text/plain");
  2799. });
  2800. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2801. auto se = detail::scope_exit([&] {
  2802. svr.stop();
  2803. thread.join();
  2804. ASSERT_FALSE(svr.is_running());
  2805. });
  2806. svr.wait_until_ready();
  2807. Client cli(HOST, PORT);
  2808. auto res = cli.Get("/me");
  2809. ASSERT_TRUE(res);
  2810. EXPECT_EQ(StatusCode::OK_200, res->status);
  2811. EXPECT_EQ("Hello alice", res->body);
  2812. }
  2813. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2814. struct RoleCtx {
  2815. std::string role;
  2816. };
  2817. Server svr;
  2818. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2819. res.user_data.set("role", RoleCtx{"admin"});
  2820. return Server::HandlerResponse::Unhandled;
  2821. });
  2822. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2823. auto *ctx = res.user_data.get<RoleCtx>("role");
  2824. ASSERT_NE(nullptr, ctx);
  2825. res.set_content(ctx->role, "text/plain");
  2826. });
  2827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2828. auto se = detail::scope_exit([&] {
  2829. svr.stop();
  2830. thread.join();
  2831. ASSERT_FALSE(svr.is_running());
  2832. });
  2833. svr.wait_until_ready();
  2834. Client cli(HOST, PORT);
  2835. auto res = cli.Get("/role");
  2836. ASSERT_TRUE(res);
  2837. EXPECT_EQ(StatusCode::OK_200, res->status);
  2838. EXPECT_EQ("admin", res->body);
  2839. }
  2840. TEST(InvalidFormatTest, StatusCode) {
  2841. Server svr;
  2842. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2843. res.set_content("Hello World!\n", "text/plain");
  2844. res.status = 9999; // Status should be a three-digit code...
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. {
  2854. Client cli(HOST, PORT);
  2855. auto res = cli.Get("/hi");
  2856. ASSERT_FALSE(res);
  2857. }
  2858. }
  2859. TEST(URLFragmentTest, WithFragment) {
  2860. Server svr;
  2861. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2862. EXPECT_TRUE(req.target == "/hi");
  2863. });
  2864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2865. auto se = detail::scope_exit([&] {
  2866. svr.stop();
  2867. thread.join();
  2868. ASSERT_FALSE(svr.is_running());
  2869. });
  2870. svr.wait_until_ready();
  2871. {
  2872. Client cli(HOST, PORT);
  2873. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2874. EXPECT_TRUE(res);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. res = cli.Get("/hi%23key1=val1=key2=val2");
  2877. EXPECT_TRUE(res);
  2878. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2879. }
  2880. }
  2881. TEST(HeaderWriter, SetHeaderWriter) {
  2882. Server svr;
  2883. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2884. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2885. return detail::write_headers(strm, hdrs);
  2886. });
  2887. svr.Get("/hi", [](const Request &req, Response &res) {
  2888. auto it = req.headers.find("CustomClientHeader");
  2889. EXPECT_TRUE(it != req.headers.end());
  2890. EXPECT_EQ(it->second, "CustomClientValue");
  2891. res.set_content("Hello World!\n", "text/plain");
  2892. });
  2893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2894. auto se = detail::scope_exit([&] {
  2895. svr.stop();
  2896. thread.join();
  2897. ASSERT_FALSE(svr.is_running());
  2898. });
  2899. svr.wait_until_ready();
  2900. {
  2901. Client cli(HOST, PORT);
  2902. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2903. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2904. return detail::write_headers(strm, hdrs);
  2905. });
  2906. auto res = cli.Get("/hi");
  2907. EXPECT_TRUE(res);
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. auto it = res->headers.find("CustomServerHeader");
  2910. EXPECT_TRUE(it != res->headers.end());
  2911. EXPECT_EQ(it->second, "CustomServerValue");
  2912. }
  2913. }
  2914. class ServerTest : public ::testing::Test {
  2915. protected:
  2916. ServerTest()
  2917. : cli_(HOST, PORT)
  2918. #ifdef CPPHTTPLIB_SSL_ENABLED
  2919. ,
  2920. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2921. #endif
  2922. {
  2923. #ifdef CPPHTTPLIB_SSL_ENABLED
  2924. cli_.enable_server_certificate_verification(false);
  2925. #endif
  2926. // Allow LARGE_DATA (100MB) responses
  2927. cli_.set_payload_max_length(200 * 1024 * 1024);
  2928. }
  2929. virtual void SetUp() {
  2930. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2931. svr_.set_payload_max_length(200 * 1024 * 1024);
  2932. svr_.set_mount_point("/", "./www");
  2933. svr_.set_mount_point("/mount", "./www2");
  2934. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2935. svr_.Get("/hi",
  2936. [&](const Request & /*req*/, Response &res) {
  2937. res.set_content("Hello World!", "text/plain");
  2938. })
  2939. .Get("/file_content",
  2940. [&](const Request & /*req*/, Response &res) {
  2941. res.set_file_content("./www/dir/test.html");
  2942. })
  2943. .Get("/file_content_with_content_type",
  2944. [&](const Request & /*req*/, Response &res) {
  2945. res.set_file_content("./www/file", "text/plain");
  2946. })
  2947. .Get("/invalid_file_content",
  2948. [&](const Request & /*req*/, Response &res) {
  2949. res.set_file_content("./www/dir/invalid_file_path");
  2950. })
  2951. .Get("/http_response_splitting",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2954. EXPECT_EQ(0U, res.headers.size());
  2955. EXPECT_FALSE(res.has_header("a"));
  2956. res.set_header("a", "1\nSet-Cookie: a=1");
  2957. EXPECT_EQ(0U, res.headers.size());
  2958. EXPECT_FALSE(res.has_header("a"));
  2959. res.set_header("a", "1\rSet-Cookie: a=1");
  2960. EXPECT_EQ(0U, res.headers.size());
  2961. EXPECT_FALSE(res.has_header("a"));
  2962. res.set_header("a\r\nb", "0");
  2963. EXPECT_EQ(0U, res.headers.size());
  2964. EXPECT_FALSE(res.has_header("a"));
  2965. res.set_header("a\rb", "0");
  2966. EXPECT_EQ(0U, res.headers.size());
  2967. EXPECT_FALSE(res.has_header("a"));
  2968. res.set_header("a\nb", "0");
  2969. EXPECT_EQ(0U, res.headers.size());
  2970. EXPECT_FALSE(res.has_header("a"));
  2971. res.set_redirect("1\r\nSet-Cookie: a=1");
  2972. EXPECT_EQ(0U, res.headers.size());
  2973. EXPECT_FALSE(res.has_header("Location"));
  2974. })
  2975. .Get("/slow",
  2976. [&](const Request & /*req*/, Response &res) {
  2977. std::this_thread::sleep_for(std::chrono::seconds(4));
  2978. res.set_content("slow", "text/plain");
  2979. })
  2980. #if 0
  2981. .Post("/slowpost",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. std::this_thread::sleep_for(std::chrono::seconds(2));
  2984. res.set_content("slow", "text/plain");
  2985. })
  2986. #endif
  2987. .Get("/remote_addr",
  2988. [&](const Request &req, Response &res) {
  2989. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2990. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2991. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2992. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2993. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2994. #endif
  2995. res.set_content(req.remote_addr, "text/plain");
  2996. })
  2997. .Get("/local_addr",
  2998. [&](const Request &req, Response &res) {
  2999. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3000. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3001. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3002. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3003. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3004. #endif
  3005. auto local_addr = req.local_addr;
  3006. auto local_port = std::to_string(req.local_port);
  3007. res.set_content(local_addr.append(":").append(local_port),
  3008. "text/plain");
  3009. })
  3010. .Get("/endwith%",
  3011. [&](const Request & /*req*/, Response &res) {
  3012. res.set_content("Hello World!", "text/plain");
  3013. })
  3014. .Get("/a\\+\\+b",
  3015. [&](const Request &req, Response &res) {
  3016. ASSERT_TRUE(req.has_param("a +b"));
  3017. auto val = req.get_param_value("a +b");
  3018. res.set_content(val, "text/plain");
  3019. })
  3020. .Get("/", [&](const Request & /*req*/,
  3021. Response &res) { res.set_redirect("/hi"); })
  3022. .Post("/1",
  3023. [](const Request & /*req*/, Response &res) {
  3024. res.set_redirect("/2", StatusCode::SeeOther_303);
  3025. })
  3026. .Get("/2",
  3027. [](const Request & /*req*/, Response &res) {
  3028. res.set_content("redirected.", "text/plain");
  3029. res.status = StatusCode::OK_200;
  3030. })
  3031. .Post("/person",
  3032. [&](const Request &req, Response &res) {
  3033. if (req.has_param("name") && req.has_param("note")) {
  3034. persons_[req.get_param_value("name")] =
  3035. req.get_param_value("note");
  3036. } else {
  3037. res.status = StatusCode::BadRequest_400;
  3038. }
  3039. })
  3040. .Put("/person",
  3041. [&](const Request &req, Response &res) {
  3042. if (req.has_param("name") && req.has_param("note")) {
  3043. persons_[req.get_param_value("name")] =
  3044. req.get_param_value("note");
  3045. } else {
  3046. res.status = StatusCode::BadRequest_400;
  3047. }
  3048. })
  3049. .Get("/person/(.*)",
  3050. [&](const Request &req, Response &res) {
  3051. string name = req.matches[1];
  3052. if (persons_.find(name) != persons_.end()) {
  3053. auto note = persons_[name];
  3054. res.set_content(note, "text/plain");
  3055. } else {
  3056. res.status = StatusCode::NotFound_404;
  3057. }
  3058. })
  3059. .Delete("/person",
  3060. [&](const Request &req, Response &res) {
  3061. if (req.has_param("name")) {
  3062. string name = req.get_param_value("name");
  3063. if (persons_.find(name) != persons_.end()) {
  3064. persons_.erase(name);
  3065. res.set_content("DELETED", "text/plain");
  3066. } else {
  3067. res.status = StatusCode::NotFound_404;
  3068. }
  3069. } else {
  3070. res.status = StatusCode::BadRequest_400;
  3071. }
  3072. })
  3073. .Post("/x-www-form-urlencoded-json",
  3074. [&](const Request &req, Response &res) {
  3075. auto json = req.get_param_value("json");
  3076. ASSERT_EQ(JSON_DATA, json);
  3077. res.set_content(json, "appliation/json");
  3078. res.status = StatusCode::OK_200;
  3079. })
  3080. .Get("/streamed-chunked",
  3081. [&](const Request & /*req*/, Response &res) {
  3082. res.set_chunked_content_provider(
  3083. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3084. sink.os << "123";
  3085. sink.os << "456";
  3086. sink.os << "789";
  3087. sink.done();
  3088. return true;
  3089. });
  3090. })
  3091. .Get("/streamed-chunked-with-prohibited-trailer",
  3092. [&](const Request & /*req*/, Response &res) {
  3093. auto i = new int(0);
  3094. // Declare both a prohibited trailer (Content-Length) and an
  3095. // allowed one
  3096. res.set_header("Trailer", "Content-Length, X-Allowed");
  3097. res.set_chunked_content_provider(
  3098. "text/plain",
  3099. [i](size_t /*offset*/, DataSink &sink) {
  3100. switch (*i) {
  3101. case 0: sink.os << "123"; break;
  3102. case 1: sink.os << "456"; break;
  3103. case 2: sink.os << "789"; break;
  3104. case 3: {
  3105. sink.done_with_trailer(
  3106. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3107. } break;
  3108. }
  3109. (*i)++;
  3110. return true;
  3111. },
  3112. [i](bool success) {
  3113. EXPECT_TRUE(success);
  3114. delete i;
  3115. });
  3116. })
  3117. .Get("/streamed-chunked2",
  3118. [&](const Request & /*req*/, Response &res) {
  3119. auto i = new int(0);
  3120. res.set_chunked_content_provider(
  3121. "text/plain",
  3122. [i](size_t /*offset*/, DataSink &sink) {
  3123. switch (*i) {
  3124. case 0: sink.os << "123"; break;
  3125. case 1: sink.os << "456"; break;
  3126. case 2: sink.os << "789"; break;
  3127. case 3: sink.done(); break;
  3128. }
  3129. (*i)++;
  3130. return true;
  3131. },
  3132. [i](bool success) {
  3133. EXPECT_TRUE(success);
  3134. delete i;
  3135. });
  3136. })
  3137. .Get("/streamed-chunked-with-trailer",
  3138. [&](const Request & /*req*/, Response &res) {
  3139. auto i = new int(0);
  3140. res.set_header("Trailer", "Dummy1, Dummy2");
  3141. res.set_chunked_content_provider(
  3142. "text/plain",
  3143. [i](size_t /*offset*/, DataSink &sink) {
  3144. switch (*i) {
  3145. case 0: sink.os << "123"; break;
  3146. case 1: sink.os << "456"; break;
  3147. case 2: sink.os << "789"; break;
  3148. case 3: {
  3149. sink.done_with_trailer(
  3150. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3151. } break;
  3152. }
  3153. (*i)++;
  3154. return true;
  3155. },
  3156. [i](bool success) {
  3157. EXPECT_TRUE(success);
  3158. delete i;
  3159. });
  3160. })
  3161. .Get("/streamed",
  3162. [&](const Request & /*req*/, Response &res) {
  3163. res.set_content_provider(
  3164. 6, "text/plain",
  3165. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3166. sink.os << (offset < 3 ? "a" : "b");
  3167. return true;
  3168. });
  3169. })
  3170. .Get("/streamed-without-length",
  3171. [&](const Request & /*req*/, Response &res) {
  3172. auto data = new std::string("abcdefg");
  3173. res.set_content_provider(
  3174. "text/plain",
  3175. [data](size_t offset, DataSink &sink) {
  3176. if (offset < data->size()) {
  3177. sink.os << data->substr(offset);
  3178. }
  3179. sink.done();
  3180. return true;
  3181. },
  3182. [data](bool success) {
  3183. EXPECT_TRUE(success);
  3184. delete data;
  3185. });
  3186. })
  3187. .Get("/streamed-with-range",
  3188. [&](const Request &req, Response &res) {
  3189. auto data = new std::string("abcdefg");
  3190. res.set_content_provider(
  3191. data->size(), "text/plain",
  3192. [data](size_t offset, size_t length, DataSink &sink) {
  3193. size_t DATA_CHUNK_SIZE = 4;
  3194. const auto &d = *data;
  3195. auto out_len =
  3196. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3197. auto ret =
  3198. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3199. EXPECT_TRUE(ret);
  3200. return true;
  3201. },
  3202. [data, &req](bool success) {
  3203. EXPECT_EQ(success, !req.has_param("error"));
  3204. delete data;
  3205. });
  3206. })
  3207. .Get("/streamed-cancel",
  3208. [&](const Request & /*req*/, Response &res) {
  3209. res.set_content_provider(
  3210. size_t(-1), "text/plain",
  3211. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3212. sink.os << "data_chunk";
  3213. return true;
  3214. });
  3215. })
  3216. .Get("/regex-with-delimiter",
  3217. [&](const Request &req, Response & /*res*/) {
  3218. ASSERT_TRUE(req.has_param("key"));
  3219. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3220. })
  3221. .Get("/with-range",
  3222. [&](const Request & /*req*/, Response &res) {
  3223. res.set_content("abcdefg", "text/plain");
  3224. })
  3225. .Get("/test-start-time",
  3226. [&](const Request &req, Response & /*res*/) {
  3227. EXPECT_NE(req.start_time_,
  3228. std::chrono::steady_clock::time_point::min());
  3229. })
  3230. .Get("/with-range-customized-response",
  3231. [&](const Request & /*req*/, Response &res) {
  3232. res.status = StatusCode::BadRequest_400;
  3233. res.set_content(JSON_DATA, "application/json");
  3234. })
  3235. .Post("/chunked",
  3236. [&](const Request &req, Response & /*res*/) {
  3237. EXPECT_EQ(req.body, "dechunked post body");
  3238. })
  3239. .Post("/large-chunked",
  3240. [&](const Request &req, Response & /*res*/) {
  3241. std::string expected(6 * 30 * 1024u, 'a');
  3242. EXPECT_EQ(req.body, expected);
  3243. })
  3244. .Post("/multipart",
  3245. [&](const Request &req, Response & /*res*/) {
  3246. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3247. req.form.get_field_count("text2") +
  3248. req.form.get_field_count("file3") +
  3249. req.form.get_field_count("file4"));
  3250. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3251. req.form.get_file_count("file2"));
  3252. ASSERT_TRUE(!req.form.has_file("???"));
  3253. ASSERT_TRUE(!req.form.has_field("???"));
  3254. ASSERT_TRUE(req.body.empty());
  3255. {
  3256. const auto &text = req.form.get_field("text1");
  3257. EXPECT_EQ("text default", text);
  3258. }
  3259. {
  3260. const auto &text = req.form.get_field("text2");
  3261. EXPECT_EQ("aωb", text);
  3262. }
  3263. {
  3264. const auto &file = req.form.get_file("file1");
  3265. EXPECT_EQ("hello.txt", file.filename);
  3266. EXPECT_EQ("text/plain", file.content_type);
  3267. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3268. }
  3269. {
  3270. const auto &file = req.form.get_file("file2");
  3271. EXPECT_EQ("world.json", file.filename);
  3272. EXPECT_EQ("application/json", file.content_type);
  3273. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3274. }
  3275. {
  3276. const auto &text = req.form.get_field("file3");
  3277. EXPECT_EQ(0u, text.size());
  3278. }
  3279. {
  3280. const auto &text = req.form.get_field("file4");
  3281. EXPECT_EQ(0u, text.size());
  3282. }
  3283. })
  3284. .Post("/multipart/multi_file_values",
  3285. [&](const Request &req, Response & /*res*/) {
  3286. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3287. req.form.get_field_count("multi_text1"));
  3288. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3289. ASSERT_TRUE(!req.form.has_file("???"));
  3290. ASSERT_TRUE(!req.form.has_field("???"));
  3291. ASSERT_TRUE(req.body.empty());
  3292. {
  3293. const auto &text = req.form.get_field("text");
  3294. EXPECT_EQ("default text", text);
  3295. }
  3296. {
  3297. const auto &text1_values = req.form.get_fields("multi_text1");
  3298. EXPECT_EQ(2u, text1_values.size());
  3299. EXPECT_EQ("aaaaa", text1_values[0]);
  3300. EXPECT_EQ("bbbbb", text1_values[1]);
  3301. }
  3302. {
  3303. const auto &file1_values = req.form.get_files("multi_file1");
  3304. EXPECT_EQ(2u, file1_values.size());
  3305. auto file1 = file1_values[0];
  3306. EXPECT_EQ(file1.filename, "hello.txt");
  3307. EXPECT_EQ(file1.content_type, "text/plain");
  3308. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3309. auto file2 = file1_values[1];
  3310. EXPECT_EQ(file2.filename, "world.json");
  3311. EXPECT_EQ(file2.content_type, "application/json");
  3312. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3313. }
  3314. })
  3315. .Post("/empty",
  3316. [&](const Request &req, Response &res) {
  3317. EXPECT_EQ(req.body, "");
  3318. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3319. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3320. res.set_content("empty", "text/plain");
  3321. })
  3322. .Post("/empty-no-content-type",
  3323. [&](const Request &req, Response &res) {
  3324. EXPECT_EQ(req.body, "");
  3325. EXPECT_FALSE(req.has_header("Content-Type"));
  3326. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3327. res.set_content("empty-no-content-type", "text/plain");
  3328. })
  3329. .Post("/path-only",
  3330. [&](const Request &req, Response &res) {
  3331. EXPECT_EQ(req.body, "");
  3332. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3333. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3334. res.set_content("path-only", "text/plain");
  3335. })
  3336. .Post("/path-headers-only",
  3337. [&](const Request &req, Response &res) {
  3338. EXPECT_EQ(req.body, "");
  3339. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3340. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3341. EXPECT_EQ("world", req.get_header_value("hello"));
  3342. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3343. res.set_content("path-headers-only", "text/plain");
  3344. })
  3345. .Post("/post-large",
  3346. [&](const Request &req, Response &res) {
  3347. EXPECT_EQ(req.body, LARGE_DATA);
  3348. res.set_content(req.body, "text/plain");
  3349. })
  3350. .Post("/post-loopback",
  3351. [&](const Request &, Response &res,
  3352. ContentReader const &content_reader) {
  3353. std::string body;
  3354. content_reader([&](const char *data, size_t data_length) {
  3355. body.append(data, data_length);
  3356. return true;
  3357. });
  3358. res.set_content(body, "text/plain");
  3359. })
  3360. .Put("/put-loopback",
  3361. [&](const Request &, Response &res,
  3362. ContentReader const &content_reader) {
  3363. std::string body;
  3364. content_reader([&](const char *data, size_t data_length) {
  3365. body.append(data, data_length);
  3366. return true;
  3367. });
  3368. res.set_content(body, "text/plain");
  3369. })
  3370. .Patch("/patch-loopback",
  3371. [&](const Request &, Response &res,
  3372. ContentReader const &content_reader) {
  3373. std::string body;
  3374. content_reader([&](const char *data, size_t data_length) {
  3375. body.append(data, data_length);
  3376. return true;
  3377. });
  3378. res.set_content(body, "text/plain");
  3379. })
  3380. .Put("/empty-no-content-type",
  3381. [&](const Request &req, Response &res) {
  3382. EXPECT_EQ(req.body, "");
  3383. EXPECT_FALSE(req.has_header("Content-Type"));
  3384. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3385. res.set_content("empty-no-content-type", "text/plain");
  3386. })
  3387. .Put("/put",
  3388. [&](const Request &req, Response &res) {
  3389. EXPECT_EQ(req.body, "PUT");
  3390. res.set_content(req.body, "text/plain");
  3391. })
  3392. .Put("/put-large",
  3393. [&](const Request &req, Response &res) {
  3394. EXPECT_EQ(req.body, LARGE_DATA);
  3395. res.set_content(req.body, "text/plain");
  3396. })
  3397. .Patch("/patch",
  3398. [&](const Request &req, Response &res) {
  3399. EXPECT_EQ(req.body, "PATCH");
  3400. res.set_content(req.body, "text/plain");
  3401. })
  3402. .Delete("/delete",
  3403. [&](const Request & /*req*/, Response &res) {
  3404. res.set_content("DELETE", "text/plain");
  3405. })
  3406. .Delete("/delete-body",
  3407. [&](const Request &req, Response &res) {
  3408. EXPECT_EQ(req.body, "content");
  3409. res.set_content(req.body, "text/plain");
  3410. })
  3411. .Options(R"(\*)",
  3412. [&](const Request & /*req*/, Response &res) {
  3413. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3414. })
  3415. .Get("/request-target",
  3416. [&](const Request &req, Response & /*res*/) {
  3417. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3418. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3419. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3420. })
  3421. .Get("/long-query-value",
  3422. [&](const Request &req, Response & /*res*/) {
  3423. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3424. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3425. })
  3426. .Get("/too-long-query-value",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3429. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3430. })
  3431. .Get("/array-param",
  3432. [&](const Request &req, Response & /*res*/) {
  3433. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3434. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3435. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3436. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3437. })
  3438. .Get("/array-param-values",
  3439. [&](const Request &req, Response & /*res*/) {
  3440. auto values = req.get_param_values("array");
  3441. EXPECT_EQ(3u, values.size());
  3442. EXPECT_EQ("value1", values[0]);
  3443. EXPECT_EQ("value2", values[1]);
  3444. EXPECT_EQ("value3", values[2]);
  3445. auto empty = req.get_param_values("nonexistent");
  3446. EXPECT_TRUE(empty.empty());
  3447. })
  3448. .Post("/validate-no-multiple-headers",
  3449. [&](const Request &req, Response & /*res*/) {
  3450. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3451. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3452. })
  3453. .Post("/content_receiver",
  3454. [&](const Request &req, Response &res,
  3455. const ContentReader &content_reader) {
  3456. if (req.is_multipart_form_data()) {
  3457. std::vector<FormData> items;
  3458. content_reader(
  3459. [&](const FormData &file) {
  3460. items.push_back(file);
  3461. return true;
  3462. },
  3463. [&](const char *data, size_t data_length) {
  3464. items.back().content.append(data, data_length);
  3465. return true;
  3466. });
  3467. EXPECT_EQ(5u, items.size());
  3468. {
  3469. const auto &file = get_file_value(items, "text1");
  3470. EXPECT_TRUE(file.filename.empty());
  3471. EXPECT_EQ("text default", file.content);
  3472. }
  3473. {
  3474. const auto &file = get_file_value(items, "text2");
  3475. EXPECT_TRUE(file.filename.empty());
  3476. EXPECT_EQ("aωb", file.content);
  3477. }
  3478. {
  3479. const auto &file = get_file_value(items, "file1");
  3480. EXPECT_EQ("hello.txt", file.filename);
  3481. EXPECT_EQ("text/plain", file.content_type);
  3482. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3483. }
  3484. {
  3485. const auto &file = get_file_value(items, "file2");
  3486. EXPECT_EQ("world.json", file.filename);
  3487. EXPECT_EQ("application/json", file.content_type);
  3488. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3489. }
  3490. {
  3491. const auto &file = get_file_value(items, "file3");
  3492. EXPECT_TRUE(file.filename.empty());
  3493. EXPECT_EQ("application/octet-stream", file.content_type);
  3494. EXPECT_EQ(0u, file.content.size());
  3495. }
  3496. } else {
  3497. std::string body;
  3498. content_reader([&](const char *data, size_t data_length) {
  3499. EXPECT_EQ(7U, data_length);
  3500. body.append(data, data_length);
  3501. return true;
  3502. });
  3503. EXPECT_EQ(body, "content");
  3504. res.set_content(body, "text/plain");
  3505. }
  3506. })
  3507. .Put("/content_receiver",
  3508. [&](const Request & /*req*/, Response &res,
  3509. const ContentReader &content_reader) {
  3510. std::string body;
  3511. content_reader([&](const char *data, size_t data_length) {
  3512. body.append(data, data_length);
  3513. return true;
  3514. });
  3515. EXPECT_EQ(body, "content");
  3516. res.set_content(body, "text/plain");
  3517. })
  3518. .Patch("/content_receiver",
  3519. [&](const Request & /*req*/, Response &res,
  3520. const ContentReader &content_reader) {
  3521. std::string body;
  3522. content_reader([&](const char *data, size_t data_length) {
  3523. body.append(data, data_length);
  3524. return true;
  3525. });
  3526. EXPECT_EQ(body, "content");
  3527. res.set_content(body, "text/plain");
  3528. })
  3529. .Post("/query-string-and-body",
  3530. [&](const Request &req, Response & /*res*/) {
  3531. ASSERT_TRUE(req.has_param("key"));
  3532. EXPECT_EQ(req.get_param_value("key"), "value");
  3533. EXPECT_EQ(req.body, "content");
  3534. })
  3535. .Get("/last-request",
  3536. [&](const Request &req, Response & /*res*/) {
  3537. EXPECT_EQ("close", req.get_header_value("Connection"));
  3538. })
  3539. .Get(R"(/redirect/(\d+))",
  3540. [&](const Request &req, Response &res) {
  3541. auto num = std::stoi(req.matches[1]) + 1;
  3542. std::string url = "/redirect/" + std::to_string(num);
  3543. res.set_redirect(url);
  3544. })
  3545. .Post("/binary",
  3546. [&](const Request &req, Response &res) {
  3547. EXPECT_EQ(4U, req.body.size());
  3548. EXPECT_EQ("application/octet-stream",
  3549. req.get_header_value("Content-Type"));
  3550. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3551. res.set_content(req.body, "application/octet-stream");
  3552. })
  3553. .Put("/binary",
  3554. [&](const Request &req, Response &res) {
  3555. EXPECT_EQ(4U, req.body.size());
  3556. EXPECT_EQ("application/octet-stream",
  3557. req.get_header_value("Content-Type"));
  3558. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3559. res.set_content(req.body, "application/octet-stream");
  3560. })
  3561. .Patch("/binary",
  3562. [&](const Request &req, Response &res) {
  3563. EXPECT_EQ(4U, req.body.size());
  3564. EXPECT_EQ("application/octet-stream",
  3565. req.get_header_value("Content-Type"));
  3566. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3567. res.set_content(req.body, "application/octet-stream");
  3568. })
  3569. .Delete("/binary",
  3570. [&](const Request &req, Response &res) {
  3571. EXPECT_EQ(4U, req.body.size());
  3572. EXPECT_EQ("application/octet-stream",
  3573. req.get_header_value("Content-Type"));
  3574. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3575. res.set_content(req.body, "application/octet-stream");
  3576. })
  3577. .Get("/issue1772",
  3578. [&](const Request & /*req*/, Response &res) {
  3579. res.status = 401;
  3580. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3581. })
  3582. .Delete("/issue609",
  3583. [](const httplib::Request &, httplib::Response &res,
  3584. const httplib::ContentReader &) {
  3585. res.set_content("ok", "text/plain");
  3586. })
  3587. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3588. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3589. .Get("/compress",
  3590. [&](const Request & /*req*/, Response &res) {
  3591. res.set_content(
  3592. "12345678901234567890123456789012345678901234567890123456789"
  3593. "01234567890123456789012345678901234567890",
  3594. "text/plain");
  3595. })
  3596. .Get("/compress-with-charset",
  3597. [&](const Request & /*req*/, Response &res) {
  3598. res.set_content(
  3599. "12345678901234567890123456789012345678901234567890123456789"
  3600. "01234567890123456789012345678901234567890",
  3601. "application/json; charset=utf-8");
  3602. })
  3603. .Get("/nocompress",
  3604. [&](const Request & /*req*/, Response &res) {
  3605. res.set_content(
  3606. "12345678901234567890123456789012345678901234567890123456789"
  3607. "01234567890123456789012345678901234567890",
  3608. "application/octet-stream");
  3609. })
  3610. .Post("/compress-multipart",
  3611. [&](const Request &req, Response & /*res*/) {
  3612. EXPECT_EQ(2u, req.form.fields.size());
  3613. ASSERT_TRUE(!req.form.has_field("???"));
  3614. {
  3615. const auto &text = req.form.get_field("key1");
  3616. EXPECT_EQ("test", text);
  3617. }
  3618. {
  3619. const auto &text = req.form.get_field("key2");
  3620. EXPECT_EQ("--abcdefg123", text);
  3621. }
  3622. })
  3623. #endif
  3624. ;
  3625. persons_["john"] = "programmer";
  3626. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3627. svr_.wait_until_ready();
  3628. }
  3629. virtual void TearDown() {
  3630. svr_.stop();
  3631. if (!request_threads_.empty()) {
  3632. std::this_thread::sleep_for(std::chrono::seconds(1));
  3633. for (auto &t : request_threads_) {
  3634. t.join();
  3635. }
  3636. }
  3637. t_.join();
  3638. }
  3639. map<string, string> persons_;
  3640. #ifdef CPPHTTPLIB_SSL_ENABLED
  3641. SSLClient cli_;
  3642. SSLServer svr_;
  3643. #else
  3644. Client cli_;
  3645. Server svr_;
  3646. #endif
  3647. thread t_;
  3648. std::vector<thread> request_threads_;
  3649. };
  3650. TEST_F(ServerTest, GetMethod200) {
  3651. auto res = cli_.Get("/hi");
  3652. ASSERT_TRUE(res);
  3653. EXPECT_EQ("HTTP/1.1", res->version);
  3654. EXPECT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ("OK", res->reason);
  3656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3657. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3658. EXPECT_EQ("Hello World!", res->body);
  3659. }
  3660. TEST_F(ServerTest, GetEmptyFile) {
  3661. auto res = cli_.Get("/empty_file");
  3662. ASSERT_TRUE(res);
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3665. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3666. EXPECT_EQ("", res->body);
  3667. }
  3668. TEST_F(ServerTest, GetFileContent) {
  3669. auto res = cli_.Get("/file_content");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3673. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3674. EXPECT_EQ("test.html", res->body);
  3675. }
  3676. TEST_F(ServerTest, GetFileContentWithRange) {
  3677. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3680. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3681. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3682. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3683. EXPECT_EQ("est", res->body);
  3684. }
  3685. TEST_F(ServerTest, GetFileContentWithContentType) {
  3686. auto res = cli_.Get("/file_content_with_content_type");
  3687. ASSERT_TRUE(res);
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3690. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3691. EXPECT_EQ("file\n", res->body);
  3692. }
  3693. TEST_F(ServerTest, GetInvalidFileContent) {
  3694. auto res = cli_.Get("/invalid_file_content");
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3697. }
  3698. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3699. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ("HTTP/1.1", res->version);
  3702. EXPECT_EQ(StatusCode::OK_200, res->status);
  3703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3704. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3705. EXPECT_EQ("Hello World!", res->body);
  3706. }
  3707. TEST_F(ServerTest, GetMethod302) {
  3708. auto res = cli_.Get("/");
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(StatusCode::Found_302, res->status);
  3711. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3712. }
  3713. TEST_F(ServerTest, GetMethod302Redirect) {
  3714. cli_.set_follow_location(true);
  3715. auto res = cli_.Get("/");
  3716. ASSERT_TRUE(res);
  3717. EXPECT_EQ(StatusCode::OK_200, res->status);
  3718. EXPECT_EQ("Hello World!", res->body);
  3719. EXPECT_EQ("/hi", res->location);
  3720. }
  3721. TEST_F(ServerTest, GetMethod404) {
  3722. auto res = cli_.Get("/invalid");
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3725. }
  3726. TEST_F(ServerTest, HeadMethod200) {
  3727. auto res = cli_.Head("/hi");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3731. EXPECT_TRUE(res->body.empty());
  3732. }
  3733. TEST_F(ServerTest, HeadMethod200Static) {
  3734. auto res = cli_.Head("/mount/dir/index.html");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::OK_200, res->status);
  3737. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3738. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3739. EXPECT_TRUE(res->body.empty());
  3740. }
  3741. TEST_F(ServerTest, HeadMethod404) {
  3742. auto res = cli_.Head("/invalid");
  3743. ASSERT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3745. EXPECT_TRUE(res->body.empty());
  3746. }
  3747. TEST_F(ServerTest, GetMethodPersonJohn) {
  3748. auto res = cli_.Get("/person/john");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::OK_200, res->status);
  3751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3752. EXPECT_EQ("programmer", res->body);
  3753. }
  3754. TEST_F(ServerTest, PostMethod1) {
  3755. auto res = cli_.Get("/person/john1");
  3756. ASSERT_TRUE(res);
  3757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3758. res = cli_.Post("/person", "name=john1&note=coder",
  3759. "application/x-www-form-urlencoded");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. res = cli_.Get("/person/john1");
  3763. ASSERT_TRUE(res);
  3764. ASSERT_EQ(StatusCode::OK_200, res->status);
  3765. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3766. ASSERT_EQ("coder", res->body);
  3767. }
  3768. TEST_F(ServerTest, PostMethod2) {
  3769. auto res = cli_.Get("/person/john2");
  3770. ASSERT_TRUE(res);
  3771. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3772. Params params;
  3773. params.emplace("name", "john2");
  3774. params.emplace("note", "coder");
  3775. res = cli_.Post("/person", params);
  3776. ASSERT_TRUE(res);
  3777. ASSERT_EQ(StatusCode::OK_200, res->status);
  3778. res = cli_.Get("/person/john2");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(StatusCode::OK_200, res->status);
  3781. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3782. ASSERT_EQ("coder", res->body);
  3783. }
  3784. TEST_F(ServerTest, PutMethod3) {
  3785. auto res = cli_.Get("/person/john3");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3788. Params params;
  3789. params.emplace("name", "john3");
  3790. params.emplace("note", "coder");
  3791. res = cli_.Put("/person", params);
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. res = cli_.Get("/person/john3");
  3795. ASSERT_TRUE(res);
  3796. ASSERT_EQ(StatusCode::OK_200, res->status);
  3797. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3798. ASSERT_EQ("coder", res->body);
  3799. }
  3800. TEST_F(ServerTest, DeleteMethod1) {
  3801. auto res = cli_.Get("/person/john4");
  3802. ASSERT_TRUE(res);
  3803. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3804. Params params;
  3805. params.emplace("name", "john4");
  3806. params.emplace("note", "coder");
  3807. res = cli_.Post("/person", params);
  3808. ASSERT_TRUE(res);
  3809. ASSERT_EQ(StatusCode::OK_200, res->status);
  3810. res = cli_.Get("/person/john4");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3814. ASSERT_EQ("coder", res->body);
  3815. Params delete_params;
  3816. delete_params.emplace("name", "john4");
  3817. res = cli_.Delete("/person", delete_params);
  3818. ASSERT_TRUE(res);
  3819. ASSERT_EQ(StatusCode::OK_200, res->status);
  3820. ASSERT_EQ("DELETED", res->body);
  3821. res = cli_.Get("/person/john4");
  3822. ASSERT_TRUE(res);
  3823. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3824. }
  3825. TEST_F(ServerTest, DeleteMethod2) {
  3826. auto res = cli_.Get("/person/john5");
  3827. ASSERT_TRUE(res);
  3828. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3829. Params params;
  3830. params.emplace("name", "john5");
  3831. params.emplace("note", "developer");
  3832. res = cli_.Post("/person", params);
  3833. ASSERT_TRUE(res);
  3834. ASSERT_EQ(StatusCode::OK_200, res->status);
  3835. res = cli_.Get("/person/john5");
  3836. ASSERT_TRUE(res);
  3837. ASSERT_EQ(StatusCode::OK_200, res->status);
  3838. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3839. ASSERT_EQ("developer", res->body);
  3840. Params delete_params;
  3841. delete_params.emplace("name", "john5");
  3842. Headers headers;
  3843. headers.emplace("Custom-Header", "test-value");
  3844. res = cli_.Delete("/person", headers, delete_params);
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ("DELETED", res->body);
  3848. res = cli_.Get("/person/john5");
  3849. ASSERT_TRUE(res);
  3850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3851. }
  3852. TEST_F(ServerTest, DeleteMethod3) {
  3853. auto res = cli_.Get("/person/john6");
  3854. ASSERT_TRUE(res);
  3855. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3856. Params params;
  3857. params.emplace("name", "john6");
  3858. params.emplace("note", "tester");
  3859. res = cli_.Post("/person", params);
  3860. ASSERT_TRUE(res);
  3861. ASSERT_EQ(StatusCode::OK_200, res->status);
  3862. res = cli_.Get("/person/john6");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3866. ASSERT_EQ("tester", res->body);
  3867. Params delete_params;
  3868. delete_params.emplace("name", "john6");
  3869. Headers headers;
  3870. headers.emplace("Custom-Header", "test-value");
  3871. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3872. ASSERT_TRUE(res);
  3873. ASSERT_EQ(StatusCode::OK_200, res->status);
  3874. ASSERT_EQ("DELETED", res->body);
  3875. res = cli_.Get("/person/john6");
  3876. ASSERT_TRUE(res);
  3877. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3878. }
  3879. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3880. Params params;
  3881. params.emplace("json", JSON_DATA);
  3882. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3883. ASSERT_TRUE(res);
  3884. ASSERT_EQ(StatusCode::OK_200, res->status);
  3885. ASSERT_EQ(JSON_DATA, res->body);
  3886. }
  3887. TEST_F(ServerTest, PostEmptyContent) {
  3888. auto res = cli_.Post("/empty", "", "text/plain");
  3889. ASSERT_TRUE(res);
  3890. ASSERT_EQ(StatusCode::OK_200, res->status);
  3891. ASSERT_EQ("empty", res->body);
  3892. }
  3893. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3894. auto res = cli_.Post("/empty-no-content-type");
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. ASSERT_EQ("empty-no-content-type", res->body);
  3898. }
  3899. TEST_F(ServerTest, PostPathOnly) {
  3900. auto res = cli_.Post("/path-only");
  3901. ASSERT_TRUE(res);
  3902. ASSERT_EQ(StatusCode::OK_200, res->status);
  3903. ASSERT_EQ("path-only", res->body);
  3904. }
  3905. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3906. auto res = cli_.Post("/path-headers-only",
  3907. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3908. ASSERT_TRUE(res);
  3909. ASSERT_EQ(StatusCode::OK_200, res->status);
  3910. ASSERT_EQ("path-headers-only", res->body);
  3911. }
  3912. TEST_F(ServerTest, PostLarge) {
  3913. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3914. ASSERT_TRUE(res);
  3915. ASSERT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ(LARGE_DATA, res->body);
  3917. }
  3918. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3919. auto res = cli_.Put("/empty-no-content-type");
  3920. ASSERT_TRUE(res);
  3921. ASSERT_EQ(StatusCode::OK_200, res->status);
  3922. ASSERT_EQ("empty-no-content-type", res->body);
  3923. }
  3924. TEST_F(ServerTest, GetMethodDir) {
  3925. auto res = cli_.Get("/dir/");
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3929. auto body = R"(<html>
  3930. <head>
  3931. </head>
  3932. <body>
  3933. <a href="/dir/test.html">Test</a>
  3934. <a href="/hi">hi</a>
  3935. </body>
  3936. </html>
  3937. )";
  3938. EXPECT_EQ(body, res->body);
  3939. }
  3940. TEST_F(ServerTest, GetMethodDirTest) {
  3941. auto res = cli_.Get("/dir/test.html");
  3942. ASSERT_TRUE(res);
  3943. EXPECT_EQ(StatusCode::OK_200, res->status);
  3944. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3945. EXPECT_EQ("test.html", res->body);
  3946. }
  3947. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3948. auto res = cli_.Get("/dir/../dir/test.html");
  3949. ASSERT_TRUE(res);
  3950. EXPECT_EQ(StatusCode::OK_200, res->status);
  3951. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3952. EXPECT_EQ("test.html", res->body);
  3953. }
  3954. TEST_F(ServerTest, GetMethodInvalidPath) {
  3955. auto res = cli_.Get("/dir/../test.html");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3958. }
  3959. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3960. auto res = cli_.Get("/../www/dir/test.html");
  3961. ASSERT_TRUE(res);
  3962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3963. }
  3964. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3965. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3966. ASSERT_TRUE(res);
  3967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3968. }
  3969. TEST_F(ServerTest, GetMethodDirMountTest) {
  3970. auto res = cli_.Get("/mount/dir/test.html");
  3971. ASSERT_TRUE(res);
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3974. EXPECT_EQ("test.html", res->body);
  3975. }
  3976. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3977. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3978. ASSERT_TRUE(res);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3981. EXPECT_EQ("test.html", res->body);
  3982. }
  3983. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3984. auto res = cli_.Get("/mount/dir/../test.html");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3987. }
  3988. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3989. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3990. ASSERT_TRUE(res);
  3991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3992. }
  3993. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3994. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3995. ASSERT_TRUE(res);
  3996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3997. }
  3998. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3999. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4002. }
  4003. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4004. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4007. }
  4008. TEST_F(ServerTest, PostMethod303) {
  4009. auto res = cli_.Post("/1", "body", "text/plain");
  4010. ASSERT_TRUE(res);
  4011. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4012. EXPECT_EQ("/2", res->get_header_value("Location"));
  4013. }
  4014. TEST_F(ServerTest, PostMethod303Redirect) {
  4015. cli_.set_follow_location(true);
  4016. auto res = cli_.Post("/1", "body", "text/plain");
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::OK_200, res->status);
  4019. EXPECT_EQ("redirected.", res->body);
  4020. EXPECT_EQ("/2", res->location);
  4021. }
  4022. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4023. auto res = cli_.Get("/dir/test.abcde");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4027. EXPECT_EQ("abcde", res->body);
  4028. }
  4029. TEST_F(ServerTest, StaticFileRange) {
  4030. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4033. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4034. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4035. EXPECT_EQ(true, res->has_header("Content-Range"));
  4036. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4037. EXPECT_EQ(std::string("cd"), res->body);
  4038. }
  4039. TEST_F(ServerTest, StaticFileRanges) {
  4040. auto res =
  4041. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4042. ASSERT_TRUE(res);
  4043. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4044. EXPECT_TRUE(
  4045. res->get_header_value("Content-Type")
  4046. .find(
  4047. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4048. 0);
  4049. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4050. }
  4051. TEST_F(ServerTest, StaticFileRangeHead) {
  4052. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4055. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4056. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4057. EXPECT_EQ(true, res->has_header("Content-Range"));
  4058. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4059. }
  4060. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4061. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4062. ASSERT_TRUE(res);
  4063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4064. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4065. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4068. res->get_header_value("Content-Range"));
  4069. EXPECT_EQ("LAST\n", res->body);
  4070. }
  4071. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4072. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4073. ASSERT_TRUE(res);
  4074. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4076. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4077. EXPECT_EQ(true, res->has_header("Content-Range"));
  4078. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4079. }
  4080. TEST_F(ServerTest, StaticFileBigFile) {
  4081. auto res = cli_.Get("/dir/1MB.txt");
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::OK_200, res->status);
  4084. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4085. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4086. }
  4087. TEST_F(ServerTest, InvalidBaseDirMount) {
  4088. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4089. }
  4090. TEST_F(ServerTest, Binary) {
  4091. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4092. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4093. "application/octet-stream");
  4094. ASSERT_TRUE(res);
  4095. ASSERT_EQ(StatusCode::OK_200, res->status);
  4096. ASSERT_EQ(4U, res->body.size());
  4097. res = cli_.Put("/binary", binary.data(), binary.size(),
  4098. "application/octet-stream");
  4099. ASSERT_TRUE(res);
  4100. ASSERT_EQ(StatusCode::OK_200, res->status);
  4101. ASSERT_EQ(4U, res->body.size());
  4102. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4103. "application/octet-stream");
  4104. ASSERT_TRUE(res);
  4105. ASSERT_EQ(StatusCode::OK_200, res->status);
  4106. ASSERT_EQ(4U, res->body.size());
  4107. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4108. "application/octet-stream");
  4109. ASSERT_TRUE(res);
  4110. ASSERT_EQ(StatusCode::OK_200, res->status);
  4111. ASSERT_EQ(4U, res->body.size());
  4112. }
  4113. TEST_F(ServerTest, BinaryString) {
  4114. auto binary = std::string("\x00\x01\x02\x03", 4);
  4115. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4116. ASSERT_TRUE(res);
  4117. ASSERT_EQ(StatusCode::OK_200, res->status);
  4118. ASSERT_EQ(4U, res->body.size());
  4119. res = cli_.Put("/binary", binary, "application/octet-stream");
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ(4U, res->body.size());
  4123. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4124. ASSERT_TRUE(res);
  4125. ASSERT_EQ(StatusCode::OK_200, res->status);
  4126. ASSERT_EQ(4U, res->body.size());
  4127. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4128. ASSERT_TRUE(res);
  4129. ASSERT_EQ(StatusCode::OK_200, res->status);
  4130. ASSERT_EQ(4U, res->body.size());
  4131. }
  4132. TEST_F(ServerTest, EmptyRequest) {
  4133. auto res = cli_.Get("");
  4134. ASSERT_TRUE(!res);
  4135. EXPECT_EQ(Error::Connection, res.error());
  4136. }
  4137. TEST_F(ServerTest, LongRequest) {
  4138. std::string request;
  4139. for (size_t i = 0; i < 545; i++) {
  4140. request += "/TooLongRequest";
  4141. }
  4142. request += "OK";
  4143. auto res = cli_.Get(request.c_str());
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4146. }
  4147. TEST_F(ServerTest, TooLongRequest) {
  4148. std::string request;
  4149. for (size_t i = 0; i < 546; i++) {
  4150. request += "/TooLongRequest";
  4151. }
  4152. request += "_NG";
  4153. auto start = std::chrono::high_resolution_clock::now();
  4154. cli_.set_keep_alive(true);
  4155. auto res = cli_.Get(request.c_str());
  4156. auto end = std::chrono::high_resolution_clock::now();
  4157. auto elapsed =
  4158. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4159. .count();
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4162. EXPECT_LE(elapsed, 1000);
  4163. EXPECT_EQ("close", res->get_header_value("Connection"));
  4164. EXPECT_FALSE(cli_.is_socket_open());
  4165. }
  4166. TEST_F(ServerTest, AlmostTooLongRequest) {
  4167. // test for #2046 - URI length check shouldn't include other content on req
  4168. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4169. // leading /, space, HTTP/1.1)
  4170. std::string request =
  4171. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4172. auto res = cli_.Get(request.c_str());
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4175. }
  4176. TEST_F(ServerTest, LongHeader) {
  4177. Request req;
  4178. req.method = "GET";
  4179. req.path = "/hi";
  4180. std::string host_and_port;
  4181. host_and_port += HOST;
  4182. host_and_port += ":";
  4183. host_and_port += std::to_string(PORT);
  4184. req.headers.emplace("Host", host_and_port.c_str());
  4185. req.headers.emplace("Accept", "*/*");
  4186. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4187. req.headers.emplace(
  4188. "Header-Name",
  4189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4217. "@@@@@@@@@@@@@@@@");
  4218. auto res = std::make_shared<Response>();
  4219. auto error = Error::Success;
  4220. auto ret = cli_.send(req, *res, error);
  4221. ASSERT_TRUE(ret);
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. }
  4224. TEST_F(ServerTest, LongQueryValue) {
  4225. auto start = std::chrono::high_resolution_clock::now();
  4226. cli_.set_keep_alive(true);
  4227. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4228. auto end = std::chrono::high_resolution_clock::now();
  4229. auto elapsed =
  4230. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4231. .count();
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4234. EXPECT_LE(elapsed, 1000);
  4235. EXPECT_EQ("close", res->get_header_value("Connection"));
  4236. EXPECT_FALSE(cli_.is_socket_open());
  4237. }
  4238. TEST_F(ServerTest, TooLongQueryValue) {
  4239. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4240. ASSERT_FALSE(res);
  4241. EXPECT_EQ(Error::Read, res.error());
  4242. }
  4243. TEST_F(ServerTest, TooLongHeader) {
  4244. Request req;
  4245. req.method = "GET";
  4246. req.path = "/hi";
  4247. std::string host_and_port;
  4248. host_and_port += HOST;
  4249. host_and_port += ":";
  4250. host_and_port += std::to_string(PORT);
  4251. req.headers.emplace("Host", host_and_port.c_str());
  4252. req.headers.emplace("Accept", "*/*");
  4253. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4254. req.headers.emplace(
  4255. "Header-Name",
  4256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4284. "@@@@@@@@@@@@@@@@@");
  4285. auto res = std::make_shared<Response>();
  4286. auto error = Error::Success;
  4287. auto ret = cli_.send(req, *res, error);
  4288. ASSERT_TRUE(ret);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. }
  4291. TEST_F(ServerTest, HeaderCountAtLimit) {
  4292. // Test with headers just under the 100 limit
  4293. httplib::Headers headers;
  4294. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4295. // This should keep us just under the 100 header limit
  4296. for (int i = 0; i < 95; i++) {
  4297. std::string name = "X-Test-Header-" + std::to_string(i);
  4298. std::string value = "value" + std::to_string(i);
  4299. headers.emplace(name, value);
  4300. }
  4301. // This should work fine as we're under the limit
  4302. auto res = cli_.Get("/hi", headers);
  4303. EXPECT_TRUE(res);
  4304. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4305. }
  4306. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4307. // Test with many headers to exceed the 100 limit
  4308. httplib::Headers headers;
  4309. // Add 150 headers to definitely exceed the 100 limit
  4310. for (int i = 0; i < 150; i++) {
  4311. std::string name = "X-Test-Header-" + std::to_string(i);
  4312. std::string value = "value" + std::to_string(i);
  4313. headers.emplace(name, value);
  4314. }
  4315. // This should fail due to exceeding header count limit
  4316. cli_.set_keep_alive(true);
  4317. auto res = cli_.Get("/hi", headers);
  4318. // The server should respond with 400 Bad Request
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4321. EXPECT_EQ("close", res->get_header_value("Connection"));
  4322. EXPECT_FALSE(cli_.is_socket_open());
  4323. }
  4324. TEST_F(ServerTest, PercentEncoding) {
  4325. auto res = cli_.Get("/e%6edwith%");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. }
  4329. TEST_F(ServerTest, PercentEncodingUnicode) {
  4330. auto res = cli_.Get("/e%u006edwith%");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. }
  4334. TEST_F(ServerTest, InvalidPercentEncoding) {
  4335. auto res = cli_.Get("/%endwith%");
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4338. }
  4339. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4340. auto res = cli_.Get("/%uendwith%");
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4343. }
  4344. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4345. auto res = cli_.Get("/hello?aaa=bbb%");
  4346. ASSERT_TRUE(res);
  4347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4348. }
  4349. TEST_F(ServerTest, PlusSignEncoding) {
  4350. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. EXPECT_EQ("a +b", res->body);
  4354. }
  4355. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4356. // This test simulates a potential DoS attack using many headers
  4357. // to verify our security fix prevents memory exhaustion
  4358. httplib::Headers attack_headers;
  4359. // Attempt to add many headers like an attacker would (200 headers to far
  4360. // exceed limit)
  4361. for (int i = 0; i < 200; i++) {
  4362. std::string name = "X-Attack-Header-" + std::to_string(i);
  4363. std::string value = "attack_payload_" + std::to_string(i);
  4364. attack_headers.emplace(name, value);
  4365. }
  4366. // Try to POST with excessive headers
  4367. cli_.set_keep_alive(true);
  4368. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4369. // Should either fail or return 400 Bad Request due to security limit
  4370. if (res) {
  4371. // If we get a response, it should be 400 Bad Request
  4372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4373. EXPECT_EQ("close", res->get_header_value("Connection"));
  4374. }
  4375. EXPECT_FALSE(cli_.is_socket_open());
  4376. }
  4377. TEST_F(ServerTest, MultipartFormData) {
  4378. UploadFormDataItems items = {
  4379. {"text1", "text default", "", ""},
  4380. {"text2", "aωb", "", ""},
  4381. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4382. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4383. {"file3", "", "", "application/octet-stream"},
  4384. {"file4", "", "", " application/json tmp-string "}};
  4385. auto res = cli_.Post("/multipart", items);
  4386. ASSERT_TRUE(res);
  4387. EXPECT_EQ(StatusCode::OK_200, res->status);
  4388. }
  4389. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4390. UploadFormDataItems items = {
  4391. {"text", "default text", "", ""},
  4392. {"multi_text1", "aaaaa", "", ""},
  4393. {"multi_text1", "bbbbb", "", ""},
  4394. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4395. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4396. "application/json"},
  4397. };
  4398. auto res = cli_.Post("/multipart/multi_file_values", items);
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4403. auto res = cli_.Get("/hi");
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4407. EXPECT_EQ("Hello World!", res->body);
  4408. }
  4409. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4410. Request req;
  4411. req.method = "POST";
  4412. req.path = "/chunked";
  4413. std::string host_and_port;
  4414. host_and_port += HOST;
  4415. host_and_port += ":";
  4416. host_and_port += std::to_string(PORT);
  4417. req.headers.emplace("Host", host_and_port.c_str());
  4418. req.headers.emplace("Accept", "*/*");
  4419. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4420. req.headers.emplace("Content-Type", "text/plain");
  4421. req.headers.emplace("Content-Length", "0");
  4422. req.headers.emplace(
  4423. "Transfer-Encoding",
  4424. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4425. // Client does not chunk, so make a chunked body manually.
  4426. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4427. auto res = std::make_shared<Response>();
  4428. auto error = Error::Success;
  4429. auto ret = cli_.send(req, *res, error);
  4430. ASSERT_TRUE(ret);
  4431. EXPECT_EQ(StatusCode::OK_200, res->status);
  4432. }
  4433. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4434. // rather than treat them as valid lengths.
  4435. template <typename ClientT>
  4436. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4437. Request req;
  4438. req.method = "POST";
  4439. req.path = "/chunked";
  4440. std::string host_and_port;
  4441. host_and_port += HOST;
  4442. host_and_port += ":";
  4443. host_and_port += std::to_string(PORT);
  4444. req.headers.emplace("Host", host_and_port.c_str());
  4445. req.headers.emplace("Content-Length", "0");
  4446. req.headers.emplace("Transfer-Encoding", "chunked");
  4447. req.body = body;
  4448. auto res = std::make_shared<Response>();
  4449. auto error = Error::Success;
  4450. ASSERT_TRUE(cli.send(req, *res, error));
  4451. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4452. }
  4453. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4454. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4455. }
  4456. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4457. expect_chunked_body_rejected(
  4458. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4459. }
  4460. TEST_F(ServerTest, GetStreamed2) {
  4461. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4462. ASSERT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4464. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4465. EXPECT_EQ(true, res->has_header("Content-Range"));
  4466. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4467. EXPECT_EQ(std::string("ab"), res->body);
  4468. }
  4469. TEST_F(ServerTest, GetStreamed) {
  4470. auto res = cli_.Get("/streamed");
  4471. ASSERT_TRUE(res);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4474. EXPECT_EQ(std::string("aaabbb"), res->body);
  4475. }
  4476. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4477. auto res =
  4478. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ(false, res->has_header("Content-Length"));
  4482. EXPECT_EQ(false, res->has_header("Content-Range"));
  4483. EXPECT_EQ(std::string("abcdefg"), res->body);
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithRange1) {
  4486. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4487. ASSERT_TRUE(res);
  4488. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4489. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4490. EXPECT_EQ(true, res->has_header("Content-Range"));
  4491. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4492. EXPECT_EQ(std::string("def"), res->body);
  4493. }
  4494. TEST_F(ServerTest, GetStreamedWithRange2) {
  4495. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4496. ASSERT_TRUE(res);
  4497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4498. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4499. EXPECT_EQ(true, res->has_header("Content-Range"));
  4500. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4501. EXPECT_EQ(std::string("bcdefg"), res->body);
  4502. }
  4503. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4504. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4507. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4508. EXPECT_EQ(true, res->has_header("Content-Range"));
  4509. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4510. EXPECT_EQ(std::string("efg"), res->body);
  4511. }
  4512. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4513. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4516. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4517. EXPECT_EQ(false, res->has_header("Content-Range"));
  4518. EXPECT_EQ(0U, res->body.size());
  4519. }
  4520. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4521. auto res = cli_.Get("/streamed-with-range",
  4522. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4523. "92233720368547758079223372036854775807"}});
  4524. ASSERT_TRUE(res);
  4525. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4526. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4527. EXPECT_EQ(false, res->has_header("Content-Range"));
  4528. EXPECT_EQ(0U, res->body.size());
  4529. }
  4530. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4531. auto res = cli_.Get(
  4532. "/with-range",
  4533. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4534. {"Accept-Encoding", ""}});
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4537. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4538. EXPECT_EQ(true, res->has_header("Content-Range"));
  4539. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4540. EXPECT_EQ(std::string("abcdefg"), res->body);
  4541. }
  4542. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4543. auto res = cli_.Get("/with-range", {
  4544. {"Range", "bytes=0-"},
  4545. {"Accept-Encoding", ""},
  4546. });
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4549. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4550. EXPECT_EQ(true, res->has_header("Content-Range"));
  4551. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4552. EXPECT_EQ(std::string("abcdefg"), res->body);
  4553. }
  4554. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4555. auto res =
  4556. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4557. ASSERT_TRUE(res);
  4558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4559. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4560. EXPECT_EQ(false, res->has_header("Content-Range"));
  4561. EXPECT_EQ(267U, res->body.size());
  4562. // Check that both range contents are present
  4563. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4564. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4565. // Check that Content-Range headers are present for both ranges
  4566. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4567. std::string::npos);
  4568. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4569. std::string::npos);
  4570. }
  4571. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4572. Ranges ranges;
  4573. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4574. ranges.emplace_back(0, -1);
  4575. }
  4576. auto res =
  4577. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4580. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4581. EXPECT_EQ(false, res->has_header("Content-Range"));
  4582. EXPECT_EQ(0U, res->body.size());
  4583. }
  4584. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4585. auto res =
  4586. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4587. ASSERT_TRUE(res);
  4588. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4589. EXPECT_EQ(5U, res->body.size());
  4590. // Check that overlapping ranges are coalesced into a single range
  4591. EXPECT_EQ("bcdef", res->body);
  4592. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4593. // Should be single range, not multipart
  4594. EXPECT_TRUE(res->has_header("Content-Range"));
  4595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4596. }
  4597. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4598. auto res =
  4599. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4602. EXPECT_EQ(268U, res->body.size());
  4603. // Check that both range contents are present
  4604. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4605. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4606. // Check that Content-Range headers are present for both ranges
  4607. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4608. std::string::npos);
  4609. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4610. std::string::npos);
  4611. }
  4612. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4613. auto res =
  4614. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ(269U, res->body.size());
  4618. // Check that both duplicate range contents are present
  4619. size_t first_abc = res->body.find("abc\r\n");
  4620. EXPECT_TRUE(first_abc != std::string::npos);
  4621. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4622. EXPECT_TRUE(second_abc != std::string::npos);
  4623. // Check that Content-Range headers are present for both ranges
  4624. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4625. EXPECT_TRUE(first_range != std::string::npos);
  4626. size_t second_range =
  4627. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4628. EXPECT_TRUE(second_range != std::string::npos);
  4629. }
  4630. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4631. auto res = cli_.Get("/streamed-with-range?error",
  4632. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4633. ASSERT_TRUE(res);
  4634. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4635. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4636. EXPECT_EQ(false, res->has_header("Content-Range"));
  4637. EXPECT_EQ(0U, res->body.size());
  4638. }
  4639. TEST_F(ServerTest, GetStreamedEndless) {
  4640. uint64_t offset = 0;
  4641. auto res = cli_.Get("/streamed-cancel",
  4642. [&](const char * /*data*/, uint64_t data_length) {
  4643. if (offset < 100) {
  4644. offset += data_length;
  4645. return true;
  4646. }
  4647. return false;
  4648. });
  4649. ASSERT_TRUE(!res);
  4650. EXPECT_EQ(Error::Canceled, res.error());
  4651. }
  4652. TEST_F(ServerTest, ClientStop) {
  4653. std::atomic_size_t count{4};
  4654. std::vector<std::thread> threads;
  4655. for (auto i = count.load(); i != 0; --i) {
  4656. threads.emplace_back([&]() {
  4657. auto res = cli_.Get("/streamed-cancel",
  4658. [&](const char *, uint64_t) { return true; });
  4659. --count;
  4660. ASSERT_TRUE(!res);
  4661. EXPECT_TRUE(res.error() == Error::Canceled ||
  4662. res.error() == Error::Read || res.error() == Error::Write);
  4663. });
  4664. }
  4665. std::this_thread::sleep_for(std::chrono::seconds(2));
  4666. while (count != 0) {
  4667. cli_.stop();
  4668. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4669. }
  4670. for (auto &t : threads) {
  4671. t.join();
  4672. }
  4673. }
  4674. TEST_F(ServerTest, GetWithRange1) {
  4675. auto res = cli_.Get("/with-range", {
  4676. make_range_header({{3, 5}}),
  4677. {"Accept-Encoding", ""},
  4678. });
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4681. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4682. EXPECT_EQ(true, res->has_header("Content-Range"));
  4683. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4684. EXPECT_EQ(std::string("def"), res->body);
  4685. }
  4686. TEST_F(ServerTest, GetWithRange2) {
  4687. auto res = cli_.Get("/with-range", {
  4688. make_range_header({{1, -1}}),
  4689. {"Accept-Encoding", ""},
  4690. });
  4691. ASSERT_TRUE(res);
  4692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4693. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4694. EXPECT_EQ(true, res->has_header("Content-Range"));
  4695. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4696. EXPECT_EQ(std::string("bcdefg"), res->body);
  4697. }
  4698. TEST_F(ServerTest, GetWithRange3) {
  4699. auto res = cli_.Get("/with-range", {
  4700. make_range_header({{0, 0}}),
  4701. {"Accept-Encoding", ""},
  4702. });
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4705. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4706. EXPECT_EQ(true, res->has_header("Content-Range"));
  4707. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4708. EXPECT_EQ(std::string("a"), res->body);
  4709. }
  4710. TEST_F(ServerTest, GetWithRange4) {
  4711. auto res = cli_.Get("/with-range", {
  4712. make_range_header({{-1, 2}}),
  4713. {"Accept-Encoding", ""},
  4714. });
  4715. ASSERT_TRUE(res);
  4716. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4717. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4718. EXPECT_EQ(true, res->has_header("Content-Range"));
  4719. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4720. EXPECT_EQ(std::string("fg"), res->body);
  4721. }
  4722. TEST_F(ServerTest, GetWithRange5) {
  4723. auto res = cli_.Get("/with-range", {
  4724. make_range_header({{0, 5}}),
  4725. {"Accept-Encoding", ""},
  4726. });
  4727. ASSERT_TRUE(res);
  4728. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4729. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4730. EXPECT_EQ(true, res->has_header("Content-Range"));
  4731. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4732. EXPECT_EQ(std::string("abcdef"), res->body);
  4733. }
  4734. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4735. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4738. }
  4739. TEST_F(ServerTest, GetWithRangeMultipart) {
  4740. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4743. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4744. EXPECT_EQ(false, res->has_header("Content-Range"));
  4745. EXPECT_EQ(267U, res->body.size());
  4746. }
  4747. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4748. auto res =
  4749. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4750. ASSERT_TRUE(res);
  4751. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4752. }
  4753. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4754. auto res = cli_.Get("/with-range-customized-response",
  4755. {{make_range_header({{1, 2}})}});
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4758. EXPECT_EQ(true, res->has_header("Content-Length"));
  4759. EXPECT_EQ(false, res->has_header("Content-Range"));
  4760. EXPECT_EQ(JSON_DATA, res->body);
  4761. }
  4762. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4763. auto res = cli_.Get("/with-range-customized-response",
  4764. {{make_range_header({{1, 2}, {4, 5}})}});
  4765. ASSERT_TRUE(res);
  4766. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4767. EXPECT_EQ(true, res->has_header("Content-Length"));
  4768. EXPECT_EQ(false, res->has_header("Content-Range"));
  4769. EXPECT_EQ(JSON_DATA, res->body);
  4770. }
  4771. TEST_F(ServerTest, Issue1772) {
  4772. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4773. ASSERT_TRUE(res);
  4774. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4775. }
  4776. TEST_F(ServerTest, Issue609) {
  4777. auto res = cli_.Delete("/issue609");
  4778. ASSERT_TRUE(res);
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. EXPECT_EQ(std::string("ok"), res->body);
  4781. }
  4782. TEST_F(ServerTest, GetStreamedChunked) {
  4783. auto res = cli_.Get("/streamed-chunked");
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ(std::string("123456789"), res->body);
  4787. }
  4788. TEST_F(ServerTest, GetStreamedChunked2) {
  4789. auto res = cli_.Get("/streamed-chunked2");
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::OK_200, res->status);
  4792. EXPECT_EQ(std::string("123456789"), res->body);
  4793. }
  4794. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4795. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. EXPECT_EQ(std::string("123456789"), res->body);
  4799. EXPECT_TRUE(res->has_header("Trailer"));
  4800. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4801. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4802. // Trailers are now stored separately from headers (security fix)
  4803. EXPECT_EQ(2U, res->trailers.size());
  4804. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4805. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4806. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4807. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4808. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4809. // Verify trailers are NOT in headers (security verification)
  4810. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4811. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4812. }
  4813. TEST_F(ServerTest, LargeChunkedPost) {
  4814. Request req;
  4815. req.method = "POST";
  4816. req.path = "/large-chunked";
  4817. std::string host_and_port;
  4818. host_and_port += HOST;
  4819. host_and_port += ":";
  4820. host_and_port += std::to_string(PORT);
  4821. req.headers.emplace("Host", host_and_port.c_str());
  4822. req.headers.emplace("Accept", "*/*");
  4823. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4824. req.headers.emplace("Content-Type", "text/plain");
  4825. req.headers.emplace("Content-Length", "0");
  4826. req.headers.emplace("Transfer-Encoding", "chunked");
  4827. std::string long_string(30 * 1024u, 'a');
  4828. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4829. // Attempt to make a large enough post to exceed OS buffers, to test that
  4830. // the server handles short reads if the full chunk data isn't available.
  4831. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4832. auto res = std::make_shared<Response>();
  4833. auto error = Error::Success;
  4834. auto ret = cli_.send(req, *res, error);
  4835. ASSERT_TRUE(ret);
  4836. EXPECT_EQ(StatusCode::OK_200, res->status);
  4837. }
  4838. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4839. auto res = cli_.Get("/remote_addr");
  4840. ASSERT_TRUE(res);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4843. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4844. }
  4845. TEST_F(ServerTest, GetMethodLocalAddr) {
  4846. auto res = cli_.Get("/local_addr");
  4847. ASSERT_TRUE(res);
  4848. EXPECT_EQ(StatusCode::OK_200, res->status);
  4849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4850. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4851. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4852. }
  4853. TEST_F(ServerTest, HTTPResponseSplitting) {
  4854. auto res = cli_.Get("/http_response_splitting");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. }
  4858. TEST_F(ServerTest, SlowRequest) {
  4859. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4860. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4861. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4862. }
  4863. #if 0
  4864. TEST_F(ServerTest, SlowPost) {
  4865. char buffer[64 * 1024];
  4866. memset(buffer, 0x42, sizeof(buffer));
  4867. auto res = cli_.Post(
  4868. "/slowpost", 64 * 1024 * 1024,
  4869. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4870. auto ret = sink.write(buffer, sizeof(buffer));
  4871. EXPECT_TRUE(ret);
  4872. return true;
  4873. },
  4874. "text/plain");
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. TEST_F(ServerTest, SlowPostFail) {
  4879. char buffer[64 * 1024];
  4880. memset(buffer, 0x42, sizeof(buffer));
  4881. cli_.set_write_timeout(std::chrono::seconds(0));
  4882. auto res = cli_.Post(
  4883. "/slowpost", 64 * 1024 * 1024,
  4884. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4885. sink.write(buffer, sizeof(buffer));
  4886. return true;
  4887. },
  4888. "text/plain");
  4889. ASSERT_TRUE(!res);
  4890. EXPECT_EQ(Error::Write, res.error());
  4891. }
  4892. #endif
  4893. TEST_F(ServerTest, Put) {
  4894. auto res = cli_.Put("/put", "PUT", "text/plain");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("PUT", res->body);
  4898. }
  4899. TEST_F(ServerTest, PutWithContentProvider) {
  4900. auto res = cli_.Put(
  4901. "/put", 3,
  4902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4903. sink.os << "PUT";
  4904. return true;
  4905. },
  4906. "text/plain");
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("PUT", res->body);
  4910. }
  4911. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4912. auto res = cli_.Post(
  4913. "/post", 42,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4915. return false;
  4916. },
  4917. "text/plain");
  4918. ASSERT_TRUE(!res);
  4919. EXPECT_EQ(Error::Canceled, res.error());
  4920. }
  4921. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4922. auto res = cli_.Put(
  4923. "/put",
  4924. [](size_t /*offset*/, DataSink &sink) {
  4925. sink.os << "PUT";
  4926. sink.done();
  4927. return true;
  4928. },
  4929. "text/plain");
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. EXPECT_EQ("PUT", res->body);
  4933. }
  4934. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4935. auto res = cli_.Post(
  4936. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4937. "text/plain");
  4938. ASSERT_TRUE(!res);
  4939. EXPECT_EQ(Error::Canceled, res.error());
  4940. }
  4941. TEST_F(ServerTest, PostLoopBack) {
  4942. std::string body;
  4943. auto res = cli_.Post(
  4944. "/post-loopback", 9,
  4945. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4946. EXPECT_EQ(9u, length);
  4947. sink.write("123", 3);
  4948. sink.write("456", 3);
  4949. sink.write("789", 3);
  4950. return true;
  4951. },
  4952. "text/plain",
  4953. [&body](const char *data, size_t data_length) {
  4954. body.append(data, data_length);
  4955. return true;
  4956. });
  4957. ASSERT_TRUE(res);
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ("123456789", body);
  4960. }
  4961. TEST_F(ServerTest, PutLoopBack) {
  4962. std::string body;
  4963. auto res = cli_.Put(
  4964. "/put-loopback", 9,
  4965. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4966. EXPECT_EQ(9u, length);
  4967. sink.write("123", 3);
  4968. sink.write("456", 3);
  4969. sink.write("789", 3);
  4970. return true;
  4971. },
  4972. "text/plain",
  4973. [&body](const char *data, size_t data_length) {
  4974. body.append(data, data_length);
  4975. return true;
  4976. });
  4977. ASSERT_TRUE(res);
  4978. EXPECT_EQ(StatusCode::OK_200, res->status);
  4979. EXPECT_EQ("123456789", body);
  4980. }
  4981. TEST_F(ServerTest, PatchLoopBack) {
  4982. std::string body;
  4983. auto res = cli_.Patch(
  4984. "/patch-loopback", 9,
  4985. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4986. EXPECT_EQ(9u, length);
  4987. sink.write("123", 3);
  4988. sink.write("456", 3);
  4989. sink.write("789", 3);
  4990. return true;
  4991. },
  4992. "text/plain",
  4993. [&body](const char *data, size_t data_length) {
  4994. body.append(data, data_length);
  4995. return true;
  4996. });
  4997. ASSERT_TRUE(res);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. EXPECT_EQ("123456789", body);
  5000. }
  5001. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5002. std::string body;
  5003. auto res = cli_.Post(
  5004. "/post-loopback",
  5005. [](size_t /*offset*/, DataSink &sink) {
  5006. sink.write("123", 3);
  5007. sink.write("456", 3);
  5008. sink.write("789", 3);
  5009. sink.done();
  5010. return true;
  5011. },
  5012. "text/plain",
  5013. [&body](const char *data, size_t data_length) {
  5014. body.append(data, data_length);
  5015. return true;
  5016. });
  5017. ASSERT_TRUE(res);
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. EXPECT_EQ("123456789", body);
  5020. }
  5021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5022. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5023. cli_.set_compress(true);
  5024. auto res = cli_.Put(
  5025. "/put", 3,
  5026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5027. sink.os << "PUT";
  5028. return true;
  5029. },
  5030. "text/plain");
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ(StatusCode::OK_200, res->status);
  5033. EXPECT_EQ("PUT", res->body);
  5034. }
  5035. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5036. cli_.set_compress(true);
  5037. auto res = cli_.Post(
  5038. "/post", 42,
  5039. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5040. return false;
  5041. },
  5042. "text/plain");
  5043. ASSERT_TRUE(!res);
  5044. EXPECT_EQ(Error::Canceled, res.error());
  5045. }
  5046. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5047. cli_.set_compress(true);
  5048. auto res = cli_.Put(
  5049. "/put",
  5050. [](size_t /*offset*/, DataSink &sink) {
  5051. sink.os << "PUT";
  5052. sink.done();
  5053. return true;
  5054. },
  5055. "text/plain");
  5056. ASSERT_TRUE(res);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("PUT", res->body);
  5059. }
  5060. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5061. cli_.set_compress(true);
  5062. auto res = cli_.Post(
  5063. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5064. "text/plain");
  5065. ASSERT_TRUE(!res);
  5066. EXPECT_EQ(Error::Canceled, res.error());
  5067. }
  5068. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5069. cli_.set_compress(true);
  5070. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5071. ASSERT_TRUE(res);
  5072. EXPECT_EQ(StatusCode::OK_200, res->status);
  5073. EXPECT_EQ(LARGE_DATA, res->body);
  5074. }
  5075. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5076. #ifdef CPPHTTPLIB_SSL_ENABLED
  5077. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5078. Client cli(s.c_str());
  5079. cli.enable_server_certificate_verification(false);
  5080. #else
  5081. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5082. Client cli(s.c_str());
  5083. #endif
  5084. cli.set_compress(true);
  5085. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5086. ASSERT_TRUE(res);
  5087. EXPECT_EQ(StatusCode::OK_200, res->status);
  5088. EXPECT_EQ(LARGE_DATA, res->body);
  5089. // The compressed size should be less than a 10th of the original. May vary
  5090. // depending on the zlib library.
  5091. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5092. static_cast<uint64_t>(10 * 1024 * 1024));
  5093. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5094. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5095. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5096. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5097. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5098. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5099. #endif
  5100. }
  5101. TEST_F(ServerTest, PutContentWithDeflate) {
  5102. cli_.set_compress(false);
  5103. Headers headers;
  5104. headers.emplace("Content-Encoding", "deflate");
  5105. // PUT in deflate format:
  5106. auto res = cli_.Put("/put", headers,
  5107. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ("PUT", res->body);
  5111. }
  5112. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5113. Headers headers;
  5114. headers.emplace("Accept-Encoding", "gzip, deflate");
  5115. auto res = cli_.Get("/streamed-chunked", headers);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ(std::string("123456789"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5121. Headers headers;
  5122. headers.emplace("Accept-Encoding", "gzip, deflate");
  5123. auto res = cli_.Get("/streamed-chunked2", headers);
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ(std::string("123456789"), res->body);
  5127. }
  5128. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5129. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5130. ASSERT_TRUE(res);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. }
  5133. TEST(GzipDecompressor, ChunkedDecompression) {
  5134. std::string data;
  5135. for (size_t i = 0; i < 32 * 1024; ++i) {
  5136. data.push_back(static_cast<char>('a' + i % 26));
  5137. }
  5138. std::string compressed_data;
  5139. {
  5140. httplib::detail::gzip_compressor compressor;
  5141. bool result = compressor.compress(
  5142. data.data(), data.size(),
  5143. /*last=*/true,
  5144. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5145. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5146. compressed_data_size);
  5147. return true;
  5148. });
  5149. ASSERT_TRUE(result);
  5150. }
  5151. std::string decompressed_data;
  5152. {
  5153. httplib::detail::gzip_decompressor decompressor;
  5154. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5155. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5156. size_t chunk_size = 130;
  5157. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5158. chunk_begin += chunk_size) {
  5159. size_t current_chunk_size =
  5160. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5161. bool result = decompressor.decompress(
  5162. compressed_data.data() + chunk_begin, current_chunk_size,
  5163. [&](const char *decompressed_data_chunk,
  5164. size_t decompressed_data_chunk_size) {
  5165. decompressed_data.insert(decompressed_data.size(),
  5166. decompressed_data_chunk,
  5167. decompressed_data_chunk_size);
  5168. return true;
  5169. });
  5170. ASSERT_TRUE(result);
  5171. }
  5172. }
  5173. ASSERT_EQ(data, decompressed_data);
  5174. }
  5175. TEST(GzipDecompressor, DeflateDecompression) {
  5176. std::string original_text = "Raw deflate without gzip";
  5177. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5178. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5179. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5180. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5181. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5182. std::string decompressed_data;
  5183. {
  5184. httplib::detail::gzip_decompressor decompressor;
  5185. bool result = decompressor.decompress(
  5186. compressed_data.data(), compressed_data.size(),
  5187. [&](const char *decompressed_data_chunk,
  5188. size_t decompressed_data_chunk_size) {
  5189. decompressed_data.insert(decompressed_data.size(),
  5190. decompressed_data_chunk,
  5191. decompressed_data_chunk_size);
  5192. return true;
  5193. });
  5194. ASSERT_TRUE(result);
  5195. }
  5196. ASSERT_EQ(original_text, decompressed_data);
  5197. }
  5198. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5199. std::string original_text = "Raw deflate without gzip";
  5200. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5201. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5202. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5203. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5204. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5205. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5206. std::string decompressed_data;
  5207. {
  5208. httplib::detail::gzip_decompressor decompressor;
  5209. bool result = decompressor.decompress(
  5210. compressed_data.data(), compressed_data.size(),
  5211. [&](const char *decompressed_data_chunk,
  5212. size_t decompressed_data_chunk_size) {
  5213. decompressed_data.insert(decompressed_data.size(),
  5214. decompressed_data_chunk,
  5215. decompressed_data_chunk_size);
  5216. return true;
  5217. });
  5218. ASSERT_TRUE(result);
  5219. }
  5220. ASSERT_EQ(original_text, decompressed_data);
  5221. }
  5222. #endif
  5223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5224. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5225. Headers headers;
  5226. headers.emplace("Accept-Encoding", "br");
  5227. auto res = cli_.Get("/streamed-chunked", headers);
  5228. ASSERT_TRUE(res);
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. EXPECT_EQ(std::string("123456789"), res->body);
  5231. }
  5232. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5233. Headers headers;
  5234. headers.emplace("Accept-Encoding", "br");
  5235. auto res = cli_.Get("/streamed-chunked2", headers);
  5236. ASSERT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. EXPECT_EQ(std::string("123456789"), res->body);
  5239. }
  5240. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5241. cli_.set_compress(true);
  5242. auto res = cli_.Put(
  5243. "/put", 3,
  5244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5245. sink.os << "PUT";
  5246. return true;
  5247. },
  5248. "text/plain");
  5249. ASSERT_TRUE(res);
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. EXPECT_EQ("PUT", res->body);
  5252. }
  5253. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5254. cli_.set_compress(true);
  5255. auto res = cli_.Put(
  5256. "/put",
  5257. [](size_t /*offset*/, DataSink &sink) {
  5258. sink.os << "PUT";
  5259. sink.done();
  5260. return true;
  5261. },
  5262. "text/plain");
  5263. ASSERT_TRUE(res);
  5264. EXPECT_EQ(StatusCode::OK_200, res->status);
  5265. EXPECT_EQ("PUT", res->body);
  5266. }
  5267. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5268. cli_.set_compress(true);
  5269. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ(LARGE_DATA, res->body);
  5273. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5274. }
  5275. #endif
  5276. TEST_F(ServerTest, Patch) {
  5277. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5278. ASSERT_TRUE(res);
  5279. EXPECT_EQ(StatusCode::OK_200, res->status);
  5280. EXPECT_EQ("PATCH", res->body);
  5281. }
  5282. TEST_F(ServerTest, Delete) {
  5283. auto res = cli_.Delete("/delete");
  5284. ASSERT_TRUE(res);
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("DELETE", res->body);
  5287. }
  5288. TEST_F(ServerTest, DeleteContentReceiver) {
  5289. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("content", res->body);
  5293. }
  5294. TEST_F(ServerTest, Options) {
  5295. auto res = cli_.Options("*");
  5296. ASSERT_TRUE(res);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5299. EXPECT_TRUE(res->body.empty());
  5300. }
  5301. TEST_F(ServerTest, URL) {
  5302. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5303. ASSERT_TRUE(res);
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. }
  5306. TEST_F(ServerTest, ArrayParam) {
  5307. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::OK_200, res->status);
  5310. }
  5311. TEST_F(ServerTest, ArrayParamValues) {
  5312. auto res =
  5313. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. }
  5317. TEST_F(ServerTest, NoMultipleHeaders) {
  5318. Headers headers = {{"Content-Length", "5"}};
  5319. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5320. "text/plain");
  5321. ASSERT_TRUE(res);
  5322. EXPECT_EQ(StatusCode::OK_200, res->status);
  5323. }
  5324. TEST_F(ServerTest, PostContentReceiver) {
  5325. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5326. ASSERT_TRUE(res);
  5327. ASSERT_EQ(StatusCode::OK_200, res->status);
  5328. ASSERT_EQ("content", res->body);
  5329. }
  5330. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5331. UploadFormDataItems items = {
  5332. {"text1", "text default", "", ""},
  5333. {"text2", "aωb", "", ""},
  5334. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5335. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5336. {"file3", "", "", "application/octet-stream"},
  5337. };
  5338. auto res = cli_.Post("/content_receiver", items);
  5339. ASSERT_TRUE(res);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. }
  5342. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5343. UploadFormDataItems items = {
  5344. {"text1", "text default", "", ""},
  5345. {"text2", "aωb", "", ""},
  5346. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5347. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5348. {"file3", "", "", "application/octet-stream"},
  5349. };
  5350. auto boundary = std::string("+++++");
  5351. std::string body;
  5352. for (const auto &item : items) {
  5353. body += "--" + boundary + "\r\n";
  5354. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5355. if (!item.filename.empty()) {
  5356. body += "; filename=\"" + item.filename + "\"";
  5357. }
  5358. body += "\r\n";
  5359. if (!item.content_type.empty()) {
  5360. body += "Content-Type: " + item.content_type + "\r\n";
  5361. }
  5362. body += "\r\n";
  5363. body += item.content + "\r\n";
  5364. }
  5365. body += "--" + boundary + "--\r\n";
  5366. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5367. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, PostContentReceiverGzip) {
  5372. cli_.set_compress(true);
  5373. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5374. ASSERT_TRUE(res);
  5375. ASSERT_EQ(StatusCode::OK_200, res->status);
  5376. ASSERT_EQ("content", res->body);
  5377. }
  5378. TEST_F(ServerTest, PutContentReceiver) {
  5379. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5380. ASSERT_TRUE(res);
  5381. ASSERT_EQ(StatusCode::OK_200, res->status);
  5382. ASSERT_EQ("content", res->body);
  5383. }
  5384. TEST_F(ServerTest, PatchContentReceiver) {
  5385. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5386. ASSERT_TRUE(res);
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. ASSERT_EQ("content", res->body);
  5389. }
  5390. template <typename ClientType>
  5391. void TestWithHeadersAndContentReceiver(
  5392. ClientType &cli,
  5393. std::function<Result(ClientType &, const std::string &, const Headers &,
  5394. const std::string &, const std::string &,
  5395. ContentReceiver, DownloadProgress)>
  5396. request_func) {
  5397. Headers headers;
  5398. headers.emplace("X-Custom-Header", "test-value");
  5399. std::string received_body;
  5400. auto res = request_func(
  5401. cli, "/content_receiver", headers, "content", "application/json",
  5402. [&](const char *data, size_t data_length) {
  5403. received_body.append(data, data_length);
  5404. return true;
  5405. },
  5406. nullptr);
  5407. ASSERT_TRUE(res);
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. EXPECT_EQ("content", received_body);
  5410. }
  5411. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5412. #ifdef CPPHTTPLIB_SSL_ENABLED
  5413. using ClientT = SSLClient;
  5414. #else
  5415. using ClientT = Client;
  5416. #endif
  5417. TestWithHeadersAndContentReceiver<ClientT>(
  5418. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5419. const std::string &body, const std::string &content_type,
  5420. ContentReceiver receiver, DownloadProgress progress) {
  5421. return cli.Post(path, headers, body, content_type, receiver, progress);
  5422. });
  5423. }
  5424. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5425. #ifdef CPPHTTPLIB_SSL_ENABLED
  5426. using ClientT = SSLClient;
  5427. #else
  5428. using ClientT = Client;
  5429. #endif
  5430. TestWithHeadersAndContentReceiver<ClientT>(
  5431. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5432. const std::string &body, const std::string &content_type,
  5433. ContentReceiver receiver, DownloadProgress progress) {
  5434. return cli.Put(path, headers, body, content_type, receiver, progress);
  5435. });
  5436. }
  5437. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5438. #ifdef CPPHTTPLIB_SSL_ENABLED
  5439. using ClientT = SSLClient;
  5440. #else
  5441. using ClientT = Client;
  5442. #endif
  5443. TestWithHeadersAndContentReceiver<ClientT>(
  5444. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5445. const std::string &body, const std::string &content_type,
  5446. ContentReceiver receiver, DownloadProgress progress) {
  5447. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5448. });
  5449. }
  5450. template <typename ClientType>
  5451. void TestWithHeadersAndContentReceiverWithProgress(
  5452. ClientType &cli,
  5453. std::function<Result(ClientType &, const std::string &, const Headers &,
  5454. const std::string &, const std::string &,
  5455. ContentReceiver, DownloadProgress)>
  5456. request_func) {
  5457. Headers headers;
  5458. headers.emplace("X-Test-Header", "progress-test");
  5459. std::string received_body;
  5460. auto progress_called = false;
  5461. auto res = request_func(
  5462. cli, "/content_receiver", headers, "content", "text/plain",
  5463. [&](const char *data, size_t data_length) {
  5464. received_body.append(data, data_length);
  5465. return true;
  5466. },
  5467. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5468. progress_called = true;
  5469. return true;
  5470. });
  5471. ASSERT_TRUE(res);
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. EXPECT_EQ("content", received_body);
  5474. EXPECT_TRUE(progress_called);
  5475. }
  5476. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5477. #ifdef CPPHTTPLIB_SSL_ENABLED
  5478. using ClientT = SSLClient;
  5479. #else
  5480. using ClientT = Client;
  5481. #endif
  5482. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5483. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5484. const std::string &body, const std::string &content_type,
  5485. ContentReceiver receiver, DownloadProgress progress) {
  5486. return cli.Post(path, headers, body, content_type, receiver, progress);
  5487. });
  5488. }
  5489. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5490. #ifdef CPPHTTPLIB_SSL_ENABLED
  5491. using ClientT = SSLClient;
  5492. #else
  5493. using ClientT = Client;
  5494. #endif
  5495. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5496. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5497. const std::string &body, const std::string &content_type,
  5498. ContentReceiver receiver, DownloadProgress progress) {
  5499. return cli.Put(path, headers, body, content_type, receiver, progress);
  5500. });
  5501. }
  5502. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5503. #ifdef CPPHTTPLIB_SSL_ENABLED
  5504. using ClientT = SSLClient;
  5505. #else
  5506. using ClientT = Client;
  5507. #endif
  5508. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5509. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5510. const std::string &body, const std::string &content_type,
  5511. ContentReceiver receiver, DownloadProgress progress) {
  5512. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5513. });
  5514. }
  5515. template <typename ClientType>
  5516. void TestWithHeadersAndContentReceiverError(
  5517. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5518. const Headers &, const std::string &,
  5519. const std::string &, ContentReceiver)>
  5520. request_func) {
  5521. Headers headers;
  5522. headers.emplace("X-Error-Test", "true");
  5523. std::string received_body;
  5524. auto receiver_failed = false;
  5525. auto res =
  5526. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5527. [&](const char *data, size_t data_length) {
  5528. received_body.append(data, data_length);
  5529. receiver_failed = true;
  5530. return false;
  5531. });
  5532. ASSERT_FALSE(res);
  5533. EXPECT_TRUE(receiver_failed);
  5534. }
  5535. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5536. #ifdef CPPHTTPLIB_SSL_ENABLED
  5537. using ClientT = SSLClient;
  5538. #else
  5539. using ClientT = Client;
  5540. #endif
  5541. TestWithHeadersAndContentReceiverError<ClientT>(
  5542. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5543. const std::string &body, const std::string &content_type,
  5544. ContentReceiver receiver) {
  5545. return cli.Post(path, headers, body, content_type, receiver);
  5546. });
  5547. }
  5548. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5549. #ifdef CPPHTTPLIB_SSL_ENABLED
  5550. using ClientT = SSLClient;
  5551. #else
  5552. using ClientT = Client;
  5553. #endif
  5554. TestWithHeadersAndContentReceiverError<ClientT>(
  5555. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5556. const std::string &body, const std::string &content_type,
  5557. ContentReceiver receiver) {
  5558. return cli.Put(path, headers, body, content_type, receiver);
  5559. });
  5560. }
  5561. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5562. #ifdef CPPHTTPLIB_SSL_ENABLED
  5563. using ClientT = SSLClient;
  5564. #else
  5565. using ClientT = Client;
  5566. #endif
  5567. TestWithHeadersAndContentReceiverError<ClientT>(
  5568. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5569. const std::string &body, const std::string &content_type,
  5570. ContentReceiver receiver) {
  5571. return cli.Patch(path, headers, body, content_type, receiver);
  5572. });
  5573. }
  5574. TEST_F(ServerTest, PostQueryStringAndBody) {
  5575. auto res =
  5576. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5577. ASSERT_TRUE(res);
  5578. ASSERT_EQ(StatusCode::OK_200, res->status);
  5579. }
  5580. TEST_F(ServerTest, HTTP2Magic) {
  5581. Request req;
  5582. req.method = "PRI";
  5583. req.path = "*";
  5584. req.body = "SM";
  5585. auto res = std::make_shared<Response>();
  5586. auto error = Error::Success;
  5587. auto ret = cli_.send(req, *res, error);
  5588. ASSERT_TRUE(ret);
  5589. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5590. }
  5591. TEST_F(ServerTest, KeepAlive) {
  5592. auto res = cli_.Get("/hi");
  5593. ASSERT_TRUE(res);
  5594. EXPECT_EQ(StatusCode::OK_200, res->status);
  5595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5596. EXPECT_EQ("Hello World!", res->body);
  5597. res = cli_.Get("/hi");
  5598. ASSERT_TRUE(res);
  5599. EXPECT_EQ(StatusCode::OK_200, res->status);
  5600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5601. EXPECT_EQ("Hello World!", res->body);
  5602. res = cli_.Get("/hi");
  5603. ASSERT_TRUE(res);
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5606. EXPECT_EQ("Hello World!", res->body);
  5607. res = cli_.Get("/not-exist");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5610. res = cli_.Post("/empty", "", "text/plain");
  5611. ASSERT_TRUE(res);
  5612. EXPECT_EQ(StatusCode::OK_200, res->status);
  5613. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5614. EXPECT_EQ("empty", res->body);
  5615. EXPECT_EQ("close", res->get_header_value("Connection"));
  5616. res = cli_.Post(
  5617. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5618. "text/plain");
  5619. ASSERT_TRUE(res);
  5620. EXPECT_EQ(StatusCode::OK_200, res->status);
  5621. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5622. EXPECT_EQ("empty", res->body);
  5623. cli_.set_keep_alive(false);
  5624. res = cli_.Get("/last-request");
  5625. ASSERT_TRUE(res);
  5626. EXPECT_EQ(StatusCode::OK_200, res->status);
  5627. EXPECT_EQ("close", res->get_header_value("Connection"));
  5628. }
  5629. TEST_F(ServerTest, TooManyRedirect) {
  5630. cli_.set_follow_location(true);
  5631. auto res = cli_.Get("/redirect/0");
  5632. ASSERT_TRUE(!res);
  5633. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5634. }
  5635. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5636. Request req;
  5637. req.method = "FOOBAR";
  5638. req.path = "/hi";
  5639. cli_.set_keep_alive(true);
  5640. auto res = cli_.send(req);
  5641. ASSERT_TRUE(res);
  5642. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5643. EXPECT_EQ("close", res->get_header_value("Connection"));
  5644. EXPECT_FALSE(cli_.is_socket_open());
  5645. }
  5646. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5647. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5648. TEST_F(ServerTest, Gzip) {
  5649. Headers headers;
  5650. headers.emplace("Accept-Encoding", "gzip, deflate");
  5651. auto res = cli_.Get("/compress", headers);
  5652. ASSERT_TRUE(res);
  5653. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5656. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5657. "7890123456789012345678901234567890",
  5658. res->body);
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5662. Headers headers;
  5663. headers.emplace("Accept-Encoding", "gzip, deflate");
  5664. auto res = cli_.Get("/compress-with-charset", headers);
  5665. ASSERT_TRUE(res);
  5666. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5667. EXPECT_EQ("application/json; charset=utf-8",
  5668. res->get_header_value("Content-Type"));
  5669. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5670. "7890123456789012345678901234567890",
  5671. res->body);
  5672. EXPECT_EQ(StatusCode::OK_200, res->status);
  5673. }
  5674. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5675. Headers headers;
  5676. headers.emplace("Accept-Encoding", "");
  5677. auto res = cli_.Get("/compress", headers);
  5678. ASSERT_TRUE(res);
  5679. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5680. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5681. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5682. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5683. "7890123456789012345678901234567890",
  5684. res->body);
  5685. EXPECT_EQ(StatusCode::OK_200, res->status);
  5686. }
  5687. TEST_F(ServerTest, GzipWithContentReceiver) {
  5688. Headers headers;
  5689. headers.emplace("Accept-Encoding", "gzip, deflate");
  5690. std::string body;
  5691. auto res = cli_.Get("/compress", headers,
  5692. [&](const char *data, uint64_t data_length) {
  5693. EXPECT_EQ(100U, data_length);
  5694. body.append(data, data_length);
  5695. return true;
  5696. });
  5697. ASSERT_TRUE(res);
  5698. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5699. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5700. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5701. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5702. "7890123456789012345678901234567890",
  5703. body);
  5704. EXPECT_EQ(StatusCode::OK_200, res->status);
  5705. }
  5706. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5707. Headers headers;
  5708. headers.emplace("Accept-Encoding", "gzip, deflate");
  5709. cli_.set_decompress(false);
  5710. auto res = cli_.Get("/compress", headers);
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5714. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5715. EXPECT_EQ(33U, res->body.size());
  5716. EXPECT_EQ(StatusCode::OK_200, res->status);
  5717. }
  5718. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5719. Headers headers;
  5720. headers.emplace("Accept-Encoding", "");
  5721. std::string body;
  5722. auto res = cli_.Get("/compress", headers,
  5723. [&](const char *data, uint64_t data_length) {
  5724. EXPECT_EQ(100U, data_length);
  5725. body.append(data, data_length);
  5726. return true;
  5727. });
  5728. ASSERT_TRUE(res);
  5729. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5731. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5733. "7890123456789012345678901234567890",
  5734. body);
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. }
  5737. TEST_F(ServerTest, NoGzip) {
  5738. Headers headers;
  5739. headers.emplace("Accept-Encoding", "gzip, deflate");
  5740. auto res = cli_.Get("/nocompress", headers);
  5741. ASSERT_TRUE(res);
  5742. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5743. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5744. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5745. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5746. "7890123456789012345678901234567890",
  5747. res->body);
  5748. EXPECT_EQ(StatusCode::OK_200, res->status);
  5749. }
  5750. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5751. Headers headers;
  5752. headers.emplace("Accept-Encoding", "gzip, deflate");
  5753. std::string body;
  5754. auto res = cli_.Get("/nocompress", headers,
  5755. [&](const char *data, uint64_t data_length) {
  5756. EXPECT_EQ(100U, data_length);
  5757. body.append(data, data_length);
  5758. return true;
  5759. });
  5760. ASSERT_TRUE(res);
  5761. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5762. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5763. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5764. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5765. "7890123456789012345678901234567890",
  5766. body);
  5767. EXPECT_EQ(StatusCode::OK_200, res->status);
  5768. }
  5769. TEST_F(ServerTest, MultipartFormDataGzip) {
  5770. UploadFormDataItems items = {
  5771. {"key1", "test", "", ""},
  5772. {"key2", "--abcdefg123", "", ""},
  5773. };
  5774. cli_.set_compress(true);
  5775. auto res = cli_.Post("/compress-multipart", items);
  5776. ASSERT_TRUE(res);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. #endif
  5780. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5781. TEST_F(ServerTest, Brotli) {
  5782. Headers headers;
  5783. headers.emplace("Accept-Encoding", "br");
  5784. auto res = cli_.Get("/compress", headers);
  5785. ASSERT_TRUE(res);
  5786. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5788. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5789. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5790. "7890123456789012345678901234567890",
  5791. res->body);
  5792. EXPECT_EQ(StatusCode::OK_200, res->status);
  5793. }
  5794. #endif
  5795. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5796. TEST_F(ServerTest, Zstd) {
  5797. Headers headers;
  5798. headers.emplace("Accept-Encoding", "zstd");
  5799. auto res = cli_.Get("/compress", headers);
  5800. ASSERT_TRUE(res);
  5801. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5803. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5804. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5805. "7890123456789012345678901234567890",
  5806. res->body);
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. }
  5809. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5810. Headers headers;
  5811. headers.emplace("Accept-Encoding", "");
  5812. auto res = cli_.Get("/compress", headers);
  5813. ASSERT_TRUE(res);
  5814. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5816. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5818. "7890123456789012345678901234567890",
  5819. res->body);
  5820. EXPECT_EQ(StatusCode::OK_200, res->status);
  5821. }
  5822. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5823. Headers headers;
  5824. headers.emplace("Accept-Encoding", "zstd");
  5825. std::string body;
  5826. auto res = cli_.Get("/compress", headers,
  5827. [&](const char *data, uint64_t data_length) {
  5828. EXPECT_EQ(100U, data_length);
  5829. body.append(data, data_length);
  5830. return true;
  5831. });
  5832. ASSERT_TRUE(res);
  5833. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5835. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5837. "7890123456789012345678901234567890",
  5838. body);
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. }
  5841. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5842. Headers headers;
  5843. headers.emplace("Accept-Encoding", "zstd");
  5844. cli_.set_decompress(false);
  5845. auto res = cli_.Get("/compress", headers);
  5846. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5847. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5848. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5849. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5850. ASSERT_TRUE(res);
  5851. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5853. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5854. EXPECT_EQ(StatusCode::OK_200, res->status);
  5855. ASSERT_EQ(26U, res->body.size());
  5856. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5857. 0);
  5858. }
  5859. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5860. Headers headers;
  5861. headers.emplace("Accept-Encoding", "");
  5862. std::string body;
  5863. auto res = cli_.Get("/compress", headers,
  5864. [&](const char *data, uint64_t data_length) {
  5865. EXPECT_EQ(100U, data_length);
  5866. body.append(data, data_length);
  5867. return true;
  5868. });
  5869. ASSERT_TRUE(res);
  5870. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5872. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5873. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5874. "7890123456789012345678901234567890",
  5875. body);
  5876. EXPECT_EQ(StatusCode::OK_200, res->status);
  5877. }
  5878. TEST_F(ServerTest, NoZstd) {
  5879. Headers headers;
  5880. headers.emplace("Accept-Encoding", "zstd");
  5881. auto res = cli_.Get("/nocompress", headers);
  5882. ASSERT_TRUE(res);
  5883. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5884. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5885. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5886. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5887. "7890123456789012345678901234567890",
  5888. res->body);
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. }
  5891. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5892. Headers headers;
  5893. headers.emplace("Accept-Encoding", "zstd");
  5894. std::string body;
  5895. auto res = cli_.Get("/nocompress", headers,
  5896. [&](const char *data, uint64_t data_length) {
  5897. EXPECT_EQ(100U, data_length);
  5898. body.append(data, data_length);
  5899. return true;
  5900. });
  5901. ASSERT_TRUE(res);
  5902. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5903. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5904. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5905. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5906. "7890123456789012345678901234567890",
  5907. body);
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. }
  5910. // TODO: How to enable zstd ??
  5911. TEST_F(ServerTest, MultipartFormDataZstd) {
  5912. UploadFormDataItems items = {
  5913. {"key1", "test", "", ""},
  5914. {"key2", "--abcdefg123", "", ""},
  5915. };
  5916. Headers headers;
  5917. headers.emplace("Accept-Encoding", "zstd");
  5918. cli_.set_compress(true);
  5919. auto res = cli_.Post("/compress-multipart", headers, items);
  5920. ASSERT_TRUE(res);
  5921. EXPECT_EQ(StatusCode::OK_200, res->status);
  5922. }
  5923. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5924. Headers headers;
  5925. headers.emplace("Accept-Encoding", "zstd");
  5926. cli_.set_compress(true);
  5927. auto res = cli_.Put(
  5928. "/put", headers, 3,
  5929. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5930. sink.os << "PUT";
  5931. return true;
  5932. },
  5933. "text/plain");
  5934. ASSERT_TRUE(res);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ("PUT", res->body);
  5937. }
  5938. // Pre-compression logging tests
  5939. TEST_F(ServerTest, PreCompressionLogging) {
  5940. // Test data for compression (matches the actual /compress endpoint content)
  5941. const std::string test_content =
  5942. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5943. "3456789012345678901234567890";
  5944. // Variables to capture logging data
  5945. std::string pre_compression_body;
  5946. std::string pre_compression_content_type;
  5947. std::string pre_compression_content_encoding;
  5948. std::string post_compression_body;
  5949. std::string post_compression_content_type;
  5950. std::string post_compression_content_encoding;
  5951. // Set up pre-compression logger
  5952. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5953. const Response &res) {
  5954. pre_compression_body = res.body;
  5955. pre_compression_content_type = res.get_header_value("Content-Type");
  5956. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5957. });
  5958. // Set up post-compression logger
  5959. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5960. post_compression_body = res.body;
  5961. post_compression_content_type = res.get_header_value("Content-Type");
  5962. post_compression_content_encoding =
  5963. res.get_header_value("Content-Encoding");
  5964. });
  5965. // Test with gzip compression
  5966. Headers headers;
  5967. headers.emplace("Accept-Encoding", "gzip");
  5968. auto res = cli_.Get("/compress", headers);
  5969. // Verify response was compressed
  5970. ASSERT_TRUE(res);
  5971. EXPECT_EQ(StatusCode::OK_200, res->status);
  5972. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5973. // Verify pre-compression logger captured uncompressed content
  5974. EXPECT_EQ(test_content, pre_compression_body);
  5975. EXPECT_EQ("text/plain", pre_compression_content_type);
  5976. EXPECT_TRUE(pre_compression_content_encoding
  5977. .empty()); // No encoding header before compression
  5978. // Verify post-compression logger captured compressed content
  5979. EXPECT_NE(test_content,
  5980. post_compression_body); // Should be different after compression
  5981. EXPECT_EQ("text/plain", post_compression_content_type);
  5982. EXPECT_EQ("gzip", post_compression_content_encoding);
  5983. // Verify compressed content is smaller
  5984. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5985. }
  5986. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5987. const std::string test_content =
  5988. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5989. "3456789012345678901234567890";
  5990. std::string pre_compression_body;
  5991. std::string post_compression_body;
  5992. svr_.set_pre_compression_logger(
  5993. [&](const Request & /*req*/, const Response &res) {
  5994. pre_compression_body = res.body;
  5995. });
  5996. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5997. post_compression_body = res.body;
  5998. });
  5999. Headers headers;
  6000. headers.emplace("Accept-Encoding", "br");
  6001. auto res = cli_.Get("/compress", headers);
  6002. ASSERT_TRUE(res);
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6005. // Verify pre-compression content is uncompressed
  6006. EXPECT_EQ(test_content, pre_compression_body);
  6007. // Verify post-compression content is compressed
  6008. EXPECT_NE(test_content, post_compression_body);
  6009. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6010. }
  6011. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6012. const std::string test_content =
  6013. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6014. "3456789012345678901234567890";
  6015. std::string pre_compression_body;
  6016. std::string post_compression_body;
  6017. svr_.set_pre_compression_logger(
  6018. [&](const Request & /*req*/, const Response &res) {
  6019. pre_compression_body = res.body;
  6020. });
  6021. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6022. post_compression_body = res.body;
  6023. });
  6024. // Request without compression (use /nocompress endpoint)
  6025. Headers headers;
  6026. auto res = cli_.Get("/nocompress", headers);
  6027. ASSERT_TRUE(res);
  6028. EXPECT_EQ(StatusCode::OK_200, res->status);
  6029. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6030. // Pre-compression logger should not be called when no compression is applied
  6031. EXPECT_TRUE(
  6032. pre_compression_body.empty()); // Pre-compression logger not called
  6033. EXPECT_EQ(
  6034. test_content,
  6035. post_compression_body); // Post-compression logger captures final content
  6036. }
  6037. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6038. const std::string test_content =
  6039. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6040. "3456789012345678901234567890";
  6041. std::string pre_compression_body;
  6042. bool pre_logger_called = false;
  6043. // Set only pre-compression logger
  6044. svr_.set_pre_compression_logger(
  6045. [&](const Request & /*req*/, const Response &res) {
  6046. pre_compression_body = res.body;
  6047. pre_logger_called = true;
  6048. });
  6049. Headers headers;
  6050. headers.emplace("Accept-Encoding", "gzip");
  6051. auto res = cli_.Get("/compress", headers);
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ(StatusCode::OK_200, res->status);
  6054. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6055. // Verify pre-compression logger was called
  6056. EXPECT_TRUE(pre_logger_called);
  6057. EXPECT_EQ(test_content, pre_compression_body);
  6058. }
  6059. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6060. {
  6061. // Test with Expect: 100-continue header - success case
  6062. // Server returns 100 Continue, client sends body, server returns 200 OK
  6063. Request req;
  6064. req.method = "POST";
  6065. req.path = "/post-large";
  6066. req.set_header("Expect", "100-continue");
  6067. req.body = LARGE_DATA;
  6068. Response res;
  6069. auto error = Error::Success;
  6070. cli_.set_keep_alive(true);
  6071. auto ret = cli_.send(req, res, error);
  6072. EXPECT_TRUE(ret);
  6073. EXPECT_EQ(StatusCode::OK_200, res.status);
  6074. EXPECT_EQ(LARGE_DATA, res.body);
  6075. }
  6076. {
  6077. // Test with Expect: 100-continue header - error case
  6078. // Client should not send the body when server returns an error
  6079. Request req;
  6080. req.method = "POST";
  6081. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6082. req.set_header("Expect", "100-continue");
  6083. req.body = LARGE_DATA;
  6084. Response res;
  6085. auto error = Error::Success;
  6086. auto start = std::chrono::high_resolution_clock::now();
  6087. cli_.set_keep_alive(true);
  6088. auto ret = cli_.send(req, res, error);
  6089. auto end = std::chrono::high_resolution_clock::now();
  6090. auto elapsed =
  6091. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6092. .count();
  6093. // With Expect: 100-continue, request completes successfully but with error
  6094. EXPECT_TRUE(ret);
  6095. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6096. EXPECT_EQ("close", res.get_header_value("Connection"));
  6097. EXPECT_FALSE(cli_.is_socket_open());
  6098. EXPECT_LE(elapsed, 2000);
  6099. }
  6100. {
  6101. // Send an extra GET request to ensure error recovery without hanging
  6102. Request req;
  6103. req.method = "GET";
  6104. req.path = "/hi";
  6105. auto start = std::chrono::high_resolution_clock::now();
  6106. auto res = cli_.send(req);
  6107. auto end = std::chrono::high_resolution_clock::now();
  6108. auto elapsed =
  6109. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6110. .count();
  6111. ASSERT_TRUE(res);
  6112. EXPECT_EQ(StatusCode::OK_200, res->status);
  6113. EXPECT_EQ("Hello World!", res->body);
  6114. EXPECT_LE(elapsed, 500);
  6115. }
  6116. }
  6117. TEST(ZstdDecompressor, ChunkedDecompression) {
  6118. std::string data;
  6119. for (size_t i = 0; i < 32 * 1024; ++i) {
  6120. data.push_back(static_cast<char>('a' + i % 26));
  6121. }
  6122. std::string compressed_data;
  6123. {
  6124. httplib::detail::zstd_compressor compressor;
  6125. bool result = compressor.compress(
  6126. data.data(), data.size(),
  6127. /*last=*/true,
  6128. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6129. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6130. compressed_data_size);
  6131. return true;
  6132. });
  6133. ASSERT_TRUE(result);
  6134. }
  6135. std::string decompressed_data;
  6136. {
  6137. httplib::detail::zstd_decompressor decompressor;
  6138. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6139. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6140. size_t chunk_size = 130;
  6141. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6142. chunk_begin += chunk_size) {
  6143. size_t current_chunk_size =
  6144. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6145. bool result = decompressor.decompress(
  6146. compressed_data.data() + chunk_begin, current_chunk_size,
  6147. [&](const char *decompressed_data_chunk,
  6148. size_t decompressed_data_chunk_size) {
  6149. decompressed_data.insert(decompressed_data.size(),
  6150. decompressed_data_chunk,
  6151. decompressed_data_chunk_size);
  6152. return true;
  6153. });
  6154. ASSERT_TRUE(result);
  6155. }
  6156. }
  6157. ASSERT_EQ(data, decompressed_data);
  6158. }
  6159. TEST(ZstdDecompressor, Decompress) {
  6160. std::string original_text = "Compressed with ZSTD";
  6161. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6162. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6163. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6164. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6165. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6166. std::string decompressed_data;
  6167. {
  6168. httplib::detail::zstd_decompressor decompressor;
  6169. bool result = decompressor.decompress(
  6170. compressed_data.data(), compressed_data.size(),
  6171. [&](const char *decompressed_data_chunk,
  6172. size_t decompressed_data_chunk_size) {
  6173. decompressed_data.insert(decompressed_data.size(),
  6174. decompressed_data_chunk,
  6175. decompressed_data_chunk_size);
  6176. return true;
  6177. });
  6178. ASSERT_TRUE(result);
  6179. }
  6180. ASSERT_EQ(original_text, decompressed_data);
  6181. }
  6182. #endif
  6183. // Sends a raw request to a server listening at HOST:PORT.
  6184. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6185. std::string *resp = nullptr) {
  6186. auto error = Error::Success;
  6187. auto client_sock = detail::create_client_socket(
  6188. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6189. /*connection_timeout_sec=*/5, 0,
  6190. /*read_timeout_sec=*/5, 0,
  6191. /*write_timeout_sec=*/5, 0, std::string(), error);
  6192. if (client_sock == INVALID_SOCKET) { return false; }
  6193. auto ret = detail::process_client_socket(
  6194. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6195. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6196. if (req.size() !=
  6197. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6198. return false;
  6199. }
  6200. char buf[512];
  6201. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6202. while (line_reader.getline()) {
  6203. if (resp) { *resp += line_reader.ptr(); }
  6204. }
  6205. return true;
  6206. });
  6207. detail::close_socket(client_sock);
  6208. return ret;
  6209. }
  6210. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6211. Server svr;
  6212. std::string header_value;
  6213. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6214. header_value = req.get_header_value("foo");
  6215. res.set_content("ok", "text/plain");
  6216. });
  6217. thread t = thread([&] { svr.listen(HOST, PORT); });
  6218. auto se = detail::scope_exit([&] {
  6219. svr.stop();
  6220. t.join();
  6221. ASSERT_FALSE(svr.is_running());
  6222. });
  6223. svr.wait_until_ready();
  6224. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6225. // like characters are not treated the same - use vertical tab and escape.
  6226. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6227. "foo: \t \v bar \x1B\t \r\n"
  6228. "Connection: close\r\n"
  6229. "\r\n";
  6230. std::string res;
  6231. ASSERT_TRUE(send_request(5, req, &res));
  6232. EXPECT_EQ(header_value, "");
  6233. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6234. }
  6235. // Sends a raw request and verifies that there isn't a crash or exception.
  6236. static void test_raw_request(const std::string &req,
  6237. std::string *out = nullptr) {
  6238. Server svr;
  6239. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6240. res.set_content("ok", "text/plain");
  6241. });
  6242. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6243. res.set_content("ok", "text/plain");
  6244. });
  6245. svr.Get("/header_field_value_check",
  6246. [&](const Request & /*req*/, Response &res) {
  6247. res.set_content("ok", "text/plain");
  6248. });
  6249. // Server read timeout must be longer than the client read timeout for the
  6250. // bug to reproduce, probably to force the server to process a request
  6251. // without a trailing blank line.
  6252. const time_t client_read_timeout_sec = 1;
  6253. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6254. bool listen_thread_ok = false;
  6255. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6256. auto se = detail::scope_exit([&] {
  6257. svr.stop();
  6258. t.join();
  6259. ASSERT_FALSE(svr.is_running());
  6260. EXPECT_TRUE(listen_thread_ok);
  6261. });
  6262. svr.wait_until_ready();
  6263. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6264. }
  6265. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6266. // A certain header line causes an exception if the header property is parsed
  6267. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6268. test_raw_request(
  6269. "GET /hi HTTP/1.1\r\n"
  6270. " : "
  6271. " "
  6272. " ");
  6273. }
  6274. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6275. // A certain header line causes an exception if the header property *name* is
  6276. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6277. // greedy matcher and requires backtracking when there are a lot of ":"
  6278. // characters.
  6279. // This occurs with libc++ but not libstdc++.
  6280. test_raw_request(
  6281. "GET /hi HTTP/1.1\r\n"
  6282. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6283. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6284. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6285. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6286. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6287. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6288. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6289. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6290. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6291. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6292. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6293. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6294. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6295. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6296. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6297. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6298. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6299. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6300. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6301. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6302. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6303. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6304. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6305. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6306. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6307. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6308. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6309. "&&&%%%");
  6310. }
  6311. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6312. // Make sure this doesn't crash the server.
  6313. // In a previous version of the header line regex, the "\r" rendered the line
  6314. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6315. // a new position where the leading white space ended and the field value
  6316. // began.
  6317. // The crash occurs with libc++ but not libstdc++.
  6318. test_raw_request("GET /hi HTTP/1.1\r\n"
  6319. "a:" +
  6320. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6321. "\r\n"
  6322. "\r\n");
  6323. }
  6324. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6325. std::string out;
  6326. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6327. "Content-Type: text/plain\r\n"
  6328. "Transfer-Encoding: chunked\r\n"
  6329. "\r\n"
  6330. "nothex\r\n",
  6331. &out);
  6332. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6333. }
  6334. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6335. std::string out;
  6336. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6337. "Content-Type: text/plain\r\n"
  6338. "Transfer-Encoding: chunked\r\n"
  6339. "\r\n"
  6340. "3\r\n"
  6341. "xyz\r\n"
  6342. "NaN\r\n",
  6343. &out);
  6344. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6345. }
  6346. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6347. std::string out;
  6348. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6349. "Content-Type: text/plain\r\n"
  6350. "Transfer-Encoding: chunked\r\n"
  6351. "\r\n"
  6352. // Length is too large for 64 bits.
  6353. "1ffffffffffffffff\r\n"
  6354. "xyz\r\n",
  6355. &out);
  6356. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6357. }
  6358. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6359. test_raw_request("GET /hi HTTP/1.1\r\n"
  6360. "Content-Type: text/plain\r\n\r");
  6361. }
  6362. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6363. std::string out;
  6364. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6365. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6366. }
  6367. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6368. Server svr;
  6369. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6370. EXPECT_TRUE(!req.remote_addr.empty());
  6371. });
  6372. thread t = thread([&] { svr.listen(HOST, PORT); });
  6373. auto se = detail::scope_exit([&] {
  6374. svr.stop();
  6375. t.join();
  6376. ASSERT_FALSE(svr.is_running());
  6377. });
  6378. svr.wait_until_ready();
  6379. // Send an invalid request line to trigger Bad Request
  6380. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6381. std::string out;
  6382. ASSERT_TRUE(send_request(5, bad_req, &out));
  6383. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6384. }
  6385. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6386. std::string out;
  6387. std::string request(
  6388. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6389. test_raw_request(request, &out);
  6390. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6391. }
  6392. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6393. std::string out;
  6394. std::string request(
  6395. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6396. test_raw_request(request, &out);
  6397. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6398. }
  6399. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6400. std::string out;
  6401. std::string request(
  6402. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6403. test_raw_request(request, &out);
  6404. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6405. }
  6406. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6407. std::string out;
  6408. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6409. "Test: \r\n\r\n",
  6410. &out);
  6411. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6412. }
  6413. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6414. Server svr;
  6415. std::string x_custom;
  6416. std::string cookie;
  6417. std::string xff;
  6418. std::string x_unicode;
  6419. std::string x_iis;
  6420. svr.Get("/check", [&](const Request &req, Response &res) {
  6421. x_custom = req.get_header_value("X-Custom");
  6422. cookie = req.get_header_value("Cookie");
  6423. xff = req.get_header_value("X-Forwarded-For");
  6424. x_unicode = req.get_header_value("X-Unicode");
  6425. x_iis = req.get_header_value("X-IIS");
  6426. res.set_content("ok", "text/plain");
  6427. });
  6428. thread t = thread([&] { svr.listen(HOST, PORT); });
  6429. auto se = detail::scope_exit([&] {
  6430. svr.stop();
  6431. t.join();
  6432. ASSERT_FALSE(svr.is_running());
  6433. });
  6434. svr.wait_until_ready();
  6435. const std::string req = "GET /check HTTP/1.1\r\n"
  6436. "Host: localhost\r\n"
  6437. "X-Custom: a%0D%0AInjected: b\r\n"
  6438. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6439. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6440. "X-Unicode: %E3%81%82\r\n"
  6441. "X-IIS: %u00E9\r\n"
  6442. "Connection: close\r\n"
  6443. "\r\n";
  6444. std::string res;
  6445. ASSERT_TRUE(send_request(5, req, &res));
  6446. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6447. // Every value must be returned verbatim (wire form), with no decoding.
  6448. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6449. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6450. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6451. EXPECT_EQ("%E3%81%82", x_unicode);
  6452. EXPECT_EQ("%u00E9", x_iis);
  6453. }
  6454. // Applications that previously relied on automatic percent-decoding can
  6455. // reproduce the old behavior by explicitly calling decode_path_component()
  6456. // or, for RFC 3986 conformance, decode_uri_component().
  6457. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6458. Server svr;
  6459. std::string decoded;
  6460. svr.Get("/check", [&](const Request &req, Response &res) {
  6461. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6462. res.set_content("ok", "text/plain");
  6463. });
  6464. thread t = thread([&] { svr.listen(HOST, PORT); });
  6465. auto se = detail::scope_exit([&] {
  6466. svr.stop();
  6467. t.join();
  6468. ASSERT_FALSE(svr.is_running());
  6469. });
  6470. svr.wait_until_ready();
  6471. const std::string req = "GET /check HTTP/1.1\r\n"
  6472. "Host: localhost\r\n"
  6473. "X-Custom: hello%20world\r\n"
  6474. "Connection: close\r\n"
  6475. "\r\n";
  6476. std::string res;
  6477. ASSERT_TRUE(send_request(5, req, &res));
  6478. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6479. EXPECT_EQ("hello world", decoded);
  6480. }
  6481. // Regression test for #2033. Browsers send Referer values that include
  6482. // percent-encoded characters such as %0A inside the URL. Decoding the
  6483. // header value would either trip the post-decode CR/LF/NUL guard (the
  6484. // original bug, returning 400) or, after that guard was relaxed, silently
  6485. // store a literal LF — both unacceptable. The wire form must round-trip.
  6486. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6487. Server svr;
  6488. std::string referer;
  6489. svr.Get("/check", [&](const Request &req, Response &res) {
  6490. referer = req.get_header_value("Referer");
  6491. res.set_content("ok", "text/plain");
  6492. });
  6493. thread t = thread([&] { svr.listen(HOST, PORT); });
  6494. auto se = detail::scope_exit([&] {
  6495. svr.stop();
  6496. t.join();
  6497. ASSERT_FALSE(svr.is_running());
  6498. });
  6499. svr.wait_until_ready();
  6500. const std::string req = "GET /check HTTP/1.1\r\n"
  6501. "Host: localhost\r\n"
  6502. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6503. "Connection: close\r\n"
  6504. "\r\n";
  6505. std::string res;
  6506. ASSERT_TRUE(send_request(5, req, &res));
  6507. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6508. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6509. }
  6510. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6511. Server svr;
  6512. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6513. res.set_header("Cache-Control", "no-cache");
  6514. res.set_chunked_content_provider(
  6515. "text/event-stream", [](size_t offset, DataSink &sink) {
  6516. std::string s = "data:";
  6517. s += std::to_string(offset);
  6518. s += "\n\n";
  6519. auto ret = sink.write(s.data(), s.size());
  6520. EXPECT_TRUE(ret);
  6521. std::this_thread::sleep_for(std::chrono::seconds(1));
  6522. return true;
  6523. });
  6524. });
  6525. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6526. svr.wait_until_ready();
  6527. Client client(HOST, PORT);
  6528. const Headers headers = {{"Accept", "text/event-stream"}};
  6529. auto get_thread = std::thread([&client, &headers]() {
  6530. auto res = client.Get(
  6531. "/events", headers,
  6532. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6533. });
  6534. auto se = detail::scope_exit([&] {
  6535. svr.stop();
  6536. get_thread.join();
  6537. listen_thread.join();
  6538. ASSERT_FALSE(svr.is_running());
  6539. });
  6540. // Give GET time to get a few messages.
  6541. std::this_thread::sleep_for(std::chrono::seconds(2));
  6542. }
  6543. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6544. httplib::Server svr;
  6545. svr.Post("/hi",
  6546. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6547. res.status = StatusCode::OK_200;
  6548. });
  6549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6550. svr.wait_until_ready();
  6551. Client cli(HOST, PORT);
  6552. auto res = cli.Post("/hi", "data", "text/plain");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. svr.stop();
  6556. thread.join();
  6557. ASSERT_FALSE(svr.is_running());
  6558. res = cli.Post("/hi", "data", "text/plain");
  6559. ASSERT_FALSE(res);
  6560. }
  6561. TEST(ServerStopTest, ListenFailure) {
  6562. Server svr;
  6563. auto t = thread([&]() {
  6564. auto ret = svr.listen("????", PORT);
  6565. EXPECT_FALSE(ret);
  6566. });
  6567. svr.wait_until_ready();
  6568. svr.stop();
  6569. t.join();
  6570. }
  6571. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6572. TEST(ServerStopTest, Decommision) {
  6573. Server svr;
  6574. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6575. for (int i = 0; i < 4; i++) {
  6576. auto is_even = !(i % 2);
  6577. std::thread t{[&] {
  6578. try {
  6579. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6580. if (is_even) {
  6581. throw std::runtime_error("Some thing that happens to go wrong.");
  6582. }
  6583. svr.listen(HOST, PORT);
  6584. } catch (...) { svr.decommission(); }
  6585. }};
  6586. svr.wait_until_ready();
  6587. // Server is up
  6588. {
  6589. Client cli(HOST, PORT);
  6590. auto res = cli.Get("/hi");
  6591. if (is_even) {
  6592. EXPECT_FALSE(res);
  6593. } else {
  6594. EXPECT_TRUE(res);
  6595. EXPECT_EQ("hi...", res->body);
  6596. }
  6597. }
  6598. svr.stop();
  6599. t.join();
  6600. // Server is down...
  6601. {
  6602. Client cli(HOST, PORT);
  6603. auto res = cli.Get("/hi");
  6604. EXPECT_FALSE(res);
  6605. }
  6606. }
  6607. }
  6608. #endif
  6609. // Helper function for string body upload progress tests
  6610. template <typename SetupHandler, typename ClientCall>
  6611. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6612. ClientCall &&client_call,
  6613. const string &body) {
  6614. Server svr;
  6615. setup_handler(svr);
  6616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6617. auto se = detail::scope_exit([&] {
  6618. svr.stop();
  6619. t.join();
  6620. });
  6621. svr.wait_until_ready();
  6622. Client cli(HOST, PORT);
  6623. vector<uint64_t> progress_values;
  6624. bool progress_called = false;
  6625. auto res =
  6626. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6627. progress_values.push_back(current);
  6628. progress_called = true;
  6629. return true;
  6630. });
  6631. ASSERT_TRUE(res);
  6632. EXPECT_EQ(200, res->status);
  6633. EXPECT_TRUE(progress_called);
  6634. }
  6635. TEST(UploadProgressTest, PostStringBodyBasic) {
  6636. TestStringBodyUploadProgress(
  6637. [](Server &svr) {
  6638. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6639. res.set_content("received", "text/plain");
  6640. });
  6641. },
  6642. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6643. return cli.Post("/test", body, "text/plain", progress_callback);
  6644. },
  6645. "test data for upload progress");
  6646. }
  6647. TEST(UploadProgressTest, PutStringBodyBasic) {
  6648. TestStringBodyUploadProgress(
  6649. [](Server &svr) {
  6650. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6651. res.set_content("put received", "text/plain");
  6652. });
  6653. },
  6654. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6655. return cli.Put("/test", body, "text/plain", progress_callback);
  6656. },
  6657. "put test data for upload progress");
  6658. }
  6659. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6660. TestStringBodyUploadProgress(
  6661. [](Server &svr) {
  6662. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6663. res.set_content("patch received", "text/plain");
  6664. });
  6665. },
  6666. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6667. return cli.Patch("/test", body, "text/plain", progress_callback);
  6668. },
  6669. "patch test data for upload progress");
  6670. }
  6671. // Helper function for content provider upload progress tests
  6672. template <typename SetupHandler, typename ClientCall>
  6673. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6674. ClientCall &&client_call) {
  6675. Server svr;
  6676. setup_handler(svr);
  6677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6678. auto se = detail::scope_exit([&] {
  6679. svr.stop();
  6680. t.join();
  6681. });
  6682. svr.wait_until_ready();
  6683. Client cli(HOST, PORT);
  6684. vector<uint64_t> progress_values;
  6685. auto res =
  6686. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6687. progress_values.push_back(current);
  6688. return true;
  6689. });
  6690. ASSERT_TRUE(res);
  6691. EXPECT_EQ(200, res->status);
  6692. EXPECT_FALSE(progress_values.empty());
  6693. }
  6694. TEST(UploadProgressTest, PostContentProviderProgress) {
  6695. TestContentProviderUploadProgress(
  6696. [](Server &svr) {
  6697. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6698. res.set_content("provider received", "text/plain");
  6699. });
  6700. },
  6701. [](Client &cli, UploadProgress progress_callback) {
  6702. return cli.Post(
  6703. "/test", 10,
  6704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6705. sink.os << "test data";
  6706. return true;
  6707. },
  6708. "text/plain", progress_callback);
  6709. });
  6710. }
  6711. // Helper function for multipart upload progress tests
  6712. template <typename SetupHandler, typename ClientCall>
  6713. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6714. ClientCall &&client_call,
  6715. const string &endpoint) {
  6716. Server svr;
  6717. setup_handler(svr);
  6718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6719. auto se = detail::scope_exit([&] {
  6720. svr.stop();
  6721. t.join();
  6722. });
  6723. svr.wait_until_ready();
  6724. Client cli(HOST, PORT);
  6725. vector<uint64_t> progress_values;
  6726. UploadFormDataItems items = {
  6727. {"field1", "value1", "", ""},
  6728. {"field2", "longer value for progress tracking test", "", ""},
  6729. {"file1", "file content data for upload progress", "test.txt",
  6730. "text/plain"}};
  6731. auto res = client_call(cli, endpoint, items,
  6732. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6733. progress_values.push_back(current);
  6734. return true;
  6735. });
  6736. ASSERT_TRUE(res);
  6737. EXPECT_EQ(200, res->status);
  6738. EXPECT_FALSE(progress_values.empty());
  6739. }
  6740. TEST(UploadProgressTest, PostMultipartProgress) {
  6741. TestMultipartUploadProgress(
  6742. [](Server &svr) {
  6743. svr.Post("/multipart", [](const Request &req, Response &res) {
  6744. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6745. res.set_content("multipart received", "text/plain");
  6746. });
  6747. },
  6748. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6749. UploadProgress progress_callback) {
  6750. return cli.Post(endpoint, items, progress_callback);
  6751. },
  6752. "/multipart");
  6753. }
  6754. // Helper function for basic download progress tests
  6755. template <typename SetupHandler, typename ClientCall>
  6756. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6757. ClientCall &&client_call, const string &endpoint,
  6758. size_t expected_content_size) {
  6759. Server svr;
  6760. setup_handler(svr);
  6761. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6762. auto se = detail::scope_exit([&] {
  6763. svr.stop();
  6764. t.join();
  6765. });
  6766. svr.wait_until_ready();
  6767. Client cli(HOST, PORT);
  6768. vector<uint64_t> progress_values;
  6769. auto res = client_call(cli, endpoint,
  6770. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6771. progress_values.push_back(current);
  6772. return true;
  6773. });
  6774. ASSERT_TRUE(res);
  6775. EXPECT_EQ(200, res->status);
  6776. EXPECT_FALSE(progress_values.empty());
  6777. EXPECT_EQ(expected_content_size, res->body.size());
  6778. }
  6779. TEST(DownloadProgressTest, GetBasic) {
  6780. TestBasicDownloadProgress(
  6781. [](Server &svr) {
  6782. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6783. string content(1000, 'D');
  6784. res.set_content(content, "text/plain");
  6785. });
  6786. },
  6787. [](Client &cli, const string &endpoint,
  6788. DownloadProgress progress_callback) {
  6789. return cli.Get(endpoint, progress_callback);
  6790. },
  6791. "/download", 1000u);
  6792. }
  6793. // Helper function for content receiver download progress tests
  6794. template <typename SetupHandler, typename ClientCall>
  6795. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6796. ClientCall &&client_call,
  6797. const string &endpoint,
  6798. size_t expected_content_size) {
  6799. Server svr;
  6800. setup_handler(svr);
  6801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6802. auto se = detail::scope_exit([&] {
  6803. svr.stop();
  6804. t.join();
  6805. });
  6806. svr.wait_until_ready();
  6807. Client cli(HOST, PORT);
  6808. vector<uint64_t> progress_values;
  6809. string received_body;
  6810. auto res = client_call(
  6811. cli, endpoint,
  6812. [&](const char *data, size_t data_length) -> bool {
  6813. received_body.append(data, data_length);
  6814. return true;
  6815. },
  6816. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6817. progress_values.push_back(current);
  6818. return true;
  6819. });
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(200, res->status);
  6822. EXPECT_FALSE(progress_values.empty());
  6823. EXPECT_EQ(expected_content_size, received_body.size());
  6824. EXPECT_TRUE(res->body.empty());
  6825. }
  6826. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6827. TestContentReceiverDownloadProgress(
  6828. [](Server &svr) {
  6829. svr.Get("/download-receiver",
  6830. [](const Request & /*req*/, Response &res) {
  6831. string content(2000, 'R');
  6832. res.set_content(content, "text/plain");
  6833. });
  6834. },
  6835. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6836. DownloadProgress progress_callback) {
  6837. return cli.Get(endpoint, content_receiver, progress_callback);
  6838. },
  6839. "/download-receiver", 2000u);
  6840. }
  6841. TEST(StreamingTest, NoContentLengthStreaming) {
  6842. Server svr;
  6843. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6844. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6845. if (offset < 6) {
  6846. sink.os << (offset < 3 ? "a" : "b");
  6847. } else {
  6848. sink.done();
  6849. }
  6850. return true;
  6851. });
  6852. });
  6853. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6854. auto listen_se = detail::scope_exit([&] {
  6855. svr.stop();
  6856. listen_thread.join();
  6857. ASSERT_FALSE(svr.is_running());
  6858. });
  6859. svr.wait_until_ready();
  6860. Client client(HOST, PORT);
  6861. auto get_thread = std::thread([&client]() {
  6862. std::string s;
  6863. auto res =
  6864. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6865. s += std::string(data, len);
  6866. return true;
  6867. });
  6868. ASSERT_TRUE(res);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("aaabbb", s);
  6871. });
  6872. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6873. // Give GET time to get a few messages.
  6874. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6875. }
  6876. TEST(MountTest, Unmount) {
  6877. Server svr;
  6878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6879. auto se = detail::scope_exit([&] {
  6880. svr.stop();
  6881. listen_thread.join();
  6882. ASSERT_FALSE(svr.is_running());
  6883. });
  6884. svr.wait_until_ready();
  6885. Client cli("localhost", PORT);
  6886. svr.set_mount_point("/mount2", "./www2");
  6887. auto res = cli.Get("/");
  6888. ASSERT_TRUE(res);
  6889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6890. res = cli.Get("/mount2/dir/test.html");
  6891. ASSERT_TRUE(res);
  6892. EXPECT_EQ(StatusCode::OK_200, res->status);
  6893. svr.set_mount_point("/", "./www");
  6894. res = cli.Get("/dir/");
  6895. ASSERT_TRUE(res);
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. svr.remove_mount_point("/");
  6898. res = cli.Get("/dir/");
  6899. ASSERT_TRUE(res);
  6900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6901. svr.remove_mount_point("/mount2");
  6902. res = cli.Get("/mount2/dir/test.html");
  6903. ASSERT_TRUE(res);
  6904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6905. }
  6906. TEST(MountTest, Redicect) {
  6907. Server svr;
  6908. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6909. auto se = detail::scope_exit([&] {
  6910. svr.stop();
  6911. listen_thread.join();
  6912. ASSERT_FALSE(svr.is_running());
  6913. });
  6914. svr.set_mount_point("/", "./www");
  6915. svr.wait_until_ready();
  6916. Client cli("localhost", PORT);
  6917. auto res = cli.Get("/dir/");
  6918. ASSERT_TRUE(res);
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. res = cli.Get("/dir");
  6921. ASSERT_TRUE(res);
  6922. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6923. res = cli.Get("/file");
  6924. ASSERT_TRUE(res);
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. res = cli.Get("/file/");
  6927. ASSERT_TRUE(res);
  6928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6929. cli.set_follow_location(true);
  6930. res = cli.Get("/dir");
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. }
  6934. TEST(MountTest, MultibytesPathName) {
  6935. Server svr;
  6936. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6937. auto se = detail::scope_exit([&] {
  6938. svr.stop();
  6939. listen_thread.join();
  6940. ASSERT_FALSE(svr.is_running());
  6941. });
  6942. svr.set_mount_point("/", "./www");
  6943. svr.wait_until_ready();
  6944. Client cli("localhost", PORT);
  6945. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6946. ASSERT_TRUE(res);
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6949. }
  6950. #ifdef _WIN32
  6951. // Issue #2435: mmap::open() must succeed even when another handle holds
  6952. // the file open for writing (e.g. an active log file).
  6953. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6954. const char *path = "mmap_concurrent_writer_test.txt";
  6955. const char *content = "hello";
  6956. {
  6957. std::ofstream f(path, std::ios::binary);
  6958. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6959. }
  6960. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6961. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6962. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6963. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6964. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6965. detail::mmap m(path);
  6966. ASSERT_TRUE(m.is_open());
  6967. EXPECT_EQ(strlen(content), m.size());
  6968. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6969. }
  6970. #endif
  6971. TEST(KeepAliveTest, ReadTimeout) {
  6972. Server svr;
  6973. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6974. std::this_thread::sleep_for(std::chrono::seconds(2));
  6975. res.set_content("a", "text/plain");
  6976. });
  6977. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6978. res.set_content("b", "text/plain");
  6979. });
  6980. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6981. auto se = detail::scope_exit([&] {
  6982. svr.stop();
  6983. listen_thread.join();
  6984. ASSERT_FALSE(svr.is_running());
  6985. });
  6986. svr.wait_until_ready();
  6987. Client cli("localhost", PORT);
  6988. cli.set_keep_alive(true);
  6989. cli.set_read_timeout(std::chrono::seconds(1));
  6990. auto resa = cli.Get("/a");
  6991. ASSERT_FALSE(resa);
  6992. EXPECT_EQ(Error::Read, resa.error());
  6993. auto resb = cli.Get("/b");
  6994. ASSERT_TRUE(resb);
  6995. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6996. EXPECT_EQ("b", resb->body);
  6997. }
  6998. TEST(KeepAliveTest, MaxCount) {
  6999. size_t keep_alive_max_count = 3;
  7000. Server svr;
  7001. svr.set_keep_alive_max_count(keep_alive_max_count);
  7002. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7003. res.set_content("Hello World!", "text/plain");
  7004. });
  7005. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7006. auto se = detail::scope_exit([&] {
  7007. svr.stop();
  7008. listen_thread.join();
  7009. ASSERT_FALSE(svr.is_running());
  7010. });
  7011. svr.wait_until_ready();
  7012. Client cli(HOST, PORT);
  7013. cli.set_keep_alive(true);
  7014. for (size_t i = 0; i < 5; i++) {
  7015. auto result = cli.Get("/hi");
  7016. ASSERT_TRUE(result);
  7017. EXPECT_EQ(StatusCode::OK_200, result->status);
  7018. if (i == keep_alive_max_count - 1) {
  7019. EXPECT_EQ("close", result->get_header_value("Connection"));
  7020. } else {
  7021. EXPECT_FALSE(result->has_header("Connection"));
  7022. }
  7023. }
  7024. }
  7025. TEST(KeepAliveTest, Issue1041) {
  7026. Server svr;
  7027. svr.set_keep_alive_timeout(3);
  7028. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7029. res.set_content("Hello World!", "text/plain");
  7030. });
  7031. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7032. auto se = detail::scope_exit([&] {
  7033. svr.stop();
  7034. listen_thread.join();
  7035. ASSERT_FALSE(svr.is_running());
  7036. });
  7037. svr.wait_until_ready();
  7038. Client cli(HOST, PORT);
  7039. cli.set_keep_alive(true);
  7040. auto result = cli.Get("/hi");
  7041. ASSERT_TRUE(result);
  7042. EXPECT_EQ(StatusCode::OK_200, result->status);
  7043. std::this_thread::sleep_for(std::chrono::seconds(5));
  7044. result = cli.Get("/hi");
  7045. ASSERT_TRUE(result);
  7046. EXPECT_EQ(StatusCode::OK_200, result->status);
  7047. }
  7048. TEST(KeepAliveTest, Issue1959) {
  7049. Server svr;
  7050. svr.set_keep_alive_timeout(5);
  7051. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7052. res.set_content("a", "text/plain");
  7053. });
  7054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7055. auto se = detail::scope_exit([&] {
  7056. if (!svr.is_running()) return;
  7057. svr.stop();
  7058. listen_thread.join();
  7059. ASSERT_FALSE(svr.is_running());
  7060. });
  7061. svr.wait_until_ready();
  7062. Client cli("localhost", PORT);
  7063. cli.set_keep_alive(true);
  7064. using namespace std::chrono;
  7065. auto start = steady_clock::now();
  7066. cli.Get("/a");
  7067. svr.stop();
  7068. listen_thread.join();
  7069. auto end = steady_clock::now();
  7070. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7071. EXPECT_LT(elapsed, 5000);
  7072. }
  7073. #ifdef CPPHTTPLIB_SSL_ENABLED
  7074. TEST(KeepAliveTest, SSLClientReconnection) {
  7075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7076. ASSERT_TRUE(svr.is_valid());
  7077. svr.set_keep_alive_timeout(1);
  7078. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7079. res.set_content("Hello World!", "text/plain");
  7080. });
  7081. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7082. auto se = detail::scope_exit([&] {
  7083. svr.stop();
  7084. listen_thread.join();
  7085. ASSERT_FALSE(svr.is_running());
  7086. });
  7087. svr.wait_until_ready();
  7088. SSLClient cli(HOST, PORT);
  7089. cli.enable_server_certificate_verification(false);
  7090. cli.set_keep_alive(true);
  7091. auto result = cli.Get("/hi");
  7092. ASSERT_TRUE(result);
  7093. EXPECT_EQ(StatusCode::OK_200, result->status);
  7094. result = cli.Get("/hi");
  7095. ASSERT_TRUE(result);
  7096. EXPECT_EQ(StatusCode::OK_200, result->status);
  7097. std::this_thread::sleep_for(std::chrono::seconds(2));
  7098. // Recoonect
  7099. result = cli.Get("/hi");
  7100. ASSERT_TRUE(result);
  7101. EXPECT_EQ(StatusCode::OK_200, result->status);
  7102. result = cli.Get("/hi");
  7103. ASSERT_TRUE(result);
  7104. EXPECT_EQ(StatusCode::OK_200, result->status);
  7105. }
  7106. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7108. ASSERT_TRUE(svr.is_valid());
  7109. svr.set_keep_alive_timeout(1);
  7110. std::string content = "reconnect";
  7111. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7112. res.set_content("Hello World!", "text/plain");
  7113. });
  7114. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7115. auto se = detail::scope_exit([&] {
  7116. svr.stop();
  7117. listen_thread.join();
  7118. ASSERT_FALSE(svr.is_running());
  7119. });
  7120. svr.wait_until_ready();
  7121. SSLClient cli(HOST, PORT);
  7122. cli.enable_server_certificate_verification(false);
  7123. cli.set_keep_alive(true);
  7124. auto result = cli.Post(
  7125. "/hi", content.size(),
  7126. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7127. sink.write(content.c_str(), content.size());
  7128. return true;
  7129. },
  7130. "text/plain");
  7131. ASSERT_TRUE(result);
  7132. EXPECT_EQ(200, result->status);
  7133. std::this_thread::sleep_for(std::chrono::seconds(2));
  7134. // Recoonect
  7135. result = cli.Post(
  7136. "/hi", content.size(),
  7137. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7138. sink.write(content.c_str(), content.size());
  7139. return true;
  7140. },
  7141. "text/plain");
  7142. ASSERT_TRUE(result);
  7143. EXPECT_EQ(200, result->status);
  7144. result = cli.Post(
  7145. "/hi", content.size(),
  7146. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7147. sink.write(content.c_str(), content.size());
  7148. return true;
  7149. },
  7150. "text/plain");
  7151. ASSERT_TRUE(result);
  7152. EXPECT_EQ(200, result->status);
  7153. }
  7154. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7155. using namespace httplib::tls;
  7156. {
  7157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7158. ASSERT_TRUE(svr.is_valid());
  7159. svr.Get("/sni", [&](const Request &req, Response &res) {
  7160. std::string expected = req.sni();
  7161. EXPECT_EQ(expected, req.get_param_value("expected"));
  7162. res.set_content("ok", "text/plain");
  7163. });
  7164. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7165. auto se = detail::scope_exit([&] {
  7166. svr.stop();
  7167. listen_thread.join();
  7168. ASSERT_FALSE(svr.is_running());
  7169. });
  7170. svr.wait_until_ready();
  7171. {
  7172. SSLClient cli("localhost", PORT);
  7173. cli.enable_server_certificate_verification(false);
  7174. auto res = cli.Get("/sni?expected=localhost");
  7175. ASSERT_TRUE(res);
  7176. }
  7177. {
  7178. SSLClient cli("::1", PORT);
  7179. cli.enable_server_certificate_verification(false);
  7180. auto res = cli.Get("/sni?expected=");
  7181. // NOTE: This may fail if the server is listening on IPv4 only
  7182. // (e.g., when localhost resolves to 127.0.0.1 only)
  7183. if (res) {
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. } else {
  7186. EXPECT_EQ(Error::Connection, res.error());
  7187. }
  7188. }
  7189. }
  7190. }
  7191. #endif
  7192. TEST(ClientProblemDetectionTest, ContentProvider) {
  7193. Server svr;
  7194. size_t content_length = 1024 * 1024;
  7195. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7196. res.set_content_provider(
  7197. content_length, "text/plain",
  7198. [&](size_t offset, size_t length, DataSink &sink) {
  7199. auto out_len = std::min(length, static_cast<size_t>(1024));
  7200. std::string out(out_len, '@');
  7201. sink.write(out.data(), out_len);
  7202. return offset < 4096;
  7203. },
  7204. [](bool success) { ASSERT_FALSE(success); });
  7205. });
  7206. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7207. res.set_content_provider(
  7208. 0, "text/plain",
  7209. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7210. EXPECT_TRUE(false);
  7211. return true;
  7212. },
  7213. [](bool success) { ASSERT_FALSE(success); });
  7214. });
  7215. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7216. auto se = detail::scope_exit([&] {
  7217. svr.stop();
  7218. listen_thread.join();
  7219. ASSERT_FALSE(svr.is_running());
  7220. });
  7221. svr.wait_until_ready();
  7222. Client cli("localhost", PORT);
  7223. {
  7224. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7225. size_t /*data_length*/) { return false; });
  7226. ASSERT_FALSE(res);
  7227. }
  7228. {
  7229. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7230. size_t /*data_length*/) { return false; });
  7231. ASSERT_TRUE(res);
  7232. }
  7233. }
  7234. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7235. Server svr;
  7236. svr.set_error_handler([](Request const &, Response &res) -> void {
  7237. res.set_chunked_content_provider(
  7238. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7239. sink.os << "hello";
  7240. sink.os << "world";
  7241. sink.done();
  7242. return true;
  7243. });
  7244. });
  7245. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7246. auto se = detail::scope_exit([&] {
  7247. svr.stop();
  7248. listen_thread.join();
  7249. ASSERT_FALSE(svr.is_running());
  7250. });
  7251. svr.wait_until_ready();
  7252. Client cli("localhost", PORT);
  7253. auto res = cli.Get("/");
  7254. ASSERT_TRUE(res);
  7255. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7256. EXPECT_EQ("helloworld", res->body);
  7257. }
  7258. TEST(LongPollingTest, ClientCloseDetection) {
  7259. Server svr;
  7260. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7261. res.set_chunked_content_provider(
  7262. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7263. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7264. sink.os << "hello";
  7265. auto count = 10;
  7266. while (count > 0 && sink.is_writable()) {
  7267. this_thread::sleep_for(chrono::milliseconds(10));
  7268. count--;
  7269. }
  7270. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7271. return true;
  7272. });
  7273. });
  7274. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7275. auto se = detail::scope_exit([&] {
  7276. svr.stop();
  7277. listen_thread.join();
  7278. ASSERT_FALSE(svr.is_running());
  7279. });
  7280. svr.wait_until_ready();
  7281. Client cli("localhost", PORT);
  7282. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7283. EXPECT_EQ("hello", string(data, data_length));
  7284. return false; // close the socket immediately.
  7285. });
  7286. ASSERT_FALSE(res);
  7287. }
  7288. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7289. Server svr;
  7290. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7291. res.set_chunked_content_provider(
  7292. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7293. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7294. sink.os << "hello";
  7295. EXPECT_TRUE(sink.os.good());
  7296. // Wait for the client to close the connection
  7297. auto count = 10;
  7298. while (count > 0 && sink.is_writable()) {
  7299. this_thread::sleep_for(chrono::milliseconds(10));
  7300. count--;
  7301. }
  7302. // After client disconnect, write repeatedly until the socket
  7303. // write actually fails (small writes may be absorbed by the
  7304. // kernel buffer)
  7305. std::string chunk(1024, 'x');
  7306. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7307. sink.os << chunk;
  7308. }
  7309. EXPECT_TRUE(sink.os.fail());
  7310. return true;
  7311. });
  7312. });
  7313. auto port = svr.bind_to_any_port("localhost");
  7314. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7315. auto se = detail::scope_exit([&] {
  7316. svr.stop();
  7317. listen_thread.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. });
  7320. svr.wait_until_ready();
  7321. Client cli("localhost", port);
  7322. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7323. EXPECT_EQ("hello", string(data, data_length));
  7324. return false; // close the socket immediately.
  7325. });
  7326. ASSERT_FALSE(res);
  7327. }
  7328. TEST(GetWithParametersTest, GetWithParameters) {
  7329. Server svr;
  7330. svr.Get("/", [&](const Request &req, Response &) {
  7331. EXPECT_EQ("world", req.get_param_value("hello"));
  7332. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7333. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7334. });
  7335. svr.Get("/params", [&](const Request &req, Response &) {
  7336. EXPECT_EQ("world", req.get_param_value("hello"));
  7337. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7338. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7339. });
  7340. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7341. EXPECT_EQ("resource-id", req.matches[1]);
  7342. EXPECT_EQ("foo", req.get_param_value("param1"));
  7343. EXPECT_EQ("bar", req.get_param_value("param2"));
  7344. });
  7345. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7346. EXPECT_EQ("user-id", req.path_params.at("id"));
  7347. EXPECT_EQ("foo", req.get_param_value("param1"));
  7348. EXPECT_EQ("bar", req.get_param_value("param2"));
  7349. });
  7350. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7351. auto se = detail::scope_exit([&] {
  7352. svr.stop();
  7353. listen_thread.join();
  7354. ASSERT_FALSE(svr.is_running());
  7355. });
  7356. svr.wait_until_ready();
  7357. {
  7358. Client cli(HOST, PORT);
  7359. Params params;
  7360. params.emplace("hello", "world");
  7361. params.emplace("hello2", "world2");
  7362. params.emplace("hello3", "world3");
  7363. auto res = cli.Get("/", params, Headers{});
  7364. ASSERT_TRUE(res);
  7365. EXPECT_EQ(StatusCode::OK_200, res->status);
  7366. }
  7367. {
  7368. Client cli(HOST, PORT);
  7369. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7370. ASSERT_TRUE(res);
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. }
  7373. {
  7374. Client cli(HOST, PORT);
  7375. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7376. ASSERT_TRUE(res);
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. }
  7379. {
  7380. Client cli(HOST, PORT);
  7381. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7382. ASSERT_TRUE(res);
  7383. EXPECT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. }
  7386. TEST(GetWithParametersTest, GetWithParameters2) {
  7387. Server svr;
  7388. svr.Get("/", [&](const Request &req, Response &res) {
  7389. auto text = req.get_param_value("hello");
  7390. res.set_content(text, "text/plain");
  7391. });
  7392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7393. auto se = detail::scope_exit([&] {
  7394. svr.stop();
  7395. listen_thread.join();
  7396. ASSERT_FALSE(svr.is_running());
  7397. });
  7398. svr.wait_until_ready();
  7399. Client cli("localhost", PORT);
  7400. Params params;
  7401. params.emplace("hello", "world");
  7402. std::string body;
  7403. auto res = cli.Get("/", params, Headers{},
  7404. [&](const char *data, size_t data_length) {
  7405. body.append(data, data_length);
  7406. return true;
  7407. });
  7408. ASSERT_TRUE(res);
  7409. EXPECT_EQ(StatusCode::OK_200, res->status);
  7410. EXPECT_EQ("world", body);
  7411. }
  7412. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7413. auto host = "httpbingo.org";
  7414. auto path = std::string{"/range/32"};
  7415. #ifdef CPPHTTPLIB_SSL_ENABLED
  7416. SSLClient cli(host);
  7417. #else
  7418. Client cli(host);
  7419. #endif
  7420. cli.set_default_headers({make_range_header({{1, 10}})});
  7421. cli.set_connection_timeout(5);
  7422. {
  7423. auto res = cli.Get(path);
  7424. ASSERT_TRUE(res);
  7425. EXPECT_EQ("bcdefghijk", res->body);
  7426. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7427. }
  7428. {
  7429. auto res = cli.Get(path);
  7430. ASSERT_TRUE(res);
  7431. EXPECT_EQ("bcdefghijk", res->body);
  7432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7433. }
  7434. }
  7435. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7436. Server svr;
  7437. svr.set_default_headers({{"Hello", "World"}});
  7438. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7439. res.set_content("ok", "text/plain");
  7440. });
  7441. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7442. auto se = detail::scope_exit([&] {
  7443. svr.stop();
  7444. listen_thread.join();
  7445. ASSERT_FALSE(svr.is_running());
  7446. });
  7447. svr.wait_until_ready();
  7448. Client cli("localhost", PORT);
  7449. auto res = cli.Get("/");
  7450. ASSERT_TRUE(res);
  7451. EXPECT_EQ(StatusCode::OK_200, res->status);
  7452. EXPECT_EQ("ok", res->body);
  7453. EXPECT_EQ("World", res->get_header_value("Hello"));
  7454. }
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7458. ASSERT_TRUE(svr.is_valid());
  7459. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7460. std::this_thread::sleep_for(std::chrono::seconds(2));
  7461. res.set_content("a", "text/plain");
  7462. });
  7463. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7464. res.set_content("b", "text/plain");
  7465. });
  7466. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7467. auto se = detail::scope_exit([&] {
  7468. svr.stop();
  7469. listen_thread.join();
  7470. ASSERT_FALSE(svr.is_running());
  7471. });
  7472. svr.wait_until_ready();
  7473. SSLClient cli("localhost", PORT);
  7474. cli.enable_server_certificate_verification(false);
  7475. cli.set_keep_alive(true);
  7476. cli.set_read_timeout(std::chrono::seconds(1));
  7477. auto resa = cli.Get("/a");
  7478. ASSERT_TRUE(!resa);
  7479. EXPECT_EQ(Error::Read, resa.error());
  7480. auto resb = cli.Get("/b");
  7481. ASSERT_TRUE(resb);
  7482. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7483. EXPECT_EQ("b", resb->body);
  7484. }
  7485. #endif
  7486. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7487. protected:
  7488. ServerTestWithAI_PASSIVE()
  7489. : cli_(HOST, PORT)
  7490. #ifdef CPPHTTPLIB_SSL_ENABLED
  7491. ,
  7492. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7493. #endif
  7494. {
  7495. #ifdef CPPHTTPLIB_SSL_ENABLED
  7496. cli_.enable_server_certificate_verification(false);
  7497. #endif
  7498. }
  7499. virtual void SetUp() {
  7500. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7501. res.set_content("Hello World!", "text/plain");
  7502. });
  7503. t_ = thread(
  7504. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7505. svr_.wait_until_ready();
  7506. }
  7507. virtual void TearDown() {
  7508. svr_.stop();
  7509. t_.join();
  7510. }
  7511. #ifdef CPPHTTPLIB_SSL_ENABLED
  7512. SSLClient cli_;
  7513. SSLServer svr_;
  7514. #else
  7515. Client cli_;
  7516. Server svr_;
  7517. #endif
  7518. thread t_;
  7519. };
  7520. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7521. auto res = cli_.Get("/hi");
  7522. ASSERT_TRUE(res);
  7523. EXPECT_EQ(StatusCode::OK_200, res->status);
  7524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7525. EXPECT_EQ("Hello World!", res->body);
  7526. }
  7527. class ServerUpDownTest : public ::testing::Test {
  7528. protected:
  7529. ServerUpDownTest() : cli_(HOST, PORT) {}
  7530. virtual void SetUp() {
  7531. t_ = thread([&]() {
  7532. svr_.bind_to_any_port(HOST);
  7533. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7534. ASSERT_TRUE(svr_.listen_after_bind());
  7535. });
  7536. svr_.wait_until_ready();
  7537. }
  7538. virtual void TearDown() {
  7539. svr_.stop();
  7540. t_.join();
  7541. }
  7542. Client cli_;
  7543. Server svr_;
  7544. thread t_;
  7545. };
  7546. TEST_F(ServerUpDownTest, QuickStartStop) {
  7547. // Should not crash, especially when run with
  7548. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7549. }
  7550. class PayloadMaxLengthTest : public ::testing::Test {
  7551. protected:
  7552. PayloadMaxLengthTest()
  7553. : cli_(HOST, PORT)
  7554. #ifdef CPPHTTPLIB_SSL_ENABLED
  7555. ,
  7556. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7557. #endif
  7558. {
  7559. #ifdef CPPHTTPLIB_SSL_ENABLED
  7560. cli_.enable_server_certificate_verification(false);
  7561. #endif
  7562. }
  7563. virtual void SetUp() {
  7564. svr_.set_payload_max_length(8);
  7565. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7566. res.set_content("test", "text/plain");
  7567. });
  7568. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7569. svr_.wait_until_ready();
  7570. }
  7571. virtual void TearDown() {
  7572. svr_.stop();
  7573. t_.join();
  7574. }
  7575. #ifdef CPPHTTPLIB_SSL_ENABLED
  7576. SSLClient cli_;
  7577. SSLServer svr_;
  7578. #else
  7579. Client cli_;
  7580. Server svr_;
  7581. #endif
  7582. thread t_;
  7583. };
  7584. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7585. auto res = cli_.Post("/test", "123456789", "text/plain");
  7586. ASSERT_TRUE(res);
  7587. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7588. res = cli_.Post("/test", "12345678", "text/plain");
  7589. ASSERT_TRUE(res);
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. }
  7592. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7593. // Test chunked encoding with payload exceeding the 8-byte limit
  7594. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7595. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7596. ASSERT_TRUE(res);
  7597. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7598. }
  7599. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7600. // Test chunked encoding with payload within the 8-byte limit
  7601. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7602. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7603. ASSERT_TRUE(res);
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. }
  7606. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7607. // Test using send_request to send chunked data exceeding payload limit
  7608. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7609. "Host: " +
  7610. std::string(HOST) + ":" + std::to_string(PORT) +
  7611. "\r\n"
  7612. "Transfer-Encoding: chunked\r\n"
  7613. "Connection: close\r\n"
  7614. "\r\n"
  7615. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7616. "0123456789\r\n"
  7617. "0\r\n" // End chunk
  7618. "\r\n";
  7619. std::string response;
  7620. bool result = send_request(1, chunked_request, &response);
  7621. if (!result) {
  7622. // If send_request fails, it might be because the server closed the
  7623. // connection due to payload limit enforcement, which is acceptable
  7624. SUCCEED()
  7625. << "Server rejected oversized chunked request (connection closed)";
  7626. } else {
  7627. // If we got a response, check if it's an error response or connection was
  7628. // closed early Short response length indicates connection was closed due to
  7629. // payload limit
  7630. if (response.length() <= 10) {
  7631. SUCCEED() << "Server closed connection for oversized chunked request";
  7632. } else {
  7633. // Check for error status codes
  7634. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7635. response.find("Payload Too Large") != std::string::npos ||
  7636. response.find("400") != std::string::npos);
  7637. }
  7638. }
  7639. }
  7640. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7641. // Test request without Content-Length header exceeding payload limit
  7642. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7643. "Host: " +
  7644. std::string(HOST) + ":" +
  7645. std::to_string(PORT) +
  7646. "\r\n"
  7647. "Connection: close\r\n"
  7648. "\r\n";
  7649. // Add payload exceeding the 8-byte limit
  7650. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7651. request_without_content_length += large_payload;
  7652. std::string response;
  7653. bool result = send_request(1, request_without_content_length, &response);
  7654. if (!result) {
  7655. // If send_request fails, server likely closed connection due to payload
  7656. // limit
  7657. SUCCEED() << "Server rejected oversized request without Content-Length "
  7658. "(connection closed)";
  7659. } else {
  7660. // Check if server responded with error or closed connection early
  7661. if (response.length() <= 10) {
  7662. SUCCEED() << "Server closed connection for oversized request without "
  7663. "Content-Length";
  7664. } else {
  7665. // Check for error status codes
  7666. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7667. response.find("Payload Too Large") != std::string::npos ||
  7668. response.find("400") != std::string::npos);
  7669. }
  7670. }
  7671. }
  7672. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7673. // Test request without Content-Length header within payload limit
  7674. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7675. "Host: " +
  7676. std::string(HOST) + ":" +
  7677. std::to_string(PORT) +
  7678. "\r\n"
  7679. "Connection: close\r\n"
  7680. "\r\n";
  7681. // Add payload within the 8-byte limit
  7682. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7683. request_without_content_length += small_payload;
  7684. std::string response;
  7685. bool result = send_request(1, request_without_content_length, &response);
  7686. // For requests without Content-Length, the server may have different behavior
  7687. // The key is that it should not reject due to payload limit for small
  7688. // payloads
  7689. if (result) {
  7690. // Check for any HTTP response (success or error, but not connection closed)
  7691. if (response.length() > 10) {
  7692. SUCCEED()
  7693. << "Server processed request without Content-Length within limit";
  7694. } else {
  7695. // Short response might indicate connection closed, which is acceptable
  7696. SUCCEED() << "Server closed connection for request without "
  7697. "Content-Length (acceptable behavior)";
  7698. }
  7699. } else {
  7700. // Connection failure might be due to protocol requirements
  7701. SUCCEED() << "Connection issue with request without Content-Length "
  7702. "(environment-specific)";
  7703. }
  7704. }
  7705. class LargePayloadMaxLengthTest : public ::testing::Test {
  7706. protected:
  7707. LargePayloadMaxLengthTest()
  7708. : cli_(HOST, PORT)
  7709. #ifdef CPPHTTPLIB_SSL_ENABLED
  7710. ,
  7711. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7712. #endif
  7713. {
  7714. #ifdef CPPHTTPLIB_SSL_ENABLED
  7715. cli_.enable_server_certificate_verification(false);
  7716. #endif
  7717. }
  7718. virtual void SetUp() {
  7719. // Set 10MB payload limit
  7720. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7721. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7722. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7723. res.set_content("Large payload test", "text/plain");
  7724. });
  7725. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7726. svr_.wait_until_ready();
  7727. }
  7728. virtual void TearDown() {
  7729. svr_.stop();
  7730. t_.join();
  7731. }
  7732. #ifdef CPPHTTPLIB_SSL_ENABLED
  7733. SSLClient cli_;
  7734. SSLServer svr_;
  7735. #else
  7736. Client cli_;
  7737. Server svr_;
  7738. #endif
  7739. thread t_;
  7740. };
  7741. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7742. // Test chunked encoding with payload within 10MB limit
  7743. std::string medium_payload(5 * 1024 * 1024,
  7744. 'A'); // 5MB payload, within 10MB limit
  7745. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7746. ASSERT_TRUE(res);
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. }
  7749. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7750. // Test chunked encoding with payload exceeding 10MB limit
  7751. std::string large_payload(12 * 1024 * 1024,
  7752. 'B'); // 12MB payload, exceeds 10MB limit
  7753. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7754. // Server may either return 413 or close the connection
  7755. if (res) {
  7756. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7757. } else {
  7758. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7759. }
  7760. }
  7761. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7762. // Test request without Content-Length header within 10MB limit
  7763. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7764. "Host: " +
  7765. std::string(HOST) + ":" +
  7766. std::to_string(PORT) +
  7767. "\r\n"
  7768. "Connection: close\r\n"
  7769. "\r\n";
  7770. // Add 1MB payload (within 10MB limit)
  7771. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7772. request_without_content_length += medium_payload;
  7773. std::string response;
  7774. bool result = send_request(5, request_without_content_length, &response);
  7775. if (result) {
  7776. // Should get a proper HTTP response for payloads within limit
  7777. if (response.length() > 10) {
  7778. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7779. "10MB limit";
  7780. } else {
  7781. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7782. "Content-Length)";
  7783. }
  7784. } else {
  7785. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7786. }
  7787. }
  7788. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7789. // Test request without Content-Length header exceeding 10MB limit
  7790. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7791. "Host: " +
  7792. std::string(HOST) + ":" +
  7793. std::to_string(PORT) +
  7794. "\r\n"
  7795. "Connection: close\r\n"
  7796. "\r\n";
  7797. // Add 12MB payload (exceeds 10MB limit)
  7798. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7799. request_without_content_length += large_payload;
  7800. std::string response;
  7801. bool result = send_request(10, request_without_content_length, &response);
  7802. if (!result) {
  7803. // Server should close connection due to payload limit
  7804. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7805. "(connection closed)";
  7806. } else {
  7807. // Check for error response
  7808. if (response.length() <= 10) {
  7809. SUCCEED()
  7810. << "Server closed connection for 12MB request exceeding 10MB limit";
  7811. } else {
  7812. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7813. response.find("Payload Too Large") != std::string::npos ||
  7814. response.find("400") != std::string::npos);
  7815. }
  7816. }
  7817. }
  7818. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7819. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7820. // path.
  7821. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7822. Server svr;
  7823. const size_t LIMIT = 64 * 1024; // 64KB
  7824. svr.set_payload_max_length(LIMIT);
  7825. size_t total = 0;
  7826. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7827. const ContentReader &content_reader) {
  7828. content_reader([&](const char * /*data*/, size_t len) {
  7829. total += len;
  7830. return true;
  7831. });
  7832. res.status = 200;
  7833. res.set_content("stream_ok", "text/plain");
  7834. });
  7835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7836. auto se = detail::scope_exit([&] {
  7837. svr.stop();
  7838. thread.join();
  7839. ASSERT_FALSE(svr.is_running());
  7840. });
  7841. svr.wait_until_ready();
  7842. // Prepare 256KB raw data and gzip-compress it
  7843. std::string raw(256 * 1024, 'A');
  7844. std::string gz;
  7845. {
  7846. z_stream zs{};
  7847. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7848. Z_DEFAULT_STRATEGY);
  7849. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7850. zs.avail_in = static_cast<uInt>(raw.size());
  7851. char outbuf[4096];
  7852. int ret;
  7853. do {
  7854. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7855. zs.avail_out = sizeof(outbuf);
  7856. ret = deflate(&zs, Z_FINISH);
  7857. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7858. } while (ret != Z_STREAM_END);
  7859. deflateEnd(&zs);
  7860. }
  7861. Client cli(HOST, PORT);
  7862. cli.set_connection_timeout(std::chrono::seconds(5));
  7863. Headers headers = {{"Content-Encoding", "gzip"}};
  7864. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7865. "application/octet-stream");
  7866. ASSERT_TRUE(res);
  7867. // Server must reject oversized decompressed payloads with 413.
  7868. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7869. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7870. EXPECT_LE(total, LIMIT);
  7871. }
  7872. #endif
  7873. // Regression test for DoS vulnerability: a malicious server sending a response
  7874. // without Content-Length header must not cause unbounded memory consumption on
  7875. // the client side. The client should stop reading after a reasonable limit,
  7876. // similar to the server-side set_payload_max_length protection.
  7877. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7878. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7879. #ifndef _WIN32
  7880. signal(SIGPIPE, SIG_IGN);
  7881. #endif
  7882. auto server_thread = std::thread([] {
  7883. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7885. default_socket_options(srv);
  7886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7888. sockaddr_in addr{};
  7889. addr.sin_family = AF_INET;
  7890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7892. int opt = 1;
  7893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7894. #ifdef _WIN32
  7895. reinterpret_cast<const char *>(&opt),
  7896. #else
  7897. &opt,
  7898. #endif
  7899. sizeof(opt));
  7900. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7901. ::listen(srv, 1);
  7902. sockaddr_in cli_addr{};
  7903. socklen_t cli_len = sizeof(cli_addr);
  7904. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7905. if (cli != INVALID_SOCKET) {
  7906. char buf[4096];
  7907. ::recv(cli, buf, sizeof(buf), 0);
  7908. // Malicious response: no Content-Length, no chunked encoding
  7909. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7910. "Connection: close\r\n"
  7911. "\r\n";
  7912. ::send(cli,
  7913. #ifdef _WIN32
  7914. static_cast<const char *>(response_header.c_str()),
  7915. static_cast<int>(response_header.size()),
  7916. #else
  7917. response_header.c_str(), response_header.size(),
  7918. #endif
  7919. 0);
  7920. // Send 10MB of data
  7921. std::string chunk(64 * 1024, 'A');
  7922. size_t total_sent = 0;
  7923. while (total_sent < MALICIOUS_DATA_SIZE) {
  7924. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7925. auto sent = ::send(cli,
  7926. #ifdef _WIN32
  7927. static_cast<const char *>(chunk.c_str()),
  7928. static_cast<int>(to_send),
  7929. #else
  7930. chunk.c_str(), to_send,
  7931. #endif
  7932. 0);
  7933. if (sent <= 0) break;
  7934. total_sent += static_cast<size_t>(sent);
  7935. }
  7936. detail::close_socket(cli);
  7937. }
  7938. detail::close_socket(srv);
  7939. });
  7940. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7941. size_t total_read = 0;
  7942. {
  7943. Client cli("127.0.0.1", PORT + 2);
  7944. cli.set_read_timeout(5, 0);
  7945. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7946. auto stream = cli.open_stream("GET", "/malicious");
  7947. ASSERT_TRUE(stream.is_valid());
  7948. char buffer[64 * 1024];
  7949. ssize_t n;
  7950. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7951. total_read += static_cast<size_t>(n);
  7952. }
  7953. } // StreamHandle and Client destroyed here, closing the socket
  7954. server_thread.join();
  7955. // With set_payload_max_length, the client must stop reading before consuming
  7956. // all 10MB. The read loop should be cut off at or near the configured limit.
  7957. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7958. << "Client read " << total_read << " bytes, exceeding the configured "
  7959. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7960. }
  7961. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7962. // the entire response body without truncation.
  7963. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7964. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7965. #ifndef _WIN32
  7966. signal(SIGPIPE, SIG_IGN);
  7967. #endif
  7968. auto server_thread = std::thread([] {
  7969. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7970. default_socket_options(srv);
  7971. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7972. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7973. sockaddr_in addr{};
  7974. addr.sin_family = AF_INET;
  7975. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7976. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7977. int opt = 1;
  7978. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7979. #ifdef _WIN32
  7980. reinterpret_cast<const char *>(&opt),
  7981. #else
  7982. &opt,
  7983. #endif
  7984. sizeof(opt));
  7985. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7986. ::listen(srv, 1);
  7987. sockaddr_in cli_addr{};
  7988. socklen_t cli_len = sizeof(cli_addr);
  7989. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7990. if (cli != INVALID_SOCKET) {
  7991. char buf[4096];
  7992. ::recv(cli, buf, sizeof(buf), 0);
  7993. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7994. "Connection: close\r\n"
  7995. "\r\n";
  7996. ::send(cli,
  7997. #ifdef _WIN32
  7998. static_cast<const char *>(response_header.c_str()),
  7999. static_cast<int>(response_header.size()),
  8000. #else
  8001. response_header.c_str(), response_header.size(),
  8002. #endif
  8003. 0);
  8004. std::string chunk(64 * 1024, 'A');
  8005. size_t total_sent = 0;
  8006. while (total_sent < DATA_SIZE) {
  8007. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8008. auto sent = ::send(cli,
  8009. #ifdef _WIN32
  8010. static_cast<const char *>(chunk.c_str()),
  8011. static_cast<int>(to_send),
  8012. #else
  8013. chunk.c_str(), to_send,
  8014. #endif
  8015. 0);
  8016. if (sent <= 0) break;
  8017. total_sent += static_cast<size_t>(sent);
  8018. }
  8019. #ifdef _WIN32
  8020. ::shutdown(cli, SD_SEND);
  8021. #else
  8022. ::shutdown(cli, SHUT_WR);
  8023. #endif
  8024. // Drain until the client closes its end, ensuring all data is delivered
  8025. char drain[1024];
  8026. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8027. detail::close_socket(cli);
  8028. }
  8029. detail::close_socket(srv);
  8030. });
  8031. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8032. size_t total_read = 0;
  8033. {
  8034. Client cli("127.0.0.1", PORT + 2);
  8035. cli.set_read_timeout(5, 0);
  8036. cli.set_payload_max_length(0); // 0 means no limit
  8037. auto stream = cli.open_stream("GET", "/data");
  8038. ASSERT_TRUE(stream.is_valid());
  8039. char buffer[64 * 1024];
  8040. ssize_t n;
  8041. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8042. total_read += static_cast<size_t>(n);
  8043. }
  8044. }
  8045. server_thread.join();
  8046. EXPECT_EQ(total_read, DATA_SIZE)
  8047. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8048. << " bytes without truncation, but only read " << total_read << " bytes.";
  8049. }
  8050. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8051. // enormous Content-Length must not cause the client to pre-allocate a huge
  8052. // response body buffer. The reservation is capped at payload_max_length_, and
  8053. // the read itself fails when the body exceeds the limit.
  8054. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8055. #ifndef _WIN32
  8056. signal(SIGPIPE, SIG_IGN);
  8057. #endif
  8058. auto server_thread = std::thread([] {
  8059. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8060. default_socket_options(srv);
  8061. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8062. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8063. sockaddr_in addr{};
  8064. addr.sin_family = AF_INET;
  8065. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8066. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8067. int opt = 1;
  8068. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8069. #ifdef _WIN32
  8070. reinterpret_cast<const char *>(&opt),
  8071. #else
  8072. &opt,
  8073. #endif
  8074. sizeof(opt));
  8075. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8076. ::listen(srv, 1);
  8077. sockaddr_in cli_addr{};
  8078. socklen_t cli_len = sizeof(cli_addr);
  8079. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8080. if (cli != INVALID_SOCKET) {
  8081. char buf[4096];
  8082. ::recv(cli, buf, sizeof(buf), 0);
  8083. // Malicious response: claim a 20GB body but send only a tiny payload.
  8084. std::string response = "HTTP/1.1 200 OK\r\n"
  8085. "Content-Length: 20000000000\r\n"
  8086. "\r\n"
  8087. "abc";
  8088. ::send(cli,
  8089. #ifdef _WIN32
  8090. static_cast<const char *>(response.c_str()),
  8091. static_cast<int>(response.size()),
  8092. #else
  8093. response.c_str(), response.size(),
  8094. #endif
  8095. 0);
  8096. detail::close_socket(cli);
  8097. }
  8098. detail::close_socket(srv);
  8099. });
  8100. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8101. {
  8102. Client cli("127.0.0.1", PORT + 2);
  8103. cli.set_read_timeout(5, 0);
  8104. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8105. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8106. // (server claims more bytes than payload_max_length permits), but it must
  8107. // not exhaust memory before getting there.
  8108. auto res = cli.Get("/malicious");
  8109. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8110. }
  8111. server_thread.join();
  8112. }
  8113. // Verify that content_receiver bypasses the default payload_max_length,
  8114. // allowing streaming downloads larger than 100MB without requiring an explicit
  8115. // set_payload_max_length call.
  8116. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8117. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8118. #ifndef _WIN32
  8119. signal(SIGPIPE, SIG_IGN);
  8120. #endif
  8121. auto server_thread = std::thread([] {
  8122. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8123. default_socket_options(srv);
  8124. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8125. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8126. sockaddr_in addr{};
  8127. addr.sin_family = AF_INET;
  8128. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8129. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8130. int opt = 1;
  8131. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8132. #ifdef _WIN32
  8133. reinterpret_cast<const char *>(&opt),
  8134. #else
  8135. &opt,
  8136. #endif
  8137. sizeof(opt));
  8138. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8139. ::listen(srv, 1);
  8140. sockaddr_in cli_addr{};
  8141. socklen_t cli_len = sizeof(cli_addr);
  8142. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8143. if (cli != INVALID_SOCKET) {
  8144. char buf[4096];
  8145. ::recv(cli, buf, sizeof(buf), 0);
  8146. // Response with Content-Length larger than default 100MB limit
  8147. auto content_length = std::to_string(DATA_SIZE);
  8148. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8149. "Content-Length: " +
  8150. content_length +
  8151. "\r\n"
  8152. "Connection: close\r\n"
  8153. "\r\n";
  8154. ::send(cli,
  8155. #ifdef _WIN32
  8156. static_cast<const char *>(response_header.c_str()),
  8157. static_cast<int>(response_header.size()),
  8158. #else
  8159. response_header.c_str(), response_header.size(),
  8160. #endif
  8161. 0);
  8162. std::string chunk(64 * 1024, 'A');
  8163. size_t total_sent = 0;
  8164. while (total_sent < DATA_SIZE) {
  8165. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8166. auto sent = ::send(cli,
  8167. #ifdef _WIN32
  8168. static_cast<const char *>(chunk.c_str()),
  8169. static_cast<int>(to_send),
  8170. #else
  8171. chunk.c_str(), to_send,
  8172. #endif
  8173. 0);
  8174. if (sent <= 0) break;
  8175. total_sent += static_cast<size_t>(sent);
  8176. }
  8177. detail::close_socket(cli);
  8178. }
  8179. detail::close_socket(srv);
  8180. });
  8181. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8182. size_t total_received = 0;
  8183. {
  8184. Client cli("127.0.0.1", PORT + 2);
  8185. cli.set_read_timeout(10, 0);
  8186. // Do NOT call set_payload_max_length — use the default 100MB limit
  8187. auto res =
  8188. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8189. total_received += data_length;
  8190. return true;
  8191. });
  8192. ASSERT_TRUE(res);
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. server_thread.join();
  8196. EXPECT_EQ(total_received, DATA_SIZE)
  8197. << "With content_receiver, the client should read all " << DATA_SIZE
  8198. << " bytes despite the default 100MB payload_max_length, but only read "
  8199. << total_received << " bytes.";
  8200. }
  8201. // Verify that an explicit set_payload_max_length smaller than the response is
  8202. // enforced even when a content_receiver is used.
  8203. TEST(ClientVulnerabilityTest,
  8204. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8205. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8206. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8207. #ifndef _WIN32
  8208. signal(SIGPIPE, SIG_IGN);
  8209. #endif
  8210. auto server_thread = std::thread([] {
  8211. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8212. default_socket_options(srv);
  8213. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8214. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8215. sockaddr_in addr{};
  8216. addr.sin_family = AF_INET;
  8217. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8218. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8219. int opt = 1;
  8220. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8221. #ifdef _WIN32
  8222. reinterpret_cast<const char *>(&opt),
  8223. #else
  8224. &opt,
  8225. #endif
  8226. sizeof(opt));
  8227. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8228. ::listen(srv, 1);
  8229. sockaddr_in cli_addr{};
  8230. socklen_t cli_len = sizeof(cli_addr);
  8231. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8232. if (cli != INVALID_SOCKET) {
  8233. char buf[4096];
  8234. ::recv(cli, buf, sizeof(buf), 0);
  8235. auto content_length = std::to_string(DATA_SIZE);
  8236. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8237. "Content-Length: " +
  8238. content_length +
  8239. "\r\n"
  8240. "Connection: close\r\n"
  8241. "\r\n";
  8242. ::send(cli,
  8243. #ifdef _WIN32
  8244. static_cast<const char *>(response_header.c_str()),
  8245. static_cast<int>(response_header.size()),
  8246. #else
  8247. response_header.c_str(), response_header.size(),
  8248. #endif
  8249. 0);
  8250. std::string chunk(64 * 1024, 'A');
  8251. size_t total_sent = 0;
  8252. while (total_sent < DATA_SIZE) {
  8253. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8254. auto sent = ::send(cli,
  8255. #ifdef _WIN32
  8256. static_cast<const char *>(chunk.c_str()),
  8257. static_cast<int>(to_send),
  8258. #else
  8259. chunk.c_str(), to_send,
  8260. #endif
  8261. 0);
  8262. if (sent <= 0) break;
  8263. total_sent += static_cast<size_t>(sent);
  8264. }
  8265. detail::close_socket(cli);
  8266. }
  8267. detail::close_socket(srv);
  8268. });
  8269. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8270. size_t total_received = 0;
  8271. {
  8272. Client cli("127.0.0.1", PORT + 2);
  8273. cli.set_read_timeout(10, 0);
  8274. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8275. auto res =
  8276. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8277. total_received += data_length;
  8278. return true;
  8279. });
  8280. // Should fail because 200MB exceeds the explicit 150MB limit
  8281. EXPECT_FALSE(res);
  8282. }
  8283. server_thread.join();
  8284. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8285. << "Client with content_receiver should respect the explicit "
  8286. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8287. << total_received << " bytes.";
  8288. }
  8289. // Verify that an explicit set_payload_max_length larger than the response
  8290. // allows the content_receiver to read all data successfully.
  8291. TEST(ClientVulnerabilityTest,
  8292. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8293. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8294. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8295. #ifndef _WIN32
  8296. signal(SIGPIPE, SIG_IGN);
  8297. #endif
  8298. auto server_thread = std::thread([] {
  8299. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8300. default_socket_options(srv);
  8301. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8302. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8303. sockaddr_in addr{};
  8304. addr.sin_family = AF_INET;
  8305. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8306. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8307. int opt = 1;
  8308. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8309. #ifdef _WIN32
  8310. reinterpret_cast<const char *>(&opt),
  8311. #else
  8312. &opt,
  8313. #endif
  8314. sizeof(opt));
  8315. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8316. ::listen(srv, 1);
  8317. sockaddr_in cli_addr{};
  8318. socklen_t cli_len = sizeof(cli_addr);
  8319. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8320. if (cli != INVALID_SOCKET) {
  8321. char buf[4096];
  8322. ::recv(cli, buf, sizeof(buf), 0);
  8323. auto content_length = std::to_string(DATA_SIZE);
  8324. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8325. "Content-Length: " +
  8326. content_length +
  8327. "\r\n"
  8328. "Connection: close\r\n"
  8329. "\r\n";
  8330. ::send(cli,
  8331. #ifdef _WIN32
  8332. static_cast<const char *>(response_header.c_str()),
  8333. static_cast<int>(response_header.size()),
  8334. #else
  8335. response_header.c_str(), response_header.size(),
  8336. #endif
  8337. 0);
  8338. std::string chunk(64 * 1024, 'A');
  8339. size_t total_sent = 0;
  8340. while (total_sent < DATA_SIZE) {
  8341. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8342. auto sent = ::send(cli,
  8343. #ifdef _WIN32
  8344. static_cast<const char *>(chunk.c_str()),
  8345. static_cast<int>(to_send),
  8346. #else
  8347. chunk.c_str(), to_send,
  8348. #endif
  8349. 0);
  8350. if (sent <= 0) break;
  8351. total_sent += static_cast<size_t>(sent);
  8352. }
  8353. #ifdef _WIN32
  8354. ::shutdown(cli, SD_SEND);
  8355. #else
  8356. ::shutdown(cli, SHUT_WR);
  8357. #endif
  8358. char drain[1024];
  8359. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8360. detail::close_socket(cli);
  8361. }
  8362. detail::close_socket(srv);
  8363. });
  8364. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8365. size_t total_received = 0;
  8366. {
  8367. Client cli("127.0.0.1", PORT + 2);
  8368. cli.set_read_timeout(10, 0);
  8369. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8370. auto res =
  8371. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8372. total_received += data_length;
  8373. return true;
  8374. });
  8375. ASSERT_TRUE(res);
  8376. EXPECT_EQ(StatusCode::OK_200, res->status);
  8377. }
  8378. server_thread.join();
  8379. EXPECT_EQ(total_received, DATA_SIZE)
  8380. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8381. << " bytes (larger than " << DATA_SIZE
  8382. << " bytes response), content_receiver should read all data, but only "
  8383. "read "
  8384. << total_received << " bytes.";
  8385. }
  8386. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8387. // Regression test for "zip bomb" attack on the client side: a malicious server
  8388. // sends a small gzip-compressed response that decompresses to a huge payload.
  8389. // The client must enforce payload_max_length on the decompressed size.
  8390. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8391. constexpr size_t DECOMPRESSED_SIZE =
  8392. 10 * 1024 * 1024; // 10MB after decompression
  8393. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8394. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8395. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8396. std::string compressed;
  8397. {
  8398. httplib::detail::gzip_compressor compressor;
  8399. bool ok =
  8400. compressor.compress(uncompressed.data(), uncompressed.size(),
  8401. /*last=*/true, [&](const char *buf, size_t len) {
  8402. compressed.append(buf, len);
  8403. return true;
  8404. });
  8405. ASSERT_TRUE(ok);
  8406. }
  8407. // Sanity: compressed data should be much smaller than the decompressed size
  8408. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8409. #ifndef _WIN32
  8410. signal(SIGPIPE, SIG_IGN);
  8411. #endif
  8412. // Set up the listening socket in the main thread so the server is guaranteed
  8413. // to be ready before the client connects (eliminates race condition).
  8414. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8415. default_socket_options(srv);
  8416. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8417. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8418. sockaddr_in addr{};
  8419. addr.sin_family = AF_INET;
  8420. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8421. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8422. int opt = 1;
  8423. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8424. #ifdef _WIN32
  8425. reinterpret_cast<const char *>(&opt),
  8426. #else
  8427. &opt,
  8428. #endif
  8429. sizeof(opt));
  8430. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8431. ASSERT_EQ(0, ::listen(srv, 1));
  8432. auto server_thread = std::thread([&compressed, srv] {
  8433. sockaddr_in cli_addr{};
  8434. socklen_t cli_len = sizeof(cli_addr);
  8435. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8436. if (cli != INVALID_SOCKET) {
  8437. // Read the full HTTP request (until \r\n\r\n)
  8438. char buf[4096];
  8439. size_t total = 0;
  8440. while (total < sizeof(buf)) {
  8441. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8442. if (n <= 0) break;
  8443. total += static_cast<size_t>(n);
  8444. // Check for end of headers
  8445. if (total >= 4) {
  8446. std::string req(buf, total);
  8447. if (req.find("\r\n\r\n") != std::string::npos) break;
  8448. }
  8449. }
  8450. // Malicious response: gzip-compressed body, no Content-Length
  8451. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8452. "Content-Encoding: gzip\r\n"
  8453. "Connection: close\r\n"
  8454. "\r\n";
  8455. ::send(cli,
  8456. #ifdef _WIN32
  8457. static_cast<const char *>(response_header.c_str()),
  8458. static_cast<int>(response_header.size()),
  8459. #else
  8460. response_header.c_str(), response_header.size(),
  8461. #endif
  8462. 0);
  8463. // Send the compressed payload (small on the wire, huge when decompressed)
  8464. size_t total_sent = 0;
  8465. while (total_sent < compressed.size()) {
  8466. auto to_send = std::min(compressed.size() - total_sent,
  8467. static_cast<size_t>(64 * 1024));
  8468. auto sent =
  8469. ::send(cli,
  8470. #ifdef _WIN32
  8471. static_cast<const char *>(compressed.c_str() + total_sent),
  8472. static_cast<int>(to_send),
  8473. #else
  8474. compressed.c_str() + total_sent, to_send,
  8475. #endif
  8476. 0);
  8477. if (sent <= 0) break;
  8478. total_sent += static_cast<size_t>(sent);
  8479. }
  8480. detail::close_socket(cli);
  8481. }
  8482. });
  8483. auto se = detail::scope_exit([&] {
  8484. detail::close_socket(srv);
  8485. server_thread.join();
  8486. });
  8487. size_t total_decompressed = 0;
  8488. {
  8489. Client cli("127.0.0.1", PORT + 3);
  8490. cli.set_read_timeout(5, 0);
  8491. cli.set_decompress(true);
  8492. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8493. auto stream = cli.open_stream("GET", "/zipbomb");
  8494. ASSERT_TRUE(stream.is_valid());
  8495. char buffer[64 * 1024];
  8496. ssize_t n;
  8497. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8498. total_decompressed += static_cast<size_t>(n);
  8499. }
  8500. }
  8501. // The decompressed size must be capped by payload_max_length. Without
  8502. // protection, the client would decompress the full 10MB from a tiny
  8503. // compressed payload, enabling a zip bomb DoS attack.
  8504. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8505. << "Client decompressed " << total_decompressed
  8506. << " bytes from a gzip response. The decompressed size should be "
  8507. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8508. }
  8509. #endif
  8510. TEST(HostAndPortPropertiesTest, NoSSL) {
  8511. httplib::Client cli("www.google.com", 1234);
  8512. ASSERT_EQ("www.google.com", cli.host());
  8513. ASSERT_EQ(1234, cli.port());
  8514. }
  8515. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8516. httplib::Client cli("www.google.com:1234");
  8517. ASSERT_EQ("www.google.com", cli.host());
  8518. ASSERT_EQ(1234, cli.port());
  8519. }
  8520. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8521. // Port number that overflows int — should not crash, client becomes invalid
  8522. httplib::Client cli("http://www.google.com:99999999999999999999");
  8523. ASSERT_FALSE(cli.is_valid());
  8524. }
  8525. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8526. // Port 99999 exceeds valid range (1-65535) — should not crash
  8527. httplib::Client cli("http://www.google.com:99999");
  8528. ASSERT_FALSE(cli.is_valid());
  8529. }
  8530. #ifdef CPPHTTPLIB_SSL_ENABLED
  8531. TEST(HostAndPortPropertiesTest, SSL) {
  8532. httplib::SSLClient cli("www.google.com");
  8533. ASSERT_EQ("www.google.com", cli.host());
  8534. ASSERT_EQ(443, cli.port());
  8535. }
  8536. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8537. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8538. std::string cert;
  8539. read_file(CA_CERT_FILE, cert);
  8540. httplib::SSLClient httplib_client("www.google.com");
  8541. // Load CA store first time
  8542. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8543. // Load CA store second time (update)
  8544. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8545. // Verify client is still valid and can make connections
  8546. httplib_client.enable_server_certificate_verification(true);
  8547. auto res = httplib_client.Get("/");
  8548. ASSERT_TRUE(res);
  8549. // Google may return 200 or 301 depending on various factors
  8550. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8551. res->status == StatusCode::MovedPermanently_301);
  8552. }
  8553. TEST(SSLClientTest, ServerNameIndication_Online) {
  8554. auto host = "httpbingo.org";
  8555. auto path = std::string{"/get"};
  8556. SSLClient cli(host, 443);
  8557. auto res = cli.Get(path);
  8558. ASSERT_TRUE(res);
  8559. ASSERT_EQ(StatusCode::OK_200, res->status);
  8560. }
  8561. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8562. // Use a site that will cause SSL verification failure due to self-signed cert
  8563. SSLClient cli("self-signed.badssl.com", 443);
  8564. cli.enable_server_certificate_verification(true);
  8565. auto res = cli.Get("/");
  8566. ASSERT_TRUE(!res);
  8567. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8568. // Verify backend error is captured for SSLServerVerification
  8569. // This occurs when certificate verification fails
  8570. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8571. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8572. EXPECT_NE(0UL, res.ssl_backend_error());
  8573. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8574. // For OpenSSL, ssl_error is 0 for verification errors
  8575. EXPECT_EQ(0, res.ssl_error());
  8576. #if !defined(_WIN32) || \
  8577. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8578. // On non-Windows or when Windows Schannel is disabled, the error comes
  8579. // from OpenSSL's verification
  8580. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8581. res.ssl_backend_error());
  8582. #endif
  8583. #endif
  8584. }
  8585. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8586. // Use a site where hostname doesn't match the certificate
  8587. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8588. SSLClient cli("wrong.host.badssl.com", 443);
  8589. cli.enable_server_certificate_verification(true);
  8590. cli.enable_server_hostname_verification(true);
  8591. auto res = cli.Get("/");
  8592. ASSERT_TRUE(!res);
  8593. // The error type depends on when hostname verification occurs:
  8594. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8595. // - Mbed TLS: SSLServerVerification (during handshake)
  8596. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8597. res.error() == Error::SSLServerVerification);
  8598. // Verify backend error is captured for hostname verification failure
  8599. EXPECT_NE(0UL, res.ssl_backend_error());
  8600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8601. // For OpenSSL, ssl_error is 0 for verification errors
  8602. EXPECT_EQ(0, res.ssl_error());
  8603. #if !defined(_WIN32) || \
  8604. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8605. // On non-Windows or when Windows Schannel is disabled, the error comes
  8606. // from OpenSSL's hostname verification
  8607. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8608. res.ssl_backend_error());
  8609. #endif
  8610. #endif
  8611. }
  8612. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8613. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8614. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8615. SSLClient cli("www.google.com", 443);
  8616. cli.enable_server_certificate_verification(true);
  8617. auto res = cli.Get("/");
  8618. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8619. }
  8620. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8621. SSLClient cli("www.google.com", 443);
  8622. cli.enable_server_certificate_verification(true);
  8623. cli.enable_windows_certificate_verification(false);
  8624. auto res = cli.Get("/");
  8625. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8626. }
  8627. #endif
  8628. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8629. Client cli("https://google.com");
  8630. auto res = cli.Get("/");
  8631. ASSERT_TRUE(res);
  8632. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8633. }
  8634. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8635. SSLClient cli("google.com");
  8636. cli.set_ca_cert_path(CA_CERT_FILE);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res);
  8639. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8640. }
  8641. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8642. SSLClient cli("google.com");
  8643. cli.enable_server_certificate_verification(true);
  8644. cli.set_ca_cert_path("hello");
  8645. auto res = cli.Get("/");
  8646. ASSERT_TRUE(!res);
  8647. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8648. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8649. // should be set
  8650. EXPECT_EQ(0, res.ssl_error());
  8651. // Verify backend error is captured for SSLLoadingCerts
  8652. // This error occurs when loading CA certificates fails
  8653. EXPECT_NE(0UL, res.ssl_backend_error());
  8654. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8655. // OpenSSL specific error codes:
  8656. // > openssl errstr 0x80000002
  8657. // error:80000002:system library::No such file or directory
  8658. // > openssl errstr 0xA000126
  8659. // error:0A000126:SSL routines::unexpected eof while reading
  8660. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8661. res.ssl_backend_error() == 0xA000126);
  8662. #endif
  8663. }
  8664. TEST(SSLClientTest, ServerCertificateVerification4) {
  8665. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8666. ASSERT_TRUE(svr.is_valid());
  8667. svr.Get("/test", [&](const Request &, Response &res) {
  8668. res.set_content("test", "text/plain");
  8669. svr.stop();
  8670. ASSERT_TRUE(true);
  8671. });
  8672. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8673. auto se = detail::scope_exit([&] {
  8674. t.join();
  8675. ASSERT_FALSE(svr.is_running());
  8676. });
  8677. svr.wait_until_ready();
  8678. SSLClient cli("127.0.0.1", PORT);
  8679. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8680. cli.enable_server_certificate_verification(true);
  8681. cli.set_connection_timeout(30);
  8682. auto res = cli.Get("/test");
  8683. ASSERT_TRUE(res);
  8684. ASSERT_EQ(StatusCode::OK_200, res->status);
  8685. }
  8686. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8687. std::string cert;
  8688. read_file(CA_CERT_FILE, cert);
  8689. SSLClient cli("google.com");
  8690. cli.load_ca_cert_store(cert.data(), cert.size());
  8691. const auto res = cli.Get("/");
  8692. ASSERT_TRUE(res);
  8693. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8694. }
  8695. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8696. // clang-format off
  8697. static constexpr char cert[] =
  8698. "GlobalSign Root CA\n"
  8699. "==================\n"
  8700. "-----BEGIN CERTIFICATE-----\n"
  8701. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8702. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8703. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8704. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8705. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8706. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8707. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8708. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8709. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8710. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8711. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8712. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8713. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8714. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8715. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8716. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8717. "-----END CERTIFICATE-----\n";
  8718. // clang-format on
  8719. SSLClient cli("google.com");
  8720. cli.load_ca_cert_store(cert, sizeof(cert));
  8721. const auto res = cli.Get("/");
  8722. ASSERT_TRUE(res);
  8723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8724. }
  8725. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8726. SSLClient cli("www.youtube.com");
  8727. cli.set_ca_cert_path(CA_CERT_FILE);
  8728. cli.enable_server_certificate_verification(true);
  8729. cli.set_follow_location(true);
  8730. auto res = cli.Get("/");
  8731. ASSERT_TRUE(res);
  8732. ASSERT_EQ(StatusCode::OK_200, res->status);
  8733. }
  8734. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8735. SSLClient cli("wWw.YouTube.Com");
  8736. cli.set_ca_cert_path(CA_CERT_FILE);
  8737. cli.enable_server_certificate_verification(true);
  8738. cli.enable_server_hostname_verification(true);
  8739. cli.set_follow_location(true);
  8740. auto res = cli.Get("/");
  8741. ASSERT_TRUE(res);
  8742. ASSERT_EQ(StatusCode::OK_200, res->status);
  8743. }
  8744. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8745. SSLClient cli("gOoGlE.COm");
  8746. cli.enable_server_certificate_verification(true);
  8747. cli.enable_server_hostname_verification(true);
  8748. cli.set_follow_location(true);
  8749. auto res = cli.Get("/");
  8750. ASSERT_TRUE(res);
  8751. ASSERT_EQ(StatusCode::OK_200, res->status);
  8752. }
  8753. TEST(SSLClientTest, Issue2004_Online) {
  8754. Client client("https://google.com");
  8755. client.set_follow_location(true);
  8756. auto res = client.Get("/");
  8757. ASSERT_TRUE(res);
  8758. ASSERT_EQ(StatusCode::OK_200, res->status);
  8759. auto body = res->body;
  8760. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8761. }
  8762. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8763. // Create SSLClient with invalid cert/key to make is_valid() return false
  8764. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8765. "nonexistent_key.pem");
  8766. // is_valid() should be false due to cert loading failure
  8767. ASSERT_FALSE(cli.is_valid());
  8768. auto res = cli.Get("/");
  8769. ASSERT_FALSE(res);
  8770. EXPECT_EQ(Error::SSLConnection, res.error());
  8771. }
  8772. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8773. // Test for Issue #2251: SSL error not properly reported when client cert
  8774. // and key paths are swapped or mismatched
  8775. // This simulates the scenario where user accidentally swaps the cert and key
  8776. // files
  8777. // Using client cert file as private key and vice versa (completely wrong)
  8778. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8779. // Should fail validation due to cert/key mismatch
  8780. ASSERT_FALSE(cli.is_valid());
  8781. // Attempt to make a request should fail with proper error
  8782. auto res = cli.Get("/");
  8783. ASSERT_FALSE(res);
  8784. EXPECT_EQ(Error::SSLConnection, res.error());
  8785. // SSL error should be recorded in the Result object (this is the key fix for
  8786. // Issue #2251)
  8787. auto backend_error = res.ssl_backend_error();
  8788. EXPECT_NE(0u, backend_error);
  8789. }
  8790. // Tests cert/key mismatch detection at the TLS context level
  8791. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8792. // Test that using mismatched cert/key causes connection failure.
  8793. // We verify this at the SSLClient level rather than through internal
  8794. // TLS API functions.
  8795. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8796. cli.enable_server_certificate_verification(false);
  8797. cli.set_connection_timeout(2);
  8798. // The mismatch should cause a connection or handshake error
  8799. auto res = cli.Get("/test");
  8800. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8801. // Either way, the request should fail
  8802. EXPECT_FALSE(res);
  8803. }
  8804. #endif
  8805. #if 0
  8806. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8807. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8808. ASSERT_TRUE(cli != nullptr);
  8809. cli->set_address_family(AF_INET6);
  8810. cli->set_interface("en0");
  8811. auto res = cli->Get("/get");
  8812. ASSERT_TRUE(res);
  8813. ASSERT_EQ(StatusCode::OK_200, res->status);
  8814. }
  8815. #endif
  8816. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8817. #ifdef CPPHTTPLIB_SSL_ENABLED
  8818. void ClientCertPresent(
  8819. const std::string &client_cert_file,
  8820. const std::string &client_private_key_file,
  8821. const std::string &client_encrypted_private_key_pass = std::string()) {
  8822. using namespace httplib::tls;
  8823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8824. CLIENT_CA_CERT_DIR);
  8825. ASSERT_TRUE(svr.is_valid());
  8826. svr.Get("/test", [&](const Request &req, Response &res) {
  8827. res.set_content("test", "text/plain");
  8828. auto cert = req.peer_cert();
  8829. ASSERT_TRUE(static_cast<bool>(cert));
  8830. std::string common_name = cert.subject_cn();
  8831. EXPECT_EQ("Common Name", common_name);
  8832. });
  8833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. t.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8841. client_encrypted_private_key_pass);
  8842. cli.enable_server_certificate_verification(false);
  8843. cli.set_connection_timeout(30);
  8844. auto res = cli.Get("/test");
  8845. ASSERT_TRUE(res);
  8846. ASSERT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST(SSLClientServerTest, ClientCertPresent) {
  8849. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8850. }
  8851. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8852. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8853. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8854. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8855. }
  8856. // PEM memory-based constructor tests (works with all TLS backends)
  8857. void PemMemoryClientCertPresent(
  8858. const std::string &client_cert_file,
  8859. const std::string &client_private_key_file,
  8860. const std::string &client_encrypted_private_key_pass = std::string()) {
  8861. // Read PEM files into memory
  8862. std::string server_cert_pem, server_key_pem;
  8863. std::string client_ca_pem;
  8864. std::string client_cert_pem, client_key_pem;
  8865. read_file(SERVER_CERT_FILE, server_cert_pem);
  8866. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8867. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8868. read_file(client_cert_file, client_cert_pem);
  8869. read_file(client_private_key_file, client_key_pem);
  8870. // Create server with PEM memory
  8871. SSLServer::PemMemory server_pem = {
  8872. server_cert_pem.c_str(),
  8873. server_cert_pem.size(),
  8874. server_key_pem.c_str(),
  8875. server_key_pem.size(),
  8876. client_ca_pem.c_str(),
  8877. client_ca_pem.size(),
  8878. nullptr // no password for server key
  8879. };
  8880. SSLServer svr(server_pem);
  8881. ASSERT_TRUE(svr.is_valid());
  8882. svr.Get("/test", [&](const Request &, Response &res) {
  8883. res.set_content("test", "text/plain");
  8884. });
  8885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. // Create client with PEM memory
  8893. const char *password = client_encrypted_private_key_pass.empty()
  8894. ? nullptr
  8895. : client_encrypted_private_key_pass.c_str();
  8896. SSLClient::PemMemory client_pem = {
  8897. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8898. client_key_pem.size(), password};
  8899. SSLClient cli(HOST, PORT, client_pem);
  8900. cli.enable_server_certificate_verification(false);
  8901. cli.set_connection_timeout(30);
  8902. auto res = cli.Get("/test");
  8903. ASSERT_TRUE(res);
  8904. ASSERT_EQ(StatusCode::OK_200, res->status);
  8905. }
  8906. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8907. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8908. }
  8909. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8910. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8911. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8912. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8913. }
  8914. TEST(SSLClientServerTest, ClientCertMissing) {
  8915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8916. CLIENT_CA_CERT_DIR);
  8917. ASSERT_TRUE(svr.is_valid());
  8918. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. t.join();
  8923. ASSERT_FALSE(svr.is_running());
  8924. });
  8925. svr.wait_until_ready();
  8926. SSLClient cli(HOST, PORT);
  8927. cli.set_connection_timeout(30);
  8928. auto res = cli.Get("/test");
  8929. ASSERT_TRUE(!res);
  8930. // When client cert is missing and server requires it, connection fails
  8931. // Error type depends on backend implementation
  8932. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8933. res.error() == Error::SSLConnection);
  8934. // Verify backend error is captured
  8935. // Note: This test may have different error codes depending on the exact
  8936. // verification failure
  8937. EXPECT_NE(0UL, res.ssl_backend_error());
  8938. }
  8939. TEST(SSLClientServerTest, TrustDirOptional) {
  8940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8941. ASSERT_TRUE(svr.is_valid());
  8942. svr.Get("/test", [&](const Request &, Response &res) {
  8943. res.set_content("test", "text/plain");
  8944. });
  8945. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8946. auto se = detail::scope_exit([&] {
  8947. svr.stop();
  8948. t.join();
  8949. ASSERT_FALSE(svr.is_running());
  8950. });
  8951. svr.wait_until_ready();
  8952. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8953. cli.enable_server_certificate_verification(false);
  8954. cli.set_connection_timeout(30);
  8955. auto res = cli.Get("/test");
  8956. ASSERT_TRUE(res);
  8957. ASSERT_EQ(StatusCode::OK_200, res->status);
  8958. }
  8959. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8960. class NoListenSSLServer : public SSLServer {
  8961. public:
  8962. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8963. const char *client_ca_cert_file_path,
  8964. const char *client_ca_cert_dir_path = nullptr)
  8965. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8966. client_ca_cert_dir_path),
  8967. stop_(false) {}
  8968. std::atomic_bool stop_;
  8969. private:
  8970. bool process_and_close_socket(socket_t /*sock*/) override {
  8971. // Don't create SSL context
  8972. while (!stop_.load()) {
  8973. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8974. }
  8975. return true;
  8976. }
  8977. };
  8978. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8979. CLIENT_CA_CERT_FILE);
  8980. ASSERT_TRUE(svr.is_valid());
  8981. svr.Get("/test", [&](const Request &, Response &res) {
  8982. res.set_content("test", "text/plain");
  8983. });
  8984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8985. auto se = detail::scope_exit([&] {
  8986. svr.stop_ = true;
  8987. svr.stop();
  8988. t.join();
  8989. ASSERT_FALSE(svr.is_running());
  8990. });
  8991. svr.wait_until_ready();
  8992. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8993. cli.enable_server_certificate_verification(false);
  8994. cli.set_connection_timeout(1);
  8995. auto res = cli.Get("/test");
  8996. ASSERT_TRUE(!res);
  8997. EXPECT_EQ(Error::SSLConnection, res.error());
  8998. // Timeout results in WantRead error code (maps to backend-specific value)
  8999. EXPECT_NE(0, res.ssl_error());
  9000. }
  9001. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9002. // Test SSLServer with client certificate verification using the standard
  9003. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9005. CLIENT_CA_CERT_DIR);
  9006. ASSERT_TRUE(svr.is_valid());
  9007. svr.Get("/test", [&](const Request &req, Response &res) {
  9008. res.set_content("test", "text/plain");
  9009. auto cert = req.peer_cert();
  9010. ASSERT_TRUE(static_cast<bool>(cert));
  9011. auto common_name = cert.subject_cn();
  9012. EXPECT_EQ("Common Name", common_name);
  9013. });
  9014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9015. auto se = detail::scope_exit([&] {
  9016. svr.stop();
  9017. t.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. svr.wait_until_ready();
  9021. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9022. cli.enable_server_certificate_verification(false);
  9023. cli.set_connection_timeout(30);
  9024. auto res = cli.Get("/test");
  9025. ASSERT_TRUE(res);
  9026. ASSERT_EQ(StatusCode::OK_200, res->status);
  9027. }
  9028. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9029. // Verifies that wildcard matching and exact matching work consistently
  9030. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9031. using namespace httplib::tls;
  9032. // We need a running server to test against
  9033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9034. ASSERT_TRUE(svr.is_valid());
  9035. svr.Get("/test", [](const Request &, Response &res) {
  9036. res.set_content("ok", "text/plain");
  9037. });
  9038. thread t([&]() { svr.listen(HOST, PORT); });
  9039. auto se = detail::scope_exit([&] {
  9040. svr.stop();
  9041. t.join();
  9042. });
  9043. svr.wait_until_ready();
  9044. bool verify_callback_called = false;
  9045. bool verify_result_wrong = false;
  9046. SSLClient cli(HOST, PORT);
  9047. cli.enable_server_certificate_verification(true);
  9048. cli.set_ca_cert_path(CA_CERT_FILE);
  9049. cli.set_connection_timeout(5);
  9050. // Note: Test certificate has CN="Common Name", not "localhost"
  9051. bool verify_result_cn = false;
  9052. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9053. verify_callback_called = true;
  9054. if (!ctx.cert) return false;
  9055. // Test 1: "Common Name" should match (our test server cert CN)
  9056. verify_result_cn = ctx.check_hostname("Common Name");
  9057. // Test 2: wrong hostname should not match
  9058. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9059. return true; // Accept for the purpose of this test
  9060. });
  9061. auto res = cli.Get("/test");
  9062. // The request may succeed or fail depending on cert configuration
  9063. // but the callback should have been called
  9064. ASSERT_TRUE(verify_callback_called)
  9065. << "Verify callback should have been called";
  9066. // CN="Common Name" should match our test certificate
  9067. //
  9068. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9069. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9070. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9071. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9072. // <openssl/base.h>, which is included transitively when
  9073. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9074. #if defined(OPENSSL_IS_BORINGSSL)
  9075. EXPECT_FALSE(verify_result_cn)
  9076. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9077. #else
  9078. EXPECT_TRUE(verify_result_cn)
  9079. << "verify_hostname should match 'Common Name' (certificate CN)";
  9080. #endif
  9081. // Wrong hostname should not match
  9082. EXPECT_FALSE(verify_result_wrong)
  9083. << "verify_hostname should not match 'wronghost.example.com'";
  9084. }
  9085. #endif
  9086. // mbedTLS-specific callback constructor test
  9087. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9088. #ifdef CPPHTTPLIB_SSL_ENABLED
  9089. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9090. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9091. ASSERT_TRUE(svr.is_valid());
  9092. // Set up a handler to verify client certificate is present
  9093. bool client_cert_verified = false;
  9094. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9095. // Verify that client certificate was provided
  9096. client_cert_verified = true;
  9097. res.set_content("success", "text/plain");
  9098. });
  9099. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9100. auto se = detail::scope_exit([&] {
  9101. svr.stop();
  9102. t.join();
  9103. ASSERT_FALSE(svr.is_running());
  9104. });
  9105. svr.wait_until_ready();
  9106. // Client with certificate
  9107. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9108. cli.enable_server_certificate_verification(false);
  9109. cli.set_connection_timeout(30);
  9110. auto res = cli.Get("/test");
  9111. ASSERT_TRUE(res);
  9112. ASSERT_EQ(StatusCode::OK_200, res->status);
  9113. ASSERT_TRUE(client_cert_verified);
  9114. EXPECT_EQ("success", res->body);
  9115. }
  9116. #endif
  9117. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9118. // backends
  9119. #ifdef CPPHTTPLIB_SSL_ENABLED
  9120. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9121. using namespace httplib::tls;
  9122. // Test that when client CA cert file is provided,
  9123. // the server properly requests and validates client certificates
  9124. // Create a server with client authentication
  9125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9126. ASSERT_TRUE(svr.is_valid());
  9127. bool handler_called = false;
  9128. svr.Get("/test", [&](const Request &req, Response &res) {
  9129. handler_called = true;
  9130. // Verify that a client certificate was provided
  9131. auto cert = req.peer_cert();
  9132. ASSERT_TRUE(static_cast<bool>(cert));
  9133. // Get the issuer name
  9134. std::string issuer_str = cert.issuer_name();
  9135. ASSERT_FALSE(issuer_str.empty());
  9136. // The client certificate should be issued by our test CA
  9137. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9138. res.set_content("authenticated", "text/plain");
  9139. });
  9140. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9141. auto se = detail::scope_exit([&] {
  9142. svr.stop();
  9143. t.join();
  9144. ASSERT_FALSE(svr.is_running());
  9145. });
  9146. svr.wait_until_ready();
  9147. // Connect with a client certificate issued by the CA
  9148. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9149. cli.enable_server_certificate_verification(false);
  9150. cli.set_connection_timeout(30);
  9151. auto res = cli.Get("/test");
  9152. ASSERT_TRUE(res);
  9153. ASSERT_EQ(StatusCode::OK_200, res->status);
  9154. ASSERT_TRUE(handler_called);
  9155. EXPECT_EQ("authenticated", res->body);
  9156. }
  9157. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9158. using namespace httplib::tls;
  9159. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9160. ASSERT_TRUE(svr.is_valid());
  9161. svr.Get("/test", [](const Request &, Response &res) {
  9162. res.set_content("ok", "text/plain");
  9163. });
  9164. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9165. auto se = detail::scope_exit([&] {
  9166. svr.stop();
  9167. t.join();
  9168. });
  9169. svr.wait_until_ready();
  9170. SSLClient cli(HOST, PORT);
  9171. cli.enable_server_certificate_verification(false);
  9172. cli.set_connection_timeout(30);
  9173. bool cert_checked = false;
  9174. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9175. if (ctx.cert) {
  9176. auto sans = ctx.sans();
  9177. // Test certificate may or may not have SANs - just verify the API
  9178. // works If SANs exist, verify the types are valid
  9179. for (const auto &san : sans) {
  9180. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9181. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9182. san.type == SanType::OTHER);
  9183. EXPECT_FALSE(san.value.empty());
  9184. }
  9185. cert_checked = true;
  9186. }
  9187. return true;
  9188. });
  9189. auto res = cli.Get("/test");
  9190. ASSERT_TRUE(res);
  9191. EXPECT_TRUE(cert_checked);
  9192. }
  9193. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9194. using namespace httplib::tls;
  9195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9196. ASSERT_TRUE(svr.is_valid());
  9197. svr.Get("/test", [](const Request &, Response &res) {
  9198. res.set_content("ok", "text/plain");
  9199. });
  9200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9201. auto se = detail::scope_exit([&] {
  9202. svr.stop();
  9203. t.join();
  9204. });
  9205. svr.wait_until_ready();
  9206. SSLClient cli(HOST, PORT);
  9207. cli.enable_server_certificate_verification(false);
  9208. cli.set_connection_timeout(30);
  9209. bool validity_checked = false;
  9210. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9211. if (ctx.cert) {
  9212. time_t not_before = 0, not_after = 0;
  9213. bool result = ctx.validity(not_before, not_after);
  9214. EXPECT_TRUE(result);
  9215. // Verify that not_before < now < not_after for a valid cert
  9216. time_t now = time(nullptr);
  9217. EXPECT_LT(not_before, now);
  9218. EXPECT_GT(not_after, now);
  9219. validity_checked = true;
  9220. }
  9221. return true;
  9222. });
  9223. auto res = cli.Get("/test");
  9224. ASSERT_TRUE(res);
  9225. EXPECT_TRUE(validity_checked);
  9226. }
  9227. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9228. using namespace httplib::tls;
  9229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9230. ASSERT_TRUE(svr.is_valid());
  9231. svr.Get("/test", [](const Request &, Response &res) {
  9232. res.set_content("ok", "text/plain");
  9233. });
  9234. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9235. auto se = detail::scope_exit([&] {
  9236. svr.stop();
  9237. t.join();
  9238. });
  9239. svr.wait_until_ready();
  9240. SSLClient cli(HOST, PORT);
  9241. cli.enable_server_certificate_verification(false);
  9242. cli.set_connection_timeout(30);
  9243. bool serial_checked = false;
  9244. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9245. if (ctx.cert) {
  9246. std::string serial = ctx.serial();
  9247. EXPECT_FALSE(serial.empty());
  9248. // Serial should be a hex string
  9249. for (char c : serial) {
  9250. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9251. (c >= 'a' && c <= 'f'));
  9252. }
  9253. serial_checked = true;
  9254. }
  9255. return true;
  9256. });
  9257. auto res = cli.Get("/test");
  9258. ASSERT_TRUE(res);
  9259. EXPECT_TRUE(serial_checked);
  9260. }
  9261. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9262. // Test 1: Valid CA file - no error should be recorded
  9263. {
  9264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9265. CLIENT_CA_CERT_FILE);
  9266. ASSERT_TRUE(svr.is_valid());
  9267. // With valid setup, last_ssl_error should be 0
  9268. EXPECT_EQ(0, svr.ssl_last_error());
  9269. }
  9270. // Test 2: Invalid CA file content
  9271. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9272. {
  9273. // Create a temporary file with completely invalid content
  9274. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9275. {
  9276. std::ofstream ofs(temp_invalid_ca);
  9277. ofs << "This is not a certificate file at all\n";
  9278. ofs << "Just plain text content\n";
  9279. }
  9280. // Create server with invalid CA file
  9281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9282. // Clean up temporary file
  9283. std::remove(temp_invalid_ca);
  9284. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9285. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9286. // Note: SSL_CTX_load_verify_locations typically fails first,
  9287. // but our error handling code path is still exercised
  9288. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9289. }
  9290. }
  9291. TEST(VerifyCallbackTest, VerifyContextFields) {
  9292. using namespace httplib::tls;
  9293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9294. ASSERT_TRUE(svr.is_valid());
  9295. svr.Get("/test", [](const Request &, Response &res) {
  9296. res.set_content("ok", "text/plain");
  9297. });
  9298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. });
  9303. svr.wait_until_ready();
  9304. SSLClient cli(HOST, PORT);
  9305. cli.enable_server_certificate_verification(false);
  9306. cli.set_connection_timeout(30);
  9307. int callback_count = 0;
  9308. bool saw_leaf_cert = false;
  9309. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9310. if (ctx.cert) {
  9311. callback_count++;
  9312. // We should see at least one certificate (the leaf)
  9313. std::string cn = ctx.subject_cn();
  9314. if (!cn.empty()) { saw_leaf_cert = true; }
  9315. // Verify context fields are populated
  9316. EXPECT_NE(ctx.session, nullptr);
  9317. EXPECT_GE(ctx.depth, 0);
  9318. }
  9319. return true;
  9320. });
  9321. auto res = cli.Get("/test");
  9322. ASSERT_TRUE(res);
  9323. EXPECT_GT(callback_count, 0);
  9324. EXPECT_TRUE(saw_leaf_cert);
  9325. }
  9326. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9327. using httplib::tls::TlsError;
  9328. // Test that verify_error_to_string returns empty for success
  9329. std::string success_str = TlsError::verify_error_to_string(0);
  9330. EXPECT_TRUE(success_str.empty());
  9331. // Test that verify_error_to_string returns non-empty for error codes
  9332. // Using a common error code (certificate expired)
  9333. std::string error_str =
  9334. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9335. EXPECT_FALSE(error_str.empty());
  9336. }
  9337. TEST(SessionVerifierTest, CertificateAccepted) {
  9338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9339. ASSERT_TRUE(svr.is_valid());
  9340. svr.Get("/test", [](const Request &, Response &res) {
  9341. res.set_content("ok", "text/plain");
  9342. });
  9343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. });
  9348. svr.wait_until_ready();
  9349. SSLClient cli(HOST, PORT);
  9350. cli.enable_server_certificate_verification(false);
  9351. cli.set_connection_timeout(30);
  9352. bool callback_called = false;
  9353. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9354. EXPECT_NE(session, nullptr);
  9355. callback_called = true;
  9356. return SSLVerifierResponse::CertificateAccepted;
  9357. });
  9358. auto res = cli.Get("/test");
  9359. ASSERT_TRUE(res);
  9360. EXPECT_EQ(200, res->status);
  9361. EXPECT_TRUE(callback_called);
  9362. }
  9363. TEST(SessionVerifierTest, CertificateRejected) {
  9364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9365. ASSERT_TRUE(svr.is_valid());
  9366. svr.Get("/test", [](const Request &, Response &res) {
  9367. res.set_content("ok", "text/plain");
  9368. });
  9369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9370. auto se = detail::scope_exit([&] {
  9371. svr.stop();
  9372. t.join();
  9373. });
  9374. svr.wait_until_ready();
  9375. SSLClient cli(HOST, PORT);
  9376. cli.enable_server_certificate_verification(false);
  9377. cli.set_connection_timeout(30);
  9378. bool callback_called = false;
  9379. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9380. EXPECT_NE(session, nullptr);
  9381. callback_called = true;
  9382. return SSLVerifierResponse::CertificateRejected;
  9383. });
  9384. auto res = cli.Get("/test");
  9385. EXPECT_FALSE(res);
  9386. EXPECT_TRUE(callback_called);
  9387. }
  9388. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9390. ASSERT_TRUE(svr.is_valid());
  9391. svr.Get("/test", [](const Request &, Response &res) {
  9392. res.set_content("ok", "text/plain");
  9393. });
  9394. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9395. auto se = detail::scope_exit([&] {
  9396. svr.stop();
  9397. t.join();
  9398. });
  9399. svr.wait_until_ready();
  9400. // NoDecisionMade with verification disabled should succeed (no default check)
  9401. SSLClient cli(HOST, PORT);
  9402. cli.enable_server_certificate_verification(false);
  9403. cli.set_connection_timeout(30);
  9404. bool callback_called = false;
  9405. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9406. EXPECT_NE(session, nullptr);
  9407. callback_called = true;
  9408. return SSLVerifierResponse::NoDecisionMade;
  9409. });
  9410. auto res = cli.Get("/test");
  9411. ASSERT_TRUE(res);
  9412. EXPECT_EQ(200, res->status);
  9413. EXPECT_TRUE(callback_called);
  9414. }
  9415. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9417. ASSERT_TRUE(svr.is_valid());
  9418. svr.Get("/test", [](const Request &, Response &res) {
  9419. res.set_content("ok", "text/plain");
  9420. });
  9421. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. });
  9426. svr.wait_until_ready();
  9427. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9428. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9429. // so we only check that the request fails, not whether the callback was
  9430. // called.
  9431. SSLClient cli(HOST, PORT);
  9432. cli.enable_server_certificate_verification(true);
  9433. cli.set_connection_timeout(30);
  9434. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9435. EXPECT_NE(session, nullptr);
  9436. return SSLVerifierResponse::NoDecisionMade;
  9437. });
  9438. auto res = cli.Get("/test");
  9439. EXPECT_FALSE(res);
  9440. }
  9441. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9442. // Test SSL server using PemMemory constructor with client CA certificates
  9443. // Read PEM files
  9444. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9445. read_file(SERVER_CERT_FILE, server_cert_pem);
  9446. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9447. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9448. // Create SSLServer with PemMemory constructor including client CA
  9449. SSLServer::PemMemory server_pem = {
  9450. server_cert_pem.c_str(),
  9451. server_cert_pem.size(),
  9452. server_key_pem.c_str(),
  9453. server_key_pem.size(),
  9454. client_ca_pem.c_str(),
  9455. client_ca_pem.size(),
  9456. nullptr // no password for server key
  9457. };
  9458. SSLServer svr(server_pem);
  9459. ASSERT_TRUE(svr.is_valid());
  9460. // No SSL error should be recorded for valid setup
  9461. EXPECT_EQ(0, svr.ssl_last_error());
  9462. // Set up server endpoints
  9463. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9464. res.set_content("ok", "text/plain");
  9465. });
  9466. // Start server in a thread
  9467. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9468. svr.wait_until_ready();
  9469. // Connect with client certificate (using constructor with paths)
  9470. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9471. cli.enable_server_certificate_verification(false);
  9472. auto res = cli.Get("/test-pem-ca");
  9473. ASSERT_TRUE(res);
  9474. EXPECT_EQ(200, res->status);
  9475. EXPECT_EQ("ok", res->body);
  9476. svr.stop();
  9477. server_thread.join();
  9478. }
  9479. #endif
  9480. #ifdef _WIN32
  9481. TEST(CleanupTest, WSACleanup) {
  9482. int ret = WSACleanup();
  9483. ASSERT_EQ(0, ret);
  9484. }
  9485. #endif
  9486. #ifndef CPPHTTPLIB_SSL_ENABLED
  9487. TEST(NoSSLSupport, SimpleInterface) {
  9488. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9489. }
  9490. #endif
  9491. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9492. TEST(InvalidScheme, SimpleInterface) {
  9493. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9494. }
  9495. #endif
  9496. TEST(NoScheme, SimpleInterface) {
  9497. Client cli("yahoo.com:80");
  9498. ASSERT_TRUE(cli.is_valid());
  9499. }
  9500. TEST(SendAPI, SimpleInterface_Online) {
  9501. Client cli("http://yahoo.com");
  9502. Request req;
  9503. req.method = "GET";
  9504. req.path = "/";
  9505. auto res = cli.send(req);
  9506. ASSERT_TRUE(res);
  9507. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9508. }
  9509. TEST(SendAPI, WithParamsInRequest) {
  9510. Server svr;
  9511. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9512. EXPECT_TRUE(req.has_param("test"));
  9513. EXPECT_EQ("test_value", req.get_param_value("test"));
  9514. });
  9515. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. t.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. });
  9521. svr.wait_until_ready();
  9522. Client cli(HOST, PORT);
  9523. {
  9524. Request req;
  9525. req.method = "GET";
  9526. req.path = "/";
  9527. req.params.emplace("test", "test_value");
  9528. auto res = cli.send(req);
  9529. ASSERT_TRUE(res);
  9530. }
  9531. {
  9532. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9533. ASSERT_TRUE(res);
  9534. }
  9535. }
  9536. TEST(ClientImplMethods, GetSocketTest) {
  9537. httplib::Server svr;
  9538. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9539. res.status = StatusCode::OK_200;
  9540. });
  9541. auto port = svr.bind_to_any_port("127.0.0.1");
  9542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9543. auto se = detail::scope_exit([&] {
  9544. svr.stop();
  9545. thread.join();
  9546. ASSERT_FALSE(svr.is_running());
  9547. });
  9548. svr.wait_until_ready();
  9549. {
  9550. httplib::Client cli("127.0.0.1", port);
  9551. cli.set_keep_alive(true);
  9552. // Use the behavior of cpp-httplib of opening the connection
  9553. // only when the first request happens. If that changes,
  9554. // this test would be obsolete.
  9555. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9556. // This also implicitly tests the server. But other tests would fail much
  9557. // earlier than this one to be considered.
  9558. auto res = cli.Get("/");
  9559. ASSERT_TRUE(res);
  9560. EXPECT_EQ(StatusCode::OK_200, res->status);
  9561. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9562. }
  9563. }
  9564. #ifdef CPPHTTPLIB_SSL_ENABLED
  9565. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9566. Client cli("http://yahoo.com");
  9567. auto res = cli.Get("/");
  9568. ASSERT_TRUE(res);
  9569. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9570. cli.set_follow_location(true);
  9571. res = cli.Get("/");
  9572. ASSERT_TRUE(res);
  9573. EXPECT_EQ(StatusCode::OK_200, res->status);
  9574. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9575. }
  9576. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9577. Client cli("https://yahoo.com");
  9578. auto res = cli.Get("/");
  9579. ASSERT_TRUE(res);
  9580. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9581. cli.set_follow_location(true);
  9582. res = cli.Get("/");
  9583. ASSERT_TRUE(res);
  9584. EXPECT_EQ(StatusCode::OK_200, res->status);
  9585. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9586. }
  9587. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9588. Client cli("https://yahoo.com");
  9589. auto res = cli.Get("/");
  9590. ASSERT_TRUE(res);
  9591. ASSERT_FALSE(!res);
  9592. ASSERT_TRUE(res);
  9593. ASSERT_FALSE(res == nullptr);
  9594. ASSERT_TRUE(res != nullptr);
  9595. EXPECT_EQ(Error::Success, res.error());
  9596. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9597. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9598. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9599. cli.set_follow_location(true);
  9600. res = cli.Get("/");
  9601. ASSERT_TRUE(res);
  9602. EXPECT_EQ(Error::Success, res.error());
  9603. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9604. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9605. EXPECT_EQ(StatusCode::OK_200, res->status);
  9606. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9607. }
  9608. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9609. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9610. Client cli("https://cdnjs.cloudflare.com");
  9611. auto res =
  9612. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9613. ASSERT_TRUE(res);
  9614. EXPECT_EQ(StatusCode::OK_200, res->status);
  9615. EXPECT_EQ(287630U, res->body.size());
  9616. EXPECT_EQ("application/javascript; charset=utf-8",
  9617. res->get_header_value("Content-Type"));
  9618. }
  9619. #endif
  9620. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9621. #undef REDIR_HOST // Silence compiler warning
  9622. #define REDIR_HOST "https://httpbingo.org"
  9623. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9624. Client cli(REDIR_HOST);
  9625. cli.set_follow_location(true);
  9626. auto res =
  9627. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9628. ASSERT_TRUE(res);
  9629. EXPECT_EQ(StatusCode::OK_200, res->status);
  9630. }
  9631. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9632. Client cli(REDIR_HOST);
  9633. cli.set_follow_location(true);
  9634. Params params;
  9635. params.emplace("url", "http://example.com");
  9636. params.emplace("status_code", "302");
  9637. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9638. ASSERT_TRUE(res);
  9639. EXPECT_EQ(StatusCode::OK_200, res->status);
  9640. }
  9641. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9642. Client cli(REDIR_HOST);
  9643. cli.set_follow_location(true);
  9644. Params params;
  9645. params.emplace("url", "http://example.com");
  9646. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9647. ASSERT_TRUE(res);
  9648. EXPECT_EQ(StatusCode::OK_200, res->status);
  9649. }
  9650. TEST(HttpToHttpsRedirectTest, CertFile) {
  9651. auto ssl_port = PORT + 1;
  9652. Server svr;
  9653. ASSERT_TRUE(svr.is_valid());
  9654. svr.Get("/index", [&](const Request &, Response &res) {
  9655. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9656. "/index");
  9657. svr.stop();
  9658. });
  9659. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9660. ASSERT_TRUE(ssl_svr.is_valid());
  9661. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9662. res.set_content("test", "text/plain");
  9663. ssl_svr.stop();
  9664. });
  9665. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9666. thread t2 =
  9667. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9668. auto se = detail::scope_exit([&] {
  9669. t2.join();
  9670. t.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. ssl_svr.wait_until_ready();
  9675. Client cli("127.0.0.1", PORT);
  9676. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9677. cli.enable_server_certificate_verification(true);
  9678. cli.set_follow_location(true);
  9679. cli.set_connection_timeout(30);
  9680. auto res = cli.Get("/index");
  9681. ASSERT_TRUE(res);
  9682. ASSERT_EQ(StatusCode::OK_200, res->status);
  9683. }
  9684. TEST(SSLClientRedirectTest, CertFile) {
  9685. auto ssl_port = PORT + 1;
  9686. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9687. ASSERT_TRUE(ssl_svr1.is_valid());
  9688. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9689. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9690. "/index");
  9691. ssl_svr1.stop();
  9692. });
  9693. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9694. ASSERT_TRUE(ssl_svr2.is_valid());
  9695. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9696. res.set_content("test", "text/plain");
  9697. ssl_svr2.stop();
  9698. });
  9699. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9700. thread t2 =
  9701. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9702. auto se = detail::scope_exit([&] {
  9703. t2.join();
  9704. t.join();
  9705. ASSERT_FALSE(ssl_svr1.is_running());
  9706. });
  9707. ssl_svr1.wait_until_ready();
  9708. ssl_svr2.wait_until_ready();
  9709. SSLClient cli("127.0.0.1", PORT);
  9710. std::string cert;
  9711. read_file(SERVER_CERT2_FILE, cert);
  9712. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9713. cli.enable_server_certificate_verification(true);
  9714. cli.set_follow_location(true);
  9715. cli.set_connection_timeout(30);
  9716. auto res = cli.Get("/index");
  9717. ASSERT_TRUE(res);
  9718. ASSERT_EQ(StatusCode::OK_200, res->status);
  9719. }
  9720. #endif
  9721. #ifdef CPPHTTPLIB_SSL_ENABLED
  9722. // Test that set_ca_cert_store() skips system certs (consistent with
  9723. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9724. // should be trusted - system certs should NOT be loaded.
  9725. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9726. // Load a specific cert that is NOT a system CA cert
  9727. std::string cert;
  9728. read_file(SERVER_CERT2_FILE, cert);
  9729. SSLClient cli("google.com");
  9730. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9731. cli.enable_server_certificate_verification(true);
  9732. // This should FAIL because:
  9733. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9734. // 2. System certs should NOT be loaded when custom store is set
  9735. // If system certs WERE loaded, this would succeed
  9736. auto res = cli.Get("/");
  9737. ASSERT_FALSE(res);
  9738. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9739. }
  9740. // Same as above, but through the native store handle path. Regression test:
  9741. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  9742. // merged system certs into the user-provided store.
  9743. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  9744. std::string cert;
  9745. read_file(SERVER_CERT2_FILE, cert);
  9746. SSLClient cli("google.com");
  9747. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9748. cli.enable_server_certificate_verification(true);
  9749. auto res = cli.Get("/");
  9750. ASSERT_FALSE(res);
  9751. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9752. }
  9753. // A custom store set via the native handle must still verify a server whose
  9754. // cert it does contain.
  9755. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  9756. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9757. ASSERT_TRUE(svr.is_valid());
  9758. svr.Get("/test", [&](const Request &, Response &res) {
  9759. res.set_content("test", "text/plain");
  9760. });
  9761. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. t.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. });
  9767. svr.wait_until_ready();
  9768. SSLClient cli("127.0.0.1", PORT);
  9769. std::string cert;
  9770. read_file(SERVER_CERT2_FILE, cert);
  9771. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9772. cli.enable_server_certificate_verification(true);
  9773. cli.set_connection_timeout(30);
  9774. auto res = cli.Get("/test");
  9775. ASSERT_TRUE(res);
  9776. ASSERT_EQ(StatusCode::OK_200, res->status);
  9777. }
  9778. // CA certs loaded through the universal Client must be transferred to the
  9779. // client created internally for following an HTTPS redirect. Regression test:
  9780. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  9781. // the CA data for redirect transfer.
  9782. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  9783. auto ssl_port = PORT + 1;
  9784. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9785. ASSERT_TRUE(ssl_svr1.is_valid());
  9786. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9787. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9788. "/index");
  9789. });
  9790. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9791. ASSERT_TRUE(ssl_svr2.is_valid());
  9792. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9793. res.set_content("test", "text/plain");
  9794. });
  9795. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9796. thread t2 =
  9797. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9798. auto se = detail::scope_exit([&] {
  9799. ssl_svr2.stop();
  9800. ssl_svr1.stop();
  9801. t2.join();
  9802. t.join();
  9803. ASSERT_FALSE(ssl_svr1.is_running());
  9804. });
  9805. ssl_svr1.wait_until_ready();
  9806. ssl_svr2.wait_until_ready();
  9807. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9808. std::string cert;
  9809. read_file(SERVER_CERT2_FILE, cert);
  9810. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9811. cli.enable_server_certificate_verification(true);
  9812. cli.set_follow_location(true);
  9813. cli.set_connection_timeout(30);
  9814. auto res = cli.Get("/index");
  9815. ASSERT_TRUE(res);
  9816. ASSERT_EQ(StatusCode::OK_200, res->status);
  9817. }
  9818. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  9819. // so a host signed by a system CA verifies even though a custom CA is set
  9820. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  9821. std::string cert;
  9822. read_file(SERVER_CERT2_FILE, cert);
  9823. SSLClient cli("google.com");
  9824. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9825. cli.enable_system_ca(true);
  9826. cli.enable_server_certificate_verification(true);
  9827. auto res = cli.Get("/");
  9828. ASSERT_TRUE(res);
  9829. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9830. }
  9831. // The custom CA remains effective when combined with the system CA
  9832. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  9833. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9834. ASSERT_TRUE(svr.is_valid());
  9835. svr.Get("/test", [&](const Request &, Response &res) {
  9836. res.set_content("test", "text/plain");
  9837. });
  9838. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9839. auto se = detail::scope_exit([&] {
  9840. svr.stop();
  9841. t.join();
  9842. ASSERT_FALSE(svr.is_running());
  9843. });
  9844. svr.wait_until_ready();
  9845. SSLClient cli("127.0.0.1", PORT);
  9846. std::string cert;
  9847. read_file(SERVER_CERT2_FILE, cert);
  9848. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9849. cli.enable_system_ca(true);
  9850. cli.enable_server_certificate_verification(true);
  9851. cli.set_connection_timeout(30);
  9852. auto res = cli.Get("/test");
  9853. ASSERT_TRUE(res);
  9854. ASSERT_EQ(StatusCode::OK_200, res->status);
  9855. }
  9856. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  9857. // skip chain verification entirely (only the certificate identity was
  9858. // checked), so a server presenting an untrusted certificate with a matching
  9859. // IP SAN was accepted. The chain must be validated for IP hosts too.
  9860. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  9861. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9862. ASSERT_TRUE(svr.is_valid());
  9863. svr.Get("/test", [&](const Request &, Response &res) {
  9864. res.set_content("test", "text/plain");
  9865. });
  9866. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9867. auto se = detail::scope_exit([&] {
  9868. svr.stop();
  9869. t.join();
  9870. ASSERT_FALSE(svr.is_running());
  9871. });
  9872. svr.wait_until_ready();
  9873. SSLClient cli("127.0.0.1", PORT);
  9874. std::string cert;
  9875. // A trusted CA that did not sign the server certificate. The server cert
  9876. // (cert2) carries the matching IP SAN, so only chain validation can reject
  9877. // this connection.
  9878. read_file(CLIENT_CA_CERT_FILE, cert);
  9879. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9880. cli.enable_server_certificate_verification(true);
  9881. cli.set_connection_timeout(30);
  9882. auto res = cli.Get("/test");
  9883. ASSERT_FALSE(res);
  9884. }
  9885. // enable_system_ca(false) prevents system CA loading entirely
  9886. TEST(SSLClientTest, DisableSystemCa_Online) {
  9887. SSLClient cli("google.com");
  9888. cli.enable_system_ca(false);
  9889. cli.enable_server_certificate_verification(true);
  9890. auto res = cli.Get("/");
  9891. ASSERT_FALSE(res);
  9892. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  9893. // itself when the CA chain is empty
  9894. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9895. res.error() == Error::SSLConnection);
  9896. }
  9897. // The universal Client forwards enable_system_ca()
  9898. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  9899. std::string cert;
  9900. read_file(SERVER_CERT2_FILE, cert);
  9901. Client cli("https://google.com");
  9902. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9903. cli.enable_system_ca(true);
  9904. cli.enable_server_certificate_verification(true);
  9905. auto res = cli.Get("/");
  9906. ASSERT_TRUE(res);
  9907. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9908. }
  9909. // The system CA policy must carry over to the client created internally for
  9910. // following a cross-host HTTPS redirect
  9911. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  9912. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9913. ASSERT_TRUE(svr.is_valid());
  9914. svr.Get("/index", [&](const Request &, Response &res) {
  9915. res.set_redirect("https://www.google.com/");
  9916. });
  9917. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9918. auto se = detail::scope_exit([&] {
  9919. svr.stop();
  9920. t.join();
  9921. ASSERT_FALSE(svr.is_running());
  9922. });
  9923. svr.wait_until_ready();
  9924. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9925. std::string cert;
  9926. read_file(SERVER_CERT2_FILE, cert);
  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. cli.set_follow_location(true);
  9931. cli.set_connection_timeout(30);
  9932. // Receiving any response proves the redirect client completed the TLS
  9933. // handshake with a system-CA-signed host
  9934. auto res = cli.Get("/index");
  9935. ASSERT_TRUE(res);
  9936. }
  9937. TEST(MultipartFormDataTest, LargeData) {
  9938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9939. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9940. const ContentReader &content_reader) {
  9941. if (req.is_multipart_form_data()) {
  9942. std::vector<FormData> items;
  9943. content_reader(
  9944. [&](const FormData &file) {
  9945. items.push_back(file);
  9946. return true;
  9947. },
  9948. [&](const char *data, size_t data_length) {
  9949. items.back().content.append(data, data_length);
  9950. return true;
  9951. });
  9952. EXPECT_TRUE(std::string(items[0].name) == "document");
  9953. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9954. EXPECT_TRUE(items[0].filename == "2MB_data");
  9955. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9956. EXPECT_TRUE(items[1].name == "hello");
  9957. EXPECT_TRUE(items[1].content == "world");
  9958. EXPECT_TRUE(items[1].filename == "");
  9959. EXPECT_TRUE(items[1].content_type == "");
  9960. } else {
  9961. std::string body;
  9962. content_reader([&](const char *data, size_t data_length) {
  9963. body.append(data, data_length);
  9964. return true;
  9965. });
  9966. }
  9967. });
  9968. auto port = svr.bind_to_any_port(HOST);
  9969. auto t = std::thread([&]() { svr.listen_after_bind(); });
  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. {
  9977. std::string data(1024 * 1024 * 2, '.');
  9978. std::stringstream buffer;
  9979. buffer << data;
  9980. SSLClient cli(HOST, port);
  9981. cli.enable_server_certificate_verification(false);
  9982. UploadFormDataItems items{
  9983. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9984. {"hello", "world", "", ""},
  9985. };
  9986. auto res = cli.Post("/post", items);
  9987. ASSERT_TRUE(res);
  9988. ASSERT_EQ(StatusCode::OK_200, res->status);
  9989. }
  9990. }
  9991. TEST(MultipartFormDataTest, DataProviderItems) {
  9992. std::random_device seed_gen;
  9993. std::mt19937 random(seed_gen());
  9994. std::string rand1;
  9995. rand1.resize(1000);
  9996. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9997. std::string rand2;
  9998. rand2.resize(3000);
  9999. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10000. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10001. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10002. const ContentReader &content_reader) {
  10003. ASSERT_FALSE(req.is_multipart_form_data());
  10004. std::string body;
  10005. content_reader([&](const char *data, size_t data_length) {
  10006. body.append(data, data_length);
  10007. return true;
  10008. });
  10009. EXPECT_EQ(body, "");
  10010. });
  10011. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10012. const ContentReader &content_reader) {
  10013. ASSERT_TRUE(req.is_multipart_form_data());
  10014. std::vector<FormData> items;
  10015. content_reader(
  10016. [&](const FormData &file) {
  10017. items.push_back(file);
  10018. return true;
  10019. },
  10020. [&](const char *data, size_t data_length) {
  10021. items.back().content.append(data, data_length);
  10022. return true;
  10023. });
  10024. ASSERT_TRUE(items.size() == 2);
  10025. EXPECT_EQ(std::string(items[0].name), "name1");
  10026. EXPECT_EQ(items[0].content, "Testing123");
  10027. EXPECT_EQ(items[0].filename, "filename1");
  10028. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10029. EXPECT_EQ(items[1].name, "name2");
  10030. EXPECT_EQ(items[1].content, "Testing456");
  10031. EXPECT_EQ(items[1].filename, "");
  10032. EXPECT_EQ(items[1].content_type, "");
  10033. });
  10034. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10035. const ContentReader &content_reader) {
  10036. ASSERT_TRUE(req.is_multipart_form_data());
  10037. std::vector<FormData> items;
  10038. content_reader(
  10039. [&](const FormData &file) {
  10040. items.push_back(file);
  10041. return true;
  10042. },
  10043. [&](const char *data, size_t data_length) {
  10044. items.back().content.append(data, data_length);
  10045. return true;
  10046. });
  10047. ASSERT_TRUE(items.size() == 2);
  10048. EXPECT_EQ(items[0].name, "name3");
  10049. EXPECT_EQ(items[0].content, rand1);
  10050. EXPECT_EQ(items[0].filename, "filename3");
  10051. EXPECT_EQ(items[0].content_type, "");
  10052. EXPECT_EQ(items[1].name, "name4");
  10053. EXPECT_EQ(items[1].content, rand2);
  10054. EXPECT_EQ(items[1].filename, "filename4");
  10055. EXPECT_EQ(items[1].content_type, "");
  10056. });
  10057. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10058. const ContentReader &content_reader) {
  10059. ASSERT_TRUE(req.is_multipart_form_data());
  10060. std::vector<FormData> items;
  10061. content_reader(
  10062. [&](const FormData &file) {
  10063. items.push_back(file);
  10064. return true;
  10065. },
  10066. [&](const char *data, size_t data_length) {
  10067. items.back().content.append(data, data_length);
  10068. return true;
  10069. });
  10070. ASSERT_TRUE(items.size() == 4);
  10071. EXPECT_EQ(std::string(items[0].name), "name1");
  10072. EXPECT_EQ(items[0].content, "Testing123");
  10073. EXPECT_EQ(items[0].filename, "filename1");
  10074. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10075. EXPECT_EQ(items[1].name, "name2");
  10076. EXPECT_EQ(items[1].content, "Testing456");
  10077. EXPECT_EQ(items[1].filename, "");
  10078. EXPECT_EQ(items[1].content_type, "");
  10079. EXPECT_EQ(items[2].name, "name3");
  10080. EXPECT_EQ(items[2].content, rand1);
  10081. EXPECT_EQ(items[2].filename, "filename3");
  10082. EXPECT_EQ(items[2].content_type, "");
  10083. EXPECT_EQ(items[3].name, "name4");
  10084. EXPECT_EQ(items[3].content, rand2);
  10085. EXPECT_EQ(items[3].filename, "filename4");
  10086. EXPECT_EQ(items[3].content_type, "");
  10087. });
  10088. auto port = svr.bind_to_any_port("localhost");
  10089. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10090. auto se = detail::scope_exit([&] {
  10091. svr.stop();
  10092. t.join();
  10093. ASSERT_FALSE(svr.is_running());
  10094. });
  10095. svr.wait_until_ready();
  10096. {
  10097. SSLClient cli("localhost", port);
  10098. cli.enable_server_certificate_verification(false);
  10099. UploadFormDataItems items{
  10100. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10101. {"name2", "Testing456", "", ""}, // not a file
  10102. };
  10103. {
  10104. auto res = cli.Post("/post-none", {}, {}, {});
  10105. ASSERT_TRUE(res);
  10106. ASSERT_EQ(StatusCode::OK_200, res->status);
  10107. }
  10108. FormDataProviderItems providers;
  10109. {
  10110. auto res =
  10111. cli.Post("/post-items", {}, items, providers); // empty providers
  10112. ASSERT_TRUE(res);
  10113. ASSERT_EQ(StatusCode::OK_200, res->status);
  10114. }
  10115. providers.push_back({"name3",
  10116. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10117. // test the offset is given correctly at each step
  10118. if (!offset)
  10119. sink.os.write(rand1.data(), 30);
  10120. else if (offset == 30)
  10121. sink.os.write(rand1.data() + 30, 300);
  10122. else if (offset == 330)
  10123. sink.os.write(rand1.data() + 330, 670);
  10124. else if (offset == rand1.size())
  10125. sink.done();
  10126. return true;
  10127. },
  10128. "filename3",
  10129. {}});
  10130. providers.push_back({"name4",
  10131. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10132. // test the offset is given correctly at each step
  10133. if (!offset)
  10134. sink.os.write(rand2.data(), 2000);
  10135. else if (offset == 2000)
  10136. sink.os.write(rand2.data() + 2000, 1);
  10137. else if (offset == 2001)
  10138. sink.os.write(rand2.data() + 2001, 999);
  10139. else if (offset == rand2.size())
  10140. sink.done();
  10141. return true;
  10142. },
  10143. "filename4",
  10144. {}});
  10145. {
  10146. auto res = cli.Post("/post-providers", {}, {}, providers);
  10147. ASSERT_TRUE(res);
  10148. ASSERT_EQ(StatusCode::OK_200, res->status);
  10149. }
  10150. {
  10151. auto res = cli.Post("/post-both", {}, items, providers);
  10152. ASSERT_TRUE(res);
  10153. ASSERT_EQ(StatusCode::OK_200, res->status);
  10154. }
  10155. }
  10156. }
  10157. TEST(MultipartFormDataTest, BadHeader) {
  10158. Server svr;
  10159. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10160. res.set_content("ok", "text/plain");
  10161. });
  10162. thread t = thread([&] { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. ASSERT_FALSE(svr.is_running());
  10167. });
  10168. svr.wait_until_ready();
  10169. const std::string body =
  10170. "This is the preamble. It is to be ignored, though it\r\n"
  10171. "is a handy place for composition agents to include an\r\n"
  10172. "explanatory note to non-MIME conformant readers.\r\n"
  10173. "\r\n"
  10174. "\r\n"
  10175. "--simple boundary\r\n"
  10176. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10177. ": BAD...\r\n"
  10178. "\r\n"
  10179. "value1\r\n"
  10180. "--simple boundary\r\n"
  10181. "Content-Disposition: form-data; name=\"field2\"; "
  10182. "filename=\"example.txt\"\r\n"
  10183. "\r\n"
  10184. "value2\r\n"
  10185. "--simple boundary--\r\n"
  10186. "This is the epilogue. It is also to be ignored.\r\n";
  10187. std::string content_type =
  10188. R"(multipart/form-data; boundary="simple boundary")";
  10189. Client cli(HOST, PORT);
  10190. auto res = cli.Post("/post", body, content_type.c_str());
  10191. ASSERT_TRUE(res);
  10192. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10193. }
  10194. TEST(MultipartFormDataTest, WithPreamble) {
  10195. Server svr;
  10196. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10197. res.set_content("ok", "text/plain");
  10198. });
  10199. thread t = thread([&] { svr.listen(HOST, PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. t.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.wait_until_ready();
  10206. const std::string body =
  10207. "This is the preamble. It is to be ignored, though it\r\n"
  10208. "is a handy place for composition agents to include an\r\n"
  10209. "explanatory note to non-MIME conformant readers.\r\n"
  10210. "\r\n"
  10211. "\r\n"
  10212. "--simple boundary\r\n"
  10213. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10214. "\r\n"
  10215. "value1\r\n"
  10216. "--simple boundary\r\n"
  10217. "Content-Disposition: form-data; name=\"field2\"; "
  10218. "filename=\"example.txt\"\r\n"
  10219. "\r\n"
  10220. "value2\r\n"
  10221. "--simple boundary--\r\n"
  10222. "This is the epilogue. It is also to be ignored.\r\n";
  10223. std::string content_type =
  10224. R"(multipart/form-data; boundary="simple boundary")";
  10225. Client cli(HOST, PORT);
  10226. auto res = cli.Post("/post", body, content_type.c_str());
  10227. ASSERT_TRUE(res);
  10228. EXPECT_EQ(StatusCode::OK_200, res->status);
  10229. }
  10230. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10232. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10233. const ContentReader &content_reader) {
  10234. if (req.is_multipart_form_data()) {
  10235. std::vector<FormData> items;
  10236. content_reader(
  10237. [&](const FormData &file) {
  10238. items.push_back(file);
  10239. return true;
  10240. },
  10241. [&](const char *data, size_t data_length) {
  10242. items.back().content.append(data, data_length);
  10243. return true;
  10244. });
  10245. EXPECT_TRUE(std::string(items[0].name) == "document");
  10246. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10247. EXPECT_TRUE(items[0].filename == "2MB_data");
  10248. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10249. EXPECT_TRUE(items[1].name == "hello");
  10250. EXPECT_TRUE(items[1].content == "world");
  10251. EXPECT_TRUE(items[1].filename == "");
  10252. EXPECT_TRUE(items[1].content_type == "");
  10253. } else {
  10254. std::string body;
  10255. content_reader([&](const char *data, size_t data_length) {
  10256. body.append(data, data_length);
  10257. return true;
  10258. });
  10259. }
  10260. });
  10261. auto port = svr.bind_to_any_port("localhost");
  10262. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10263. auto se = detail::scope_exit([&] {
  10264. svr.stop();
  10265. t.join();
  10266. ASSERT_FALSE(svr.is_running());
  10267. });
  10268. svr.wait_until_ready();
  10269. {
  10270. std::string data(1024 * 1024 * 2, '.');
  10271. std::stringstream buffer;
  10272. buffer << data;
  10273. SSLClient cli("localhost", port);
  10274. cli.enable_server_certificate_verification(false);
  10275. UploadFormDataItems items{
  10276. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10277. {"hello", "world", "", ""},
  10278. };
  10279. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10280. ASSERT_TRUE(res);
  10281. ASSERT_EQ(StatusCode::OK_200, res->status);
  10282. }
  10283. }
  10284. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10285. std::string data(1024 * 1024 * 2, '&');
  10286. std::stringstream buffer;
  10287. buffer << data;
  10288. Client cli("https://localhost:8080");
  10289. UploadFormDataItems items{
  10290. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10291. {"hello", "world", "", ""},
  10292. };
  10293. for (const char &c : " \t\r\n") {
  10294. auto res =
  10295. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10296. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10297. ASSERT_FALSE(res);
  10298. }
  10299. }
  10300. TEST(MultipartFormDataTest, PutFormData) {
  10301. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10302. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10303. const ContentReader &content_reader) {
  10304. if (req.is_multipart_form_data()) {
  10305. std::vector<FormData> items;
  10306. content_reader(
  10307. [&](const FormData &file) {
  10308. items.push_back(file);
  10309. return true;
  10310. },
  10311. [&](const char *data, size_t data_length) {
  10312. items.back().content.append(data, data_length);
  10313. return true;
  10314. });
  10315. EXPECT_TRUE(std::string(items[0].name) == "document");
  10316. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10317. EXPECT_TRUE(items[0].filename == "2MB_data");
  10318. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10319. EXPECT_TRUE(items[1].name == "hello");
  10320. EXPECT_TRUE(items[1].content == "world");
  10321. EXPECT_TRUE(items[1].filename == "");
  10322. EXPECT_TRUE(items[1].content_type == "");
  10323. } else {
  10324. std::string body;
  10325. content_reader([&](const char *data, size_t data_length) {
  10326. body.append(data, data_length);
  10327. return true;
  10328. });
  10329. }
  10330. });
  10331. auto port = svr.bind_to_any_port("localhost");
  10332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. t.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. });
  10338. svr.wait_until_ready();
  10339. {
  10340. std::string data(1024 * 1024 * 2, '&');
  10341. std::stringstream buffer;
  10342. buffer << data;
  10343. SSLClient cli("localhost", port);
  10344. cli.enable_server_certificate_verification(false);
  10345. UploadFormDataItems items{
  10346. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10347. {"hello", "world", "", ""},
  10348. };
  10349. auto res = cli.Put("/put", items);
  10350. ASSERT_TRUE(res);
  10351. ASSERT_EQ(StatusCode::OK_200, res->status);
  10352. }
  10353. }
  10354. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10355. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10356. svr.Put("/put_customboundary",
  10357. [&](const Request &req, const Response & /*res*/,
  10358. const ContentReader &content_reader) {
  10359. if (req.is_multipart_form_data()) {
  10360. std::vector<FormData> items;
  10361. content_reader(
  10362. [&](const FormData &file) {
  10363. items.push_back(file);
  10364. return true;
  10365. },
  10366. [&](const char *data, size_t data_length) {
  10367. items.back().content.append(data, data_length);
  10368. return true;
  10369. });
  10370. EXPECT_TRUE(std::string(items[0].name) == "document");
  10371. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10372. EXPECT_TRUE(items[0].filename == "2MB_data");
  10373. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10374. EXPECT_TRUE(items[1].name == "hello");
  10375. EXPECT_TRUE(items[1].content == "world");
  10376. EXPECT_TRUE(items[1].filename == "");
  10377. EXPECT_TRUE(items[1].content_type == "");
  10378. } else {
  10379. std::string body;
  10380. content_reader([&](const char *data, size_t data_length) {
  10381. body.append(data, data_length);
  10382. return true;
  10383. });
  10384. }
  10385. });
  10386. auto port = svr.bind_to_any_port("localhost");
  10387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. t.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. {
  10395. std::string data(1024 * 1024 * 2, '&');
  10396. std::stringstream buffer;
  10397. buffer << data;
  10398. SSLClient cli("localhost", port);
  10399. cli.enable_server_certificate_verification(false);
  10400. UploadFormDataItems items{
  10401. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10402. {"hello", "world", "", ""},
  10403. };
  10404. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10405. ASSERT_TRUE(res);
  10406. ASSERT_EQ(StatusCode::OK_200, res->status);
  10407. }
  10408. }
  10409. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10410. std::string data(1024 * 1024 * 2, '&');
  10411. std::stringstream buffer;
  10412. buffer << data;
  10413. Client cli("https://localhost:8080");
  10414. cli.enable_server_certificate_verification(false);
  10415. UploadFormDataItems items{
  10416. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10417. {"hello", "world", "", ""},
  10418. };
  10419. for (const char &c : " \t\r\n") {
  10420. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10421. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10422. ASSERT_FALSE(res);
  10423. }
  10424. }
  10425. TEST(MultipartFormDataTest, AlternateFilename) {
  10426. auto handled = false;
  10427. Server svr;
  10428. svr.Post("/test", [&](const Request &req, Response &res) {
  10429. ASSERT_EQ(2u, req.form.files.size());
  10430. ASSERT_EQ(1u, req.form.fields.size());
  10431. // Test files
  10432. const auto &file1 = req.form.get_file("file1");
  10433. ASSERT_EQ("file1", file1.name);
  10434. ASSERT_EQ("A.txt", file1.filename);
  10435. ASSERT_EQ("text/plain", file1.content_type);
  10436. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10437. const auto &file2 = req.form.get_file("file2");
  10438. ASSERT_EQ("file2", file2.name);
  10439. ASSERT_EQ("a.html", file2.filename);
  10440. ASSERT_EQ("text/html", file2.content_type);
  10441. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10442. file2.content);
  10443. // Test text field
  10444. const auto &text = req.form.get_field("text");
  10445. ASSERT_EQ("text default", text);
  10446. res.set_content("ok", "text/plain");
  10447. handled = true;
  10448. });
  10449. thread t = thread([&] { svr.listen(HOST, PORT); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. ASSERT_FALSE(svr.is_running());
  10454. ASSERT_TRUE(handled);
  10455. });
  10456. svr.wait_until_ready();
  10457. auto req = "POST /test HTTP/1.1\r\n"
  10458. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10459. "Content-Length: 399\r\n"
  10460. "\r\n"
  10461. "----------\r\n"
  10462. "Content-Disposition: form-data; name=\"text\"\r\n"
  10463. "\r\n"
  10464. "text default\r\n"
  10465. "----------\r\n"
  10466. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10467. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10468. "Content-Type: text/plain\r\n"
  10469. "\r\n"
  10470. "Content of a.txt.\r\n"
  10471. "\r\n"
  10472. "----------\r\n"
  10473. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10474. "\"a.html\"\r\n"
  10475. "Content-Type: text/html\r\n"
  10476. "\r\n"
  10477. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10478. "\r\n"
  10479. "------------\r\n";
  10480. ASSERT_TRUE(send_request(1, req));
  10481. }
  10482. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10483. auto handled = false;
  10484. Server svr;
  10485. svr.Post("/test", [&](const Request &req, Response &res) {
  10486. // Case-insensitive "utf-8''" prefix with a long value
  10487. const auto &file = req.form.get_file("file1");
  10488. ASSERT_EQ("file1", file.name);
  10489. // 8000 chars exercises both the Content-Disposition parser and the
  10490. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10491. // Prior to the fix, std::regex_match on this header would cause O(N)
  10492. // stack recursion in libstdc++, leading to SIGSEGV.
  10493. std::string expected_filename(8000, 'A');
  10494. ASSERT_EQ(expected_filename, file.filename);
  10495. res.set_content("ok", "text/plain");
  10496. handled = true;
  10497. });
  10498. thread t = thread([&] { svr.listen(HOST, PORT); });
  10499. auto se = detail::scope_exit([&] {
  10500. svr.stop();
  10501. t.join();
  10502. ASSERT_FALSE(svr.is_running());
  10503. ASSERT_TRUE(handled);
  10504. });
  10505. svr.wait_until_ready();
  10506. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10507. // Regression test for GHSA-qq6v-r583-3h69
  10508. std::string long_filename(8000, 'A');
  10509. std::string body = "----------\r\n"
  10510. "Content-Disposition: form-data; name=\"file1\"; "
  10511. "filename*=\"Utf-8''" +
  10512. long_filename +
  10513. "\"\r\n"
  10514. "\r\n"
  10515. "hello\r\n"
  10516. "------------\r\n";
  10517. auto req = "POST /test HTTP/1.1\r\n"
  10518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10519. "Content-Length: " +
  10520. std::to_string(body.size()) + "\r\n\r\n" + body;
  10521. ASSERT_TRUE(send_request(1, req));
  10522. }
  10523. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10524. auto handled = false;
  10525. Server svr;
  10526. svr.Post("/test", [&](const Request &req, Response &) {
  10527. ASSERT_EQ(2u, req.form.fields.size());
  10528. const auto &text1 = req.form.get_field("text1");
  10529. ASSERT_EQ("text1", text1);
  10530. const auto &text2 = req.form.get_field("text2");
  10531. ASSERT_EQ("text2", text2);
  10532. handled = true;
  10533. });
  10534. thread t = thread([&] { svr.listen(HOST, PORT); });
  10535. auto se = detail::scope_exit([&] {
  10536. svr.stop();
  10537. t.join();
  10538. ASSERT_FALSE(svr.is_running());
  10539. ASSERT_TRUE(handled);
  10540. });
  10541. svr.wait_until_ready();
  10542. auto req = "POST /test HTTP/1.1\r\n"
  10543. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10544. "Content-Length: 146\r\n"
  10545. "\r\n----------\r\n"
  10546. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10547. "\r\n"
  10548. "text1"
  10549. "\r\n----------\r\n"
  10550. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10551. "\r\n"
  10552. "text2"
  10553. "\r\n------------";
  10554. std::string response;
  10555. ASSERT_TRUE(send_request(1, req, &response));
  10556. ASSERT_EQ("200", response.substr(9, 3));
  10557. }
  10558. TEST(MultipartFormDataTest, ContentLength) {
  10559. auto handled = false;
  10560. Server svr;
  10561. svr.Post("/test", [&](const Request &req, Response &) {
  10562. ASSERT_EQ(2u, req.form.fields.size());
  10563. const auto &text1 = req.form.get_field("text1");
  10564. ASSERT_EQ("text1", text1);
  10565. const auto &text2 = req.form.get_field("text2");
  10566. ASSERT_EQ("text2", text2);
  10567. handled = true;
  10568. });
  10569. thread t = thread([&] { svr.listen(HOST, PORT); });
  10570. auto se = detail::scope_exit([&] {
  10571. svr.stop();
  10572. t.join();
  10573. ASSERT_FALSE(svr.is_running());
  10574. ASSERT_TRUE(handled);
  10575. });
  10576. svr.wait_until_ready();
  10577. auto req = "POST /test HTTP/1.1\r\n"
  10578. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10579. "Content-Length: 167\r\n"
  10580. "\r\n----------\r\n"
  10581. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10582. "Content-Length: 5\r\n"
  10583. "\r\n"
  10584. "text1"
  10585. "\r\n----------\r\n"
  10586. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10587. "\r\n"
  10588. "text2"
  10589. "\r\n------------\r\n";
  10590. std::string response;
  10591. ASSERT_TRUE(send_request(1, req, &response));
  10592. ASSERT_EQ("200", response.substr(9, 3));
  10593. }
  10594. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10595. auto handled = false;
  10596. Server svr;
  10597. svr.Post("/test", [&](const Request &req, Response &) {
  10598. ASSERT_EQ(2u, req.form.fields.size());
  10599. const auto &text1 = req.form.get_field("text1");
  10600. ASSERT_EQ("text1", text1);
  10601. // TODO: Add header access for text fields if needed
  10602. const auto &text2 = req.form.get_field("text2");
  10603. ASSERT_EQ("text2", text2);
  10604. // TODO: Header access for text fields needs to be implemented
  10605. // auto &headers = it->second.headers;
  10606. // ASSERT_EQ(3U, headers.size());
  10607. // auto custom_header = headers.find("x-whatever");
  10608. // ASSERT_TRUE(custom_header != headers.end());
  10609. // ASSERT_NE("customvalue", custom_header->second);
  10610. // ASSERT_EQ("CustomValue", custom_header->second);
  10611. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10612. handled = true;
  10613. });
  10614. thread t = thread([&] { svr.listen(HOST, PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. t.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. ASSERT_TRUE(handled);
  10620. });
  10621. svr.wait_until_ready();
  10622. auto req = "POST /test HTTP/1.1\r\n"
  10623. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10624. "Content-Length: 232\r\n"
  10625. "\r\n----------\r\n"
  10626. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10627. "Content-Length: 5\r\n"
  10628. "X-Test: 1\r\n"
  10629. "\r\n"
  10630. "text1"
  10631. "\r\n----------\r\n"
  10632. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10633. "Content-Type: text/plain\r\n"
  10634. "X-Whatever: CustomValue\r\n"
  10635. "\r\n"
  10636. "text2"
  10637. "\r\n------------\r\n"
  10638. "That should be disregarded. Not even read";
  10639. std::string response;
  10640. ASSERT_TRUE(send_request(1, req, &response));
  10641. ASSERT_EQ("200", response.substr(9, 3));
  10642. }
  10643. TEST(MultipartFormDataTest, LargeHeader) {
  10644. auto handled = false;
  10645. Server svr;
  10646. svr.Post("/test", [&](const Request &req, Response &) {
  10647. ASSERT_EQ(1u, req.form.fields.size());
  10648. const auto &text = req.form.get_field("name1");
  10649. ASSERT_EQ("text1", text);
  10650. handled = true;
  10651. });
  10652. thread t = thread([&] { svr.listen(HOST, PORT); });
  10653. auto se = detail::scope_exit([&] {
  10654. svr.stop();
  10655. t.join();
  10656. ASSERT_FALSE(svr.is_running());
  10657. ASSERT_TRUE(handled);
  10658. });
  10659. svr.wait_until_ready();
  10660. auto boundary = std::string("cpp-httplib-multipart-data");
  10661. std::string content = "--" + boundary +
  10662. "\r\n"
  10663. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10664. "\r\n"
  10665. "text1\r\n"
  10666. "--" +
  10667. boundary + "--\r\n";
  10668. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10669. "Content-Type: multipart/form-data;boundary=" +
  10670. boundary +
  10671. "\r\n"
  10672. "Content-Length: " +
  10673. std::to_string(content.size()) +
  10674. "\r\n"
  10675. "Dummy-Header: ";
  10676. std::string header_suffix = "\r\n"
  10677. "\r\n";
  10678. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10679. size_t header_dummy_size =
  10680. read_buff_size -
  10681. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10682. auto header_dummy = std::string(header_dummy_size, '@');
  10683. auto req = header_prefix + header_dummy + header_suffix + content;
  10684. std::string response;
  10685. ASSERT_TRUE(send_request(1, req, &response));
  10686. ASSERT_EQ("200", response.substr(9, 3));
  10687. }
  10688. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10689. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10690. // (not chunked Transfer-Encoding) after the streaming refactor.
  10691. auto handled = false;
  10692. Server svr;
  10693. svr.Post("/upload", [&](const Request &req, Response &res) {
  10694. auto cl_it = req.headers.find("Content-Length");
  10695. EXPECT_TRUE(cl_it != req.headers.end());
  10696. auto te_it = req.headers.find("Transfer-Encoding");
  10697. EXPECT_TRUE(te_it == req.headers.end());
  10698. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10699. res.set_content("ok", "text/plain");
  10700. handled = true;
  10701. });
  10702. auto port = svr.bind_to_any_port(HOST);
  10703. auto t = thread([&] { svr.listen_after_bind(); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. t.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. ASSERT_TRUE(handled);
  10709. });
  10710. svr.wait_until_ready();
  10711. UploadFormDataItems items = {
  10712. {"field1", "hello", "", "text/plain"},
  10713. {"file1", "world", "test.txt", "application/octet-stream"},
  10714. };
  10715. Client cli(HOST, port);
  10716. auto res = cli.Post("/upload", {}, items);
  10717. ASSERT_TRUE(res);
  10718. EXPECT_EQ(StatusCode::OK_200, res->status);
  10719. }
  10720. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10721. // Verify that make_multipart_content_provider coalesces many small segments
  10722. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10723. constexpr size_t kItemCount = 1000;
  10724. UploadFormDataItems items;
  10725. items.reserve(kItemCount);
  10726. for (size_t i = 0; i < kItemCount; i++) {
  10727. items.push_back(
  10728. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10729. }
  10730. const std::string boundary = "----test-boundary";
  10731. auto content_length = detail::get_multipart_content_length(items, boundary);
  10732. auto provider = detail::make_multipart_content_provider(items, boundary);
  10733. // Drive the provider the same way write_content_with_progress does
  10734. size_t write_count = 0;
  10735. size_t total_bytes = 0;
  10736. DataSink sink;
  10737. size_t offset = 0;
  10738. sink.write = [&](const char *d, size_t l) -> bool {
  10739. (void)d;
  10740. write_count++;
  10741. total_bytes += l;
  10742. offset += l;
  10743. return true;
  10744. };
  10745. sink.is_writable = []() -> bool { return true; };
  10746. while (offset < content_length) {
  10747. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10748. }
  10749. EXPECT_EQ(content_length, total_bytes);
  10750. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10751. // With buffering into 64KB blocks, write_count should be much smaller.
  10752. auto segment_count = 3 * kItemCount + 1;
  10753. EXPECT_LT(write_count, segment_count / 10);
  10754. }
  10755. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10756. // Integration test: send many UploadFormDataItems and verify the server
  10757. // receives all of them correctly (#2410).
  10758. constexpr size_t kItemCount = 500;
  10759. auto handled = false;
  10760. Server svr;
  10761. svr.Post("/upload", [&](const Request &req, Response &res) {
  10762. EXPECT_EQ(kItemCount, req.form.fields.size());
  10763. for (size_t i = 0; i < kItemCount; i++) {
  10764. auto key = "field" + std::to_string(i);
  10765. auto val = "value" + std::to_string(i);
  10766. auto it = req.form.fields.find(key);
  10767. if (it != req.form.fields.end()) {
  10768. EXPECT_EQ(val, it->second.content);
  10769. } else {
  10770. ADD_FAILURE() << "Missing field: " << key;
  10771. }
  10772. }
  10773. res.set_content("ok", "text/plain");
  10774. handled = true;
  10775. });
  10776. auto port = svr.bind_to_any_port(HOST);
  10777. auto t = thread([&] { svr.listen_after_bind(); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. t.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. ASSERT_TRUE(handled);
  10783. });
  10784. svr.wait_until_ready();
  10785. UploadFormDataItems items;
  10786. items.reserve(kItemCount);
  10787. for (size_t i = 0; i < kItemCount; i++) {
  10788. items.push_back(
  10789. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10790. }
  10791. Client cli(HOST, port);
  10792. auto res = cli.Post("/upload", items);
  10793. ASSERT_TRUE(res);
  10794. EXPECT_EQ(StatusCode::OK_200, res->status);
  10795. }
  10796. TEST(MultipartFormDataTest, MakeFileProvider) {
  10797. // Verify make_file_provider sends a file's contents correctly.
  10798. const std::string file_content(4096, 'Z');
  10799. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10800. {
  10801. std::ofstream ofs(tmp_path, std::ios::binary);
  10802. ofs.write(file_content.data(),
  10803. static_cast<std::streamsize>(file_content.size()));
  10804. }
  10805. auto handled = false;
  10806. Server svr;
  10807. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10808. const ContentReader &content_reader) {
  10809. ASSERT_TRUE(req.is_multipart_form_data());
  10810. std::vector<FormData> items;
  10811. content_reader(
  10812. [&](const FormData &file) {
  10813. items.push_back(file);
  10814. return true;
  10815. },
  10816. [&](const char *data, size_t data_length) {
  10817. items.back().content.append(data, data_length);
  10818. return true;
  10819. });
  10820. ASSERT_EQ(1u, items.size());
  10821. EXPECT_EQ("myfile", items[0].name);
  10822. EXPECT_EQ("data.bin", items[0].filename);
  10823. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10824. EXPECT_EQ(file_content, items[0].content);
  10825. handled = true;
  10826. });
  10827. auto port = svr.bind_to_any_port(HOST);
  10828. auto t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. ASSERT_TRUE(handled);
  10834. std::remove(tmp_path.c_str());
  10835. });
  10836. svr.wait_until_ready();
  10837. FormDataProviderItems providers;
  10838. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10839. "application/octet-stream"));
  10840. Client cli(HOST, port);
  10841. auto res = cli.Post("/upload", {}, {}, providers);
  10842. ASSERT_TRUE(res);
  10843. EXPECT_EQ(StatusCode::OK_200, res->status);
  10844. }
  10845. TEST(MakeFileBodyTest, Basic) {
  10846. const std::string file_content(4096, 'Z');
  10847. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10848. {
  10849. std::ofstream ofs(tmp_path, std::ios::binary);
  10850. ofs.write(file_content.data(),
  10851. static_cast<std::streamsize>(file_content.size()));
  10852. }
  10853. auto handled = false;
  10854. Server svr;
  10855. svr.Post("/upload", [&](const Request &req, Response &res) {
  10856. EXPECT_EQ(file_content, req.body);
  10857. handled = true;
  10858. res.status = StatusCode::OK_200;
  10859. });
  10860. auto port = svr.bind_to_any_port(HOST);
  10861. auto t = thread([&] { svr.listen_after_bind(); });
  10862. auto se = detail::scope_exit([&] {
  10863. svr.stop();
  10864. t.join();
  10865. ASSERT_FALSE(svr.is_running());
  10866. ASSERT_TRUE(handled);
  10867. std::remove(tmp_path.c_str());
  10868. });
  10869. svr.wait_until_ready();
  10870. auto fb = make_file_body(tmp_path);
  10871. ASSERT_GT(fb.first, 0u);
  10872. Client cli(HOST, port);
  10873. auto res =
  10874. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10875. ASSERT_TRUE(res);
  10876. EXPECT_EQ(StatusCode::OK_200, res->status);
  10877. }
  10878. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10879. static constexpr unsigned int number_of_tasks{1000000};
  10880. std::atomic_uint count{0};
  10881. std::unique_ptr<TaskQueue> task_queue{
  10882. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10883. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10884. auto queued = task_queue->enqueue(
  10885. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10886. EXPECT_TRUE(queued);
  10887. }
  10888. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10889. task_queue->shutdown();
  10890. #else
  10891. EXPECT_NO_THROW(task_queue->shutdown());
  10892. #endif
  10893. EXPECT_EQ(number_of_tasks, count.load());
  10894. }
  10895. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10896. static constexpr unsigned int number_of_tasks{1000000};
  10897. static constexpr unsigned int qlimit{2};
  10898. unsigned int queued_count{0};
  10899. std::atomic_uint count{0};
  10900. std::unique_ptr<TaskQueue> task_queue{
  10901. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10902. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10903. if (task_queue->enqueue(
  10904. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10905. queued_count++;
  10906. }
  10907. }
  10908. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10909. task_queue->shutdown();
  10910. #else
  10911. EXPECT_NO_THROW(task_queue->shutdown());
  10912. #endif
  10913. EXPECT_EQ(queued_count, count.load());
  10914. EXPECT_TRUE(queued_count <= number_of_tasks);
  10915. EXPECT_TRUE(queued_count >= qlimit);
  10916. }
  10917. TEST(TaskQueueTest, MaxQueuedRequests) {
  10918. static constexpr unsigned int qlimit{3};
  10919. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10920. std::condition_variable sem_cv;
  10921. std::mutex sem_mtx;
  10922. int credits = 0;
  10923. bool queued;
  10924. /* Fill up the queue with tasks that will block until we give them credits to
  10925. * complete. */
  10926. for (unsigned int n = 0; n <= qlimit;) {
  10927. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10928. std::unique_lock<std::mutex> lock(sem_mtx);
  10929. while (credits <= 0) {
  10930. sem_cv.wait(lock);
  10931. }
  10932. /* Consume the credit and signal the test code if they are all gone. */
  10933. if (--credits == 0) { sem_cv.notify_one(); }
  10934. });
  10935. if (n < qlimit) {
  10936. /* The first qlimit enqueues must succeed. */
  10937. EXPECT_TRUE(queued);
  10938. } else {
  10939. /* The last one will succeed only when the worker thread
  10940. * starts and dequeues the first blocking task. Although
  10941. * not necessary for the correctness of this test, we sleep for
  10942. * a short while to avoid busy waiting. */
  10943. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10944. }
  10945. if (queued) { n++; }
  10946. }
  10947. /* Further enqueues must fail since the queue is full. */
  10948. for (auto i = 0; i < 4; i++) {
  10949. queued = task_queue->enqueue([] {});
  10950. EXPECT_FALSE(queued);
  10951. }
  10952. /* Give the credits to allow the previous tasks to complete. */
  10953. {
  10954. std::unique_lock<std::mutex> lock(sem_mtx);
  10955. credits += qlimit + 1;
  10956. }
  10957. sem_cv.notify_all();
  10958. /* Wait for all the credits to be consumed. */
  10959. {
  10960. std::unique_lock<std::mutex> lock(sem_mtx);
  10961. while (credits > 0) {
  10962. sem_cv.wait(lock);
  10963. }
  10964. }
  10965. /* Check that we are able again to enqueue at least qlimit tasks. */
  10966. for (unsigned int i = 0; i < qlimit; i++) {
  10967. queued = task_queue->enqueue([] {});
  10968. EXPECT_TRUE(queued);
  10969. }
  10970. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10971. task_queue->shutdown();
  10972. #else
  10973. EXPECT_NO_THROW(task_queue->shutdown());
  10974. #endif
  10975. }
  10976. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10977. Server svr;
  10978. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10979. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10980. });
  10981. svr.Get("/hello", [](const Request &req, Response &res) {
  10982. res.set_content(req.get_param_value("key"), "text/plain");
  10983. });
  10984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10985. auto se = detail::scope_exit([&] {
  10986. svr.stop();
  10987. thread.join();
  10988. ASSERT_FALSE(svr.is_running());
  10989. });
  10990. svr.wait_until_ready();
  10991. {
  10992. Client cli(HOST, PORT);
  10993. cli.set_follow_location(true);
  10994. auto res = cli.Get("/");
  10995. ASSERT_TRUE(res);
  10996. EXPECT_EQ(StatusCode::OK_200, res->status);
  10997. EXPECT_EQ("val&key2=val2", res->body);
  10998. }
  10999. }
  11000. #endif
  11001. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11002. Server svr;
  11003. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11004. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11005. });
  11006. svr.Get("/hello", [](const Request &req, Response &res) {
  11007. res.set_content(req.get_param_value("key"), "text/plain");
  11008. });
  11009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. thread.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. {
  11017. Client cli(HOST, PORT);
  11018. cli.set_follow_location(true);
  11019. auto res = cli.Get("/");
  11020. ASSERT_TRUE(res);
  11021. EXPECT_EQ(StatusCode::OK_200, res->status);
  11022. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11023. }
  11024. }
  11025. TEST(RedirectTest, RedirectWithPlusInPath) {
  11026. Server svr;
  11027. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11028. res.set_redirect("/a+b");
  11029. });
  11030. // Route pattern uses regex; escape + as \\+
  11031. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11032. res.set_content(req.path, "text/plain");
  11033. });
  11034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11035. auto se = detail::scope_exit([&] {
  11036. svr.stop();
  11037. thread.join();
  11038. ASSERT_FALSE(svr.is_running());
  11039. });
  11040. svr.wait_until_ready();
  11041. {
  11042. Client cli(HOST, PORT);
  11043. cli.set_follow_location(true);
  11044. auto res = cli.Get("/");
  11045. ASSERT_TRUE(res);
  11046. EXPECT_EQ(StatusCode::OK_200, res->status);
  11047. EXPECT_EQ("/a+b", res->body);
  11048. }
  11049. }
  11050. #ifdef CPPHTTPLIB_SSL_ENABLED
  11051. TEST(RedirectTest, Issue2185_Online) {
  11052. SSLClient client("github.com");
  11053. client.set_follow_location(true);
  11054. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11055. "Coollab-Windows.zip");
  11056. ASSERT_TRUE(res);
  11057. EXPECT_EQ(StatusCode::OK_200, res->status);
  11058. EXPECT_EQ(9920427U, res->body.size());
  11059. }
  11060. #endif
  11061. TEST(VulnerabilityTest, CRLFInjection) {
  11062. Server svr;
  11063. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11064. res.set_content("Hello 1", "text/plain");
  11065. });
  11066. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11067. res.set_content("Hello 2", "text/plain");
  11068. });
  11069. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11070. res.set_content("Hello 3", "text/plain");
  11071. });
  11072. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11073. res.set_content("Hello 4", "text/plain");
  11074. });
  11075. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11076. for (const auto &x : req.headers) {
  11077. auto key = x.first;
  11078. EXPECT_STRNE("evil", key.c_str());
  11079. }
  11080. });
  11081. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11082. auto se = detail::scope_exit([&] {
  11083. svr.stop();
  11084. thread.join();
  11085. ASSERT_FALSE(svr.is_running());
  11086. });
  11087. svr.wait_until_ready();
  11088. {
  11089. Client cli(HOST, PORT);
  11090. cli.Post("/test1", "A=B",
  11091. "application/x-www-form-urlencoded\r\nevil: hello1");
  11092. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11093. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11094. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11095. }
  11096. }
  11097. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11098. auto server_thread = std::thread([] {
  11099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11100. default_socket_options(srv);
  11101. sockaddr_in addr{};
  11102. addr.sin_family = AF_INET;
  11103. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11104. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11105. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11106. ::listen(srv, 1);
  11107. sockaddr_in cli_addr{};
  11108. socklen_t cli_len = sizeof(cli_addr);
  11109. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11110. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11111. std::string buf_all;
  11112. char buf[2048];
  11113. ssize_t n;
  11114. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11115. buf_all.append(buf, static_cast<size_t>(n));
  11116. size_t pos;
  11117. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11118. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11119. auto e = request_block.find("\r\n");
  11120. if (e != std::string::npos) {
  11121. auto request_line = request_block.substr(0, e);
  11122. std::string msg =
  11123. "CRLF injection detected in request line: '" + request_line + "'";
  11124. EXPECT_FALSE(true) << msg;
  11125. }
  11126. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11127. ::send(cli,
  11128. #ifdef _WIN32
  11129. static_cast<const char *>(resp.c_str()),
  11130. static_cast<int>(resp.size()),
  11131. #else
  11132. resp.c_str(), resp.size(),
  11133. #endif
  11134. 0);
  11135. buf_all.erase(0, pos + 4);
  11136. }
  11137. }
  11138. detail::close_socket(cli);
  11139. detail::close_socket(srv);
  11140. });
  11141. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11142. auto cli = Client("127.0.0.1", PORT + 1);
  11143. auto headers = Headers{
  11144. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11145. {"Connection", "keep-alive"}};
  11146. auto res = cli.Get("/hi", headers);
  11147. EXPECT_FALSE(res);
  11148. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11149. server_thread.join();
  11150. }
  11151. TEST(PathParamsTest, StaticMatch) {
  11152. const auto pattern = "/users/all";
  11153. detail::PathParamsMatcher matcher(pattern);
  11154. Request request;
  11155. request.path = "/users/all";
  11156. ASSERT_TRUE(matcher.match(request));
  11157. std::unordered_map<std::string, std::string> expected_params = {};
  11158. EXPECT_EQ(request.path_params, expected_params);
  11159. }
  11160. TEST(PathParamsTest, StaticMismatch) {
  11161. const auto pattern = "/users/all";
  11162. detail::PathParamsMatcher matcher(pattern);
  11163. Request request;
  11164. request.path = "/users/1";
  11165. ASSERT_FALSE(matcher.match(request));
  11166. }
  11167. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11168. const auto pattern = "/users/:id/subscriptions";
  11169. detail::PathParamsMatcher matcher(pattern);
  11170. Request request;
  11171. request.path = "/users/42/subscriptions";
  11172. ASSERT_TRUE(matcher.match(request));
  11173. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11174. EXPECT_EQ(request.path_params, expected_params);
  11175. }
  11176. TEST(PathParamsTest, SingleParamInTheEnd) {
  11177. const auto pattern = "/users/:id";
  11178. detail::PathParamsMatcher matcher(pattern);
  11179. Request request;
  11180. request.path = "/users/24";
  11181. ASSERT_TRUE(matcher.match(request));
  11182. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11183. EXPECT_EQ(request.path_params, expected_params);
  11184. }
  11185. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11186. const auto pattern = "/users/:id/";
  11187. detail::PathParamsMatcher matcher(pattern);
  11188. Request request;
  11189. request.path = "/users/42/";
  11190. ASSERT_TRUE(matcher.match(request));
  11191. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11192. EXPECT_EQ(request.path_params, expected_params);
  11193. }
  11194. TEST(PathParamsTest, EmptyParam) {
  11195. const auto pattern = "/users/:id/";
  11196. detail::PathParamsMatcher matcher(pattern);
  11197. Request request;
  11198. request.path = "/users//";
  11199. ASSERT_TRUE(matcher.match(request));
  11200. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11201. EXPECT_EQ(request.path_params, expected_params);
  11202. }
  11203. TEST(PathParamsTest, FragmentMismatch) {
  11204. const auto pattern = "/users/:id/";
  11205. detail::PathParamsMatcher matcher(pattern);
  11206. Request request;
  11207. request.path = "/admins/24/";
  11208. ASSERT_FALSE(matcher.match(request));
  11209. }
  11210. TEST(PathParamsTest, ExtraFragments) {
  11211. const auto pattern = "/users/:id";
  11212. detail::PathParamsMatcher matcher(pattern);
  11213. Request request;
  11214. request.path = "/users/42/subscriptions";
  11215. ASSERT_FALSE(matcher.match(request));
  11216. }
  11217. TEST(PathParamsTest, MissingTrailingParam) {
  11218. const auto pattern = "/users/:id";
  11219. detail::PathParamsMatcher matcher(pattern);
  11220. Request request;
  11221. request.path = "/users";
  11222. ASSERT_FALSE(matcher.match(request));
  11223. }
  11224. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11225. const auto pattern = "/users/:id/subscriptions";
  11226. detail::PathParamsMatcher matcher(pattern);
  11227. Request request;
  11228. request.path = "/users/subscriptions";
  11229. ASSERT_FALSE(matcher.match(request));
  11230. }
  11231. TEST(PathParamsTest, MultipleParams) {
  11232. const auto pattern = "/users/:userid/subscriptions/:subid";
  11233. detail::PathParamsMatcher matcher(pattern);
  11234. Request request;
  11235. request.path = "/users/42/subscriptions/2";
  11236. ASSERT_TRUE(matcher.match(request));
  11237. std::unordered_map<std::string, std::string> expected_params = {
  11238. {"userid", "42"}, {"subid", "2"}};
  11239. EXPECT_EQ(request.path_params, expected_params);
  11240. }
  11241. TEST(PathParamsTest, SequenceOfParams) {
  11242. const auto pattern = "/values/:x/:y/:z";
  11243. detail::PathParamsMatcher matcher(pattern);
  11244. Request request;
  11245. request.path = "/values/1/2/3";
  11246. ASSERT_TRUE(matcher.match(request));
  11247. std::unordered_map<std::string, std::string> expected_params = {
  11248. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11249. EXPECT_EQ(request.path_params, expected_params);
  11250. }
  11251. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11252. const auto pattern = "/prefix:suffix";
  11253. detail::PathParamsMatcher matcher(pattern);
  11254. Request request;
  11255. request.path = "/prefix:suffix";
  11256. ASSERT_TRUE(matcher.match(request));
  11257. const std::unordered_map<std::string, std::string> expected_params = {};
  11258. EXPECT_EQ(request.path_params, expected_params);
  11259. }
  11260. TEST(ParseUrlTest, VariousPatterns) {
  11261. {
  11262. detail::UrlComponents uc;
  11263. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11264. EXPECT_EQ("http", uc.scheme);
  11265. EXPECT_EQ("example.com", uc.host);
  11266. EXPECT_EQ("8080", uc.port);
  11267. EXPECT_EQ("/path", uc.path);
  11268. EXPECT_EQ("?q=1", uc.query);
  11269. }
  11270. {
  11271. detail::UrlComponents uc;
  11272. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11273. EXPECT_EQ("https", uc.scheme);
  11274. EXPECT_EQ("example.com", uc.host);
  11275. EXPECT_TRUE(uc.port.empty());
  11276. EXPECT_EQ("/path", uc.path);
  11277. }
  11278. {
  11279. detail::UrlComponents uc;
  11280. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11281. EXPECT_EQ("::1", uc.host);
  11282. EXPECT_EQ("8080", uc.port);
  11283. EXPECT_EQ("/path", uc.path);
  11284. }
  11285. {
  11286. detail::UrlComponents uc;
  11287. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11288. }
  11289. {
  11290. detail::UrlComponents uc;
  11291. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11292. EXPECT_TRUE(uc.scheme.empty());
  11293. EXPECT_EQ("example.com", uc.host);
  11294. EXPECT_EQ("/path", uc.path);
  11295. EXPECT_EQ("?q=1", uc.query);
  11296. }
  11297. {
  11298. detail::UrlComponents uc;
  11299. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11300. EXPECT_TRUE(uc.host.empty());
  11301. EXPECT_EQ("/path", uc.path);
  11302. EXPECT_EQ("?q=1", uc.query);
  11303. }
  11304. {
  11305. detail::UrlComponents uc;
  11306. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11307. EXPECT_EQ("example.com", uc.host);
  11308. EXPECT_EQ("8080", uc.port);
  11309. }
  11310. {
  11311. // Unix socket path — must not be parsed as host
  11312. detail::UrlComponents uc;
  11313. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11314. EXPECT_TRUE(uc.host.empty());
  11315. }
  11316. {
  11317. detail::UrlComponents uc;
  11318. ASSERT_TRUE(detail::parse_url("", uc));
  11319. EXPECT_TRUE(uc.host.empty());
  11320. EXPECT_TRUE(uc.path.empty());
  11321. }
  11322. {
  11323. detail::UrlComponents uc;
  11324. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11325. }
  11326. {
  11327. detail::UrlComponents uc;
  11328. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11329. }
  11330. {
  11331. // Accepted by parse_url; callers restrict to http/https
  11332. detail::UrlComponents uc;
  11333. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11334. EXPECT_EQ("ftp", uc.scheme);
  11335. }
  11336. {
  11337. detail::UrlComponents uc;
  11338. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11339. }
  11340. {
  11341. detail::UrlComponents uc;
  11342. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11343. }
  11344. }
  11345. TEST(ParseUrlTest, FragmentHandling) {
  11346. {
  11347. detail::UrlComponents uc;
  11348. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11349. EXPECT_EQ("/path", uc.path);
  11350. EXPECT_TRUE(uc.query.empty());
  11351. }
  11352. {
  11353. detail::UrlComponents uc;
  11354. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11355. EXPECT_TRUE(uc.path.empty());
  11356. EXPECT_TRUE(uc.query.empty());
  11357. }
  11358. }
  11359. TEST(ParseUrlTest, UserinfoHandling) {
  11360. // Userinfo with @ but no colon — host includes @
  11361. detail::UrlComponents uc;
  11362. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11363. EXPECT_EQ("user@host.com", uc.host);
  11364. EXPECT_EQ("/path", uc.path);
  11365. }
  11366. TEST(ParseUrlTest, IPv6EdgeCases) {
  11367. {
  11368. detail::UrlComponents uc;
  11369. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11370. EXPECT_TRUE(uc.scheme.empty());
  11371. EXPECT_EQ("::1", uc.host);
  11372. EXPECT_EQ("8080", uc.port);
  11373. }
  11374. {
  11375. // Zone ID '%25' is not in [a-fA-F0-9:]
  11376. detail::UrlComponents uc;
  11377. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11378. }
  11379. }
  11380. TEST(ParseUrlTest, SchemeEdgeCases) {
  11381. {
  11382. detail::UrlComponents uc;
  11383. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11384. }
  11385. {
  11386. detail::UrlComponents uc;
  11387. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11388. }
  11389. {
  11390. detail::UrlComponents uc;
  11391. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11392. }
  11393. }
  11394. TEST(ParseUrlTest, PortEdgeCases) {
  11395. {
  11396. detail::UrlComponents uc;
  11397. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11398. EXPECT_TRUE(uc.port.empty());
  11399. EXPECT_EQ("/path", uc.path);
  11400. }
  11401. {
  11402. // parse_url accepts any port string; validation is done by parse_port
  11403. detail::UrlComponents uc;
  11404. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11405. EXPECT_EQ("abc", uc.port);
  11406. }
  11407. }
  11408. TEST(ParseUrlTest, WebSocketPatterns) {
  11409. {
  11410. detail::UrlComponents uc;
  11411. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11412. EXPECT_EQ("ws", uc.scheme);
  11413. EXPECT_EQ("echo.example.com", uc.host);
  11414. EXPECT_EQ("8080", uc.port);
  11415. EXPECT_EQ("/ws", uc.path);
  11416. }
  11417. {
  11418. detail::UrlComponents uc;
  11419. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11420. EXPECT_EQ("wss", uc.scheme);
  11421. EXPECT_EQ("echo.example.com", uc.host);
  11422. EXPECT_TRUE(uc.port.empty());
  11423. EXPECT_EQ("/ws", uc.path);
  11424. }
  11425. }
  11426. TEST(ParseUrlTest, QueryOnly) {
  11427. detail::UrlComponents uc;
  11428. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11429. EXPECT_TRUE(uc.host.empty());
  11430. EXPECT_TRUE(uc.path.empty());
  11431. EXPECT_EQ("?q=1&r=2", uc.query);
  11432. }
  11433. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11434. detail::UrlComponents uc;
  11435. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11436. EXPECT_TRUE(uc.scheme.empty());
  11437. EXPECT_EQ("example.com", uc.host);
  11438. EXPECT_EQ("443", uc.port);
  11439. EXPECT_EQ("/path", uc.path);
  11440. }
  11441. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11442. // If ipv6 regex working, regex match codepath is taken.
  11443. // else port will default to 80 in Client impl
  11444. int clientImplMagicPort = 80;
  11445. int port = 4321;
  11446. // above ports must be different to avoid false negative
  11447. EXPECT_NE(clientImplMagicPort, port);
  11448. std::string ipV6TestURL = "http://[ff06::c3]";
  11449. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11450. CLIENT_PRIVATE_KEY_FILE);
  11451. EXPECT_EQ(cli.port(), port);
  11452. }
  11453. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11454. auto file_path = "./www/dir/index.html";
  11455. auto dir_path = "./www/dir";
  11456. detail::FileStat stat_file(file_path);
  11457. EXPECT_TRUE(stat_file.is_file());
  11458. EXPECT_FALSE(stat_file.is_dir());
  11459. detail::FileStat stat_dir(dir_path);
  11460. EXPECT_FALSE(stat_dir.is_file());
  11461. EXPECT_TRUE(stat_dir.is_dir());
  11462. }
  11463. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11464. // IPv4 with default HTTP port (80)
  11465. EXPECT_EQ("example.com",
  11466. detail::make_host_and_port_string("example.com", 80, false));
  11467. // IPv4 with default HTTPS port (443)
  11468. EXPECT_EQ("example.com",
  11469. detail::make_host_and_port_string("example.com", 443, true));
  11470. // IPv4 with non-default HTTP port
  11471. EXPECT_EQ("example.com:8080",
  11472. detail::make_host_and_port_string("example.com", 8080, false));
  11473. // IPv4 with non-default HTTPS port
  11474. EXPECT_EQ("example.com:8443",
  11475. detail::make_host_and_port_string("example.com", 8443, true));
  11476. // IPv6 with default HTTP port (80)
  11477. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11478. // IPv6 with default HTTPS port (443)
  11479. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11480. // IPv6 with non-default HTTP port
  11481. EXPECT_EQ("[::1]:8080",
  11482. detail::make_host_and_port_string("::1", 8080, false));
  11483. // IPv6 with non-default HTTPS port
  11484. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11485. // IPv6 full address with default port
  11486. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11487. detail::make_host_and_port_string(
  11488. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11489. // IPv6 full address with non-default port
  11490. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11491. detail::make_host_and_port_string(
  11492. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11493. // IPv6 localhost with non-default port
  11494. EXPECT_EQ("[::1]:3000",
  11495. detail::make_host_and_port_string("::1", 3000, false));
  11496. // IPv6 with zone ID (link-local address) with default port
  11497. EXPECT_EQ("[fe80::1%eth0]",
  11498. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11499. // IPv6 with zone ID (link-local address) with non-default port
  11500. EXPECT_EQ("[fe80::1%eth0]:8080",
  11501. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11502. // Edge case: Port 443 with is_ssl=false (should add port)
  11503. EXPECT_EQ("example.com:443",
  11504. detail::make_host_and_port_string("example.com", 443, false));
  11505. // Edge case: Port 80 with is_ssl=true (should add port)
  11506. EXPECT_EQ("example.com:80",
  11507. detail::make_host_and_port_string("example.com", 80, true));
  11508. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11509. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11510. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11511. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11512. // Security fix: Already bracketed IPv6 should not get double brackets
  11513. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11514. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11515. EXPECT_EQ("[::1]:8080",
  11516. detail::make_host_and_port_string("[::1]", 8080, false));
  11517. EXPECT_EQ("[2001:db8::1]:8080",
  11518. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11519. EXPECT_EQ("[fe80::1%eth0]",
  11520. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11521. EXPECT_EQ("[fe80::1%eth0]:8080",
  11522. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11523. // Edge case: Empty host (should return as-is)
  11524. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11525. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11526. // This is a known limitation but shouldn't crash
  11527. EXPECT_EQ("[host:name]",
  11528. detail::make_host_and_port_string("host:name", 80, false));
  11529. // Port number edge cases (no validation, but should not crash)
  11530. EXPECT_EQ("example.com:0",
  11531. detail::make_host_and_port_string("example.com", 0, false));
  11532. EXPECT_EQ("example.com:-1",
  11533. detail::make_host_and_port_string("example.com", -1, false));
  11534. EXPECT_EQ("example.com:65535",
  11535. detail::make_host_and_port_string("example.com", 65535, false));
  11536. EXPECT_EQ("example.com:65536",
  11537. detail::make_host_and_port_string("example.com", 65536, false));
  11538. }
  11539. #ifdef CPPHTTPLIB_SSL_ENABLED
  11540. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11541. httplib::SSLClient cli("roblox.com", 443);
  11542. cli.set_follow_location(true);
  11543. auto res = cli.Get("/");
  11544. ASSERT_TRUE(res);
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. }
  11547. #endif
  11548. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11549. Server svr;
  11550. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11551. EXPECT_EQ(res.status, 400);
  11552. });
  11553. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11554. auto se = detail::scope_exit([&] {
  11555. svr.stop();
  11556. thread.join();
  11557. ASSERT_FALSE(svr.is_running());
  11558. });
  11559. svr.wait_until_ready();
  11560. Client cli(HOST, PORT);
  11561. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11562. }
  11563. TEST(InvalidHeaderCharsTest, is_field_name) {
  11564. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11565. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11566. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11567. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11568. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11569. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11570. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11571. EXPECT_FALSE(detail::fields::is_field_name(""));
  11572. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11573. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11574. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11575. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11576. }
  11577. TEST(InvalidHeaderCharsTest, is_field_value) {
  11578. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11579. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11580. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11581. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11582. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11583. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11584. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11585. EXPECT_TRUE(detail::fields::is_field_value(""));
  11586. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11587. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11588. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11589. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11590. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11591. }
  11592. TEST(InvalidHeaderCharsTest, OnServer) {
  11593. Server svr;
  11594. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11595. std::string header = "Not Set";
  11596. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11597. res.set_header(header, "value");
  11598. res.set_content("Page Content Page Content", "text/plain");
  11599. });
  11600. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11601. std::string header = "Not Set";
  11602. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11603. res.set_header("X-Test", header);
  11604. res.set_content("Page Content Page Content", "text/plain");
  11605. });
  11606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11607. auto se = detail::scope_exit([&] {
  11608. svr.stop();
  11609. thread.join();
  11610. ASSERT_FALSE(svr.is_running());
  11611. });
  11612. svr.wait_until_ready();
  11613. Client cli(HOST, PORT);
  11614. {
  11615. auto res = cli.Get(
  11616. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11617. ASSERT_TRUE(res);
  11618. EXPECT_EQ("Page Content Page Content", res->body);
  11619. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11620. }
  11621. {
  11622. auto res = cli.Get(
  11623. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11624. ASSERT_TRUE(res);
  11625. EXPECT_EQ("Page Content Page Content", res->body);
  11626. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11627. }
  11628. }
  11629. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11630. auto handled = false;
  11631. Server svr;
  11632. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11633. thread t = thread([&] { svr.listen(HOST, PORT); });
  11634. auto se = detail::scope_exit([&] {
  11635. svr.stop();
  11636. t.join();
  11637. ASSERT_FALSE(svr.is_running());
  11638. ASSERT_FALSE(handled);
  11639. });
  11640. svr.wait_until_ready();
  11641. auto req = "POST /test HTTP/1.1\r\n"
  11642. "Content-Length: x\r\n"
  11643. "\r\n";
  11644. std::string response;
  11645. ASSERT_TRUE(send_request(1, req, &response));
  11646. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11647. response.substr(0, response.find("\r\n")));
  11648. }
  11649. #ifndef _WIN32
  11650. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11651. static constexpr char reject[] = "Unauthorized";
  11652. static constexpr char accept[] = "Upload accepted";
  11653. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11654. Server svr;
  11655. svr.set_expect_100_continue_handler(
  11656. [](const Request & /*req*/, Response &res) {
  11657. res.status = StatusCode::Unauthorized_401;
  11658. res.set_content(reject, "text/plain");
  11659. return res.status;
  11660. });
  11661. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11662. res.set_content(accept, "text/plain");
  11663. });
  11664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11665. auto se = detail::scope_exit([&] {
  11666. svr.stop();
  11667. thread.join();
  11668. ASSERT_FALSE(svr.is_running());
  11669. });
  11670. svr.wait_until_ready();
  11671. {
  11672. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11673. curl_easy_init(), &curl_easy_cleanup};
  11674. ASSERT_NE(curl, nullptr);
  11675. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11676. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11677. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11678. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11679. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11680. &curl_slist_free_all};
  11681. ASSERT_NE(list, nullptr);
  11682. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11683. struct read_data {
  11684. size_t read_size;
  11685. size_t total_size;
  11686. } data = {0, total_size};
  11687. using read_callback_t =
  11688. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11689. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11690. void *userdata) -> size_t {
  11691. read_data *d = (read_data *)userdata;
  11692. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11693. std::fill_n(ptr, size * nmemb, 'A');
  11694. d->read_size += size * nmemb;
  11695. return size * nmemb;
  11696. };
  11697. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11698. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11699. std::vector<char> buffer;
  11700. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11701. using write_callback_t =
  11702. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11703. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11704. void *userdata) -> size_t {
  11705. std::vector<char> *buf = (std::vector<char> *)userdata;
  11706. buf->reserve(buf->size() + size * nmemb + 1);
  11707. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11708. return size * nmemb;
  11709. };
  11710. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11711. {
  11712. const auto res = curl_easy_perform(curl.get());
  11713. ASSERT_EQ(res, CURLE_OK);
  11714. }
  11715. {
  11716. auto response_code = long{};
  11717. const auto res =
  11718. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11719. ASSERT_EQ(res, CURLE_OK);
  11720. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11721. }
  11722. {
  11723. auto dl = curl_off_t{};
  11724. const auto res =
  11725. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11726. ASSERT_EQ(res, CURLE_OK);
  11727. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11728. }
  11729. {
  11730. buffer.push_back('\0');
  11731. ASSERT_STRCASEEQ(buffer.data(), reject);
  11732. }
  11733. }
  11734. }
  11735. #endif
  11736. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11737. // Regression test for #2458.
  11738. //
  11739. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11740. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11741. // ticket can make the client socket spuriously readable during the
  11742. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11743. // the client withholds the body and then blocks reading a response that never
  11744. // comes, failing with `Failed to read connection`.
  11745. //
  11746. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11747. // within the timeout. This raw OpenSSL server deliberately never sends
  11748. // `100 Continue`; the client must still deliver the body and receive 200.
  11749. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11750. signal(SIGPIPE, SIG_IGN);
  11751. const auto port = PORT + 4;
  11752. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11753. ASSERT_NE(srv, INVALID_SOCKET);
  11754. int opt = 1;
  11755. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11756. sockaddr_in addr{};
  11757. addr.sin_family = AF_INET;
  11758. addr.sin_port = htons(static_cast<uint16_t>(port));
  11759. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11760. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11761. ASSERT_EQ(0, ::listen(srv, 1));
  11762. std::atomic<size_t> server_body_bytes{0};
  11763. auto server_thread = std::thread([&] {
  11764. sockaddr_in cli_addr{};
  11765. socklen_t cli_len = sizeof(cli_addr);
  11766. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11767. if (cli == INVALID_SOCKET) { return; }
  11768. // Bound the lifetime of the server side so a buggy client (which never
  11769. // sends the body) cannot make this thread block forever on join.
  11770. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11771. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11772. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11773. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11774. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11775. SSL *ssl = SSL_new(ctx);
  11776. SSL_set_fd(ssl, static_cast<int>(cli));
  11777. if (SSL_accept(ssl) > 0) {
  11778. // Read the request headers. Reading here also flushes the TLS 1.3
  11779. // session tickets to the client. Deliberately do NOT send
  11780. // `100 Continue`.
  11781. std::string buf;
  11782. char tmp[1024];
  11783. while (buf.find("\r\n\r\n") == std::string::npos) {
  11784. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11785. if (n <= 0) { break; }
  11786. buf.append(tmp, static_cast<size_t>(n));
  11787. }
  11788. // A correct client sends the body now; count what arrives.
  11789. auto pos = buf.find("\r\n\r\n");
  11790. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11791. while (body < 4096) {
  11792. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11793. if (n <= 0) { break; }
  11794. body += static_cast<size_t>(n);
  11795. }
  11796. server_body_bytes = body;
  11797. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11798. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11799. SSL_shutdown(ssl);
  11800. }
  11801. SSL_free(ssl);
  11802. detail::close_socket(cli);
  11803. SSL_CTX_free(ctx);
  11804. });
  11805. auto se = detail::scope_exit([&] {
  11806. server_thread.join();
  11807. detail::close_socket(srv);
  11808. });
  11809. SSLClient cli("127.0.0.1", port);
  11810. cli.enable_server_certificate_verification(false);
  11811. cli.set_connection_timeout(5, 0);
  11812. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11813. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11814. std::string body(4096, 'A');
  11815. auto res = cli.Put("/api/test", body, "application/json");
  11816. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11817. EXPECT_EQ(StatusCode::OK_200, res->status);
  11818. EXPECT_EQ(body.size(), server_body_bytes.load());
  11819. }
  11820. #endif
  11821. template <typename S, typename C>
  11822. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11823. svr.Get("/stream", [&](const Request &, Response &res) {
  11824. auto data = new std::string("01234567890123456789");
  11825. res.set_content_provider(
  11826. data->size(), "text/plain",
  11827. [&, data](size_t offset, size_t length, DataSink &sink) {
  11828. const size_t DATA_CHUNK_SIZE = 4;
  11829. const auto &d = *data;
  11830. std::this_thread::sleep_for(std::chrono::seconds(1));
  11831. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11832. return true;
  11833. },
  11834. [data](bool success) {
  11835. EXPECT_FALSE(success);
  11836. delete data;
  11837. });
  11838. });
  11839. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11840. auto i = new size_t(0);
  11841. res.set_content_provider(
  11842. "text/plain",
  11843. [i](size_t, DataSink &sink) {
  11844. if (*i < 5) {
  11845. std::this_thread::sleep_for(std::chrono::seconds(1));
  11846. sink.write("abcd", 4);
  11847. (*i)++;
  11848. } else {
  11849. sink.done();
  11850. }
  11851. return true;
  11852. },
  11853. [i](bool success) {
  11854. EXPECT_FALSE(success);
  11855. delete i;
  11856. });
  11857. });
  11858. svr.Get("/chunked", [&](const Request &, Response &res) {
  11859. auto i = new size_t(0);
  11860. res.set_chunked_content_provider(
  11861. "text/plain",
  11862. [i](size_t, DataSink &sink) {
  11863. if (*i < 5) {
  11864. std::this_thread::sleep_for(std::chrono::seconds(1));
  11865. sink.os << "abcd";
  11866. (*i)++;
  11867. } else {
  11868. sink.done();
  11869. }
  11870. return true;
  11871. },
  11872. [i](bool success) {
  11873. EXPECT_FALSE(success);
  11874. delete i;
  11875. });
  11876. });
  11877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. listen_thread.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11885. {
  11886. auto start = std::chrono::steady_clock::now();
  11887. auto res = cli.Get("/stream");
  11888. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11889. std::chrono::steady_clock::now() - start)
  11890. .count();
  11891. ASSERT_FALSE(res);
  11892. EXPECT_EQ(Error::Read, res.error());
  11893. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11894. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11895. }
  11896. {
  11897. auto start = std::chrono::steady_clock::now();
  11898. auto res = cli.Get("/stream_without_length");
  11899. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11900. std::chrono::steady_clock::now() - start)
  11901. .count();
  11902. ASSERT_FALSE(res);
  11903. EXPECT_EQ(Error::Read, res.error());
  11904. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11905. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11906. }
  11907. {
  11908. auto start = std::chrono::steady_clock::now();
  11909. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11910. EXPECT_EQ("abcd", string(data, data_length));
  11911. return true;
  11912. });
  11913. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11914. std::chrono::steady_clock::now() - start)
  11915. .count();
  11916. ASSERT_FALSE(res);
  11917. EXPECT_EQ(Error::Read, res.error());
  11918. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11919. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11920. }
  11921. }
  11922. TEST(MaxTimeoutTest, ContentStream) {
  11923. time_t timeout = 2000;
  11924. time_t threshold = 200;
  11925. Server svr;
  11926. Client cli("localhost", PORT);
  11927. max_timeout_test(svr, cli, timeout, threshold);
  11928. }
  11929. #ifdef CPPHTTPLIB_SSL_ENABLED
  11930. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11931. time_t timeout = 2000;
  11932. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11934. SSLClient cli("localhost", PORT);
  11935. cli.enable_server_certificate_verification(false);
  11936. max_timeout_test(svr, cli, timeout, threshold);
  11937. }
  11938. #endif
  11939. class EventDispatcher {
  11940. public:
  11941. EventDispatcher() {}
  11942. bool wait_event(DataSink *sink) {
  11943. unique_lock<mutex> lk(m_);
  11944. int id = id_;
  11945. // Wait with timeout to prevent hanging if client disconnects
  11946. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11947. [&] { return cid_ == id; })) {
  11948. return false; // Timeout occurred
  11949. }
  11950. sink->write(message_.data(), message_.size());
  11951. return true;
  11952. }
  11953. void send_event(const string &message) {
  11954. lock_guard<mutex> lk(m_);
  11955. cid_ = id_++;
  11956. message_ = message;
  11957. cv_.notify_all();
  11958. }
  11959. private:
  11960. mutex m_;
  11961. condition_variable cv_;
  11962. atomic_int id_{0};
  11963. atomic_int cid_{-1};
  11964. string message_;
  11965. };
  11966. TEST(ClientInThreadTest, Issue2068) {
  11967. EventDispatcher ed;
  11968. Server svr;
  11969. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11970. res.set_chunked_content_provider("text/event-stream",
  11971. [&](size_t /*offset*/, DataSink &sink) {
  11972. return ed.wait_event(&sink);
  11973. });
  11974. });
  11975. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11976. svr.wait_until_ready();
  11977. thread event_thread([&] {
  11978. int id = 0;
  11979. while (svr.is_running()) {
  11980. this_thread::sleep_for(chrono::milliseconds(500));
  11981. std::stringstream ss;
  11982. ss << "data: " << id << "\n\n";
  11983. ed.send_event(ss.str());
  11984. id++;
  11985. }
  11986. });
  11987. auto se = detail::scope_exit([&] {
  11988. svr.stop();
  11989. listen_thread.join();
  11990. event_thread.join();
  11991. ASSERT_FALSE(svr.is_running());
  11992. });
  11993. {
  11994. auto client = detail::make_unique<Client>(HOST, PORT);
  11995. client->set_read_timeout(std::chrono::minutes(10));
  11996. std::atomic<bool> stop{false};
  11997. std::thread t([&] {
  11998. client->Get("/event1",
  11999. [&](const char *, size_t) -> bool { return !stop; });
  12000. });
  12001. std::this_thread::sleep_for(std::chrono::seconds(2));
  12002. stop = true;
  12003. client->stop();
  12004. t.join();
  12005. // Reset client after thread has finished
  12006. client.reset();
  12007. }
  12008. }
  12009. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12010. auto handled = false;
  12011. Server svr;
  12012. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12014. auto se = detail::scope_exit([&] {
  12015. svr.stop();
  12016. t.join();
  12017. ASSERT_FALSE(svr.is_running());
  12018. ASSERT_FALSE(handled);
  12019. });
  12020. svr.wait_until_ready();
  12021. // Two Content-Length headers with different values — must be rejected
  12022. auto req = "POST /test HTTP/1.1\r\n"
  12023. "Content-Length: 5\r\n"
  12024. "Content-Length: 10\r\n"
  12025. "\r\n"
  12026. "hello";
  12027. std::string response;
  12028. ASSERT_TRUE(send_request(1, req, &response));
  12029. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12030. response.substr(0, response.find("\r\n")));
  12031. }
  12032. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12033. auto handled = false;
  12034. Server svr;
  12035. svr.Post("/test", [&](const Request &, Response &res) {
  12036. handled = true;
  12037. res.set_content("ok", "text/plain");
  12038. });
  12039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12040. auto se = detail::scope_exit([&] {
  12041. svr.stop();
  12042. t.join();
  12043. ASSERT_FALSE(svr.is_running());
  12044. ASSERT_TRUE(handled);
  12045. });
  12046. svr.wait_until_ready();
  12047. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12048. auto req = "POST /test HTTP/1.1\r\n"
  12049. "Content-Length: 5\r\n"
  12050. "Content-Length: 5\r\n"
  12051. "\r\n"
  12052. "hello";
  12053. std::string response;
  12054. ASSERT_TRUE(send_request(1, req, &response));
  12055. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12056. }
  12057. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12058. Server svr;
  12059. svr.Get("/", [](const Request &req, Response &res) {
  12060. EXPECT_EQ(2U, req.trailers.size());
  12061. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12062. // Denied
  12063. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12064. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12065. // Accepted
  12066. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12067. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12068. EXPECT_TRUE(req.has_trailer("X-World"));
  12069. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12070. res.set_content("ok", "text/plain");
  12071. });
  12072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12073. auto se = detail::scope_exit([&] {
  12074. svr.stop();
  12075. t.join();
  12076. ASSERT_FALSE(svr.is_running());
  12077. });
  12078. svr.wait_until_ready();
  12079. const std::string req = "GET / HTTP/1.1\r\n"
  12080. "Transfer-Encoding: chunked\r\n"
  12081. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12082. "\r\n"
  12083. "0\r\n"
  12084. "Content-Length: 10\r\n"
  12085. "Host: internal.local\r\n"
  12086. "Content-Type: malicious/content\r\n"
  12087. "Cookie: any\r\n"
  12088. "Set-Cookie: any\r\n"
  12089. "X-Forwarded-For: attacker.com\r\n"
  12090. "X-Real-Ip: 1.1.1.1\r\n"
  12091. "X-Hello: hello\r\n"
  12092. "X-World: world\r\n"
  12093. "\r\n";
  12094. std::string res;
  12095. ASSERT_TRUE(send_request(1, req, &res));
  12096. }
  12097. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12098. Server svr;
  12099. std::string observed_remote_addr;
  12100. std::string observed_xff;
  12101. svr.Get("/ip", [&](const Request &req, Response &res) {
  12102. observed_remote_addr = req.remote_addr;
  12103. observed_xff = req.get_header_value("X-Forwarded-For");
  12104. res.set_content("ok", "text/plain");
  12105. });
  12106. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12107. auto se = detail::scope_exit([&] {
  12108. svr.stop();
  12109. t.join();
  12110. ASSERT_FALSE(svr.is_running());
  12111. });
  12112. svr.wait_until_ready();
  12113. Client cli(HOST, PORT);
  12114. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12115. ASSERT_TRUE(res);
  12116. EXPECT_EQ(StatusCode::OK_200, res->status);
  12117. EXPECT_EQ(observed_xff, "203.0.113.66");
  12118. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12119. observed_remote_addr == "127.0.0.1");
  12120. }
  12121. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12122. Server svr;
  12123. svr.set_trusted_proxies({"203.0.113.66"});
  12124. std::string observed_remote_addr;
  12125. std::string observed_xff;
  12126. svr.Get("/ip", [&](const Request &req, Response &res) {
  12127. observed_remote_addr = req.remote_addr;
  12128. observed_xff = req.get_header_value("X-Forwarded-For");
  12129. res.set_content("ok", "text/plain");
  12130. });
  12131. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12132. auto se = detail::scope_exit([&] {
  12133. svr.stop();
  12134. t.join();
  12135. ASSERT_FALSE(svr.is_running());
  12136. });
  12137. svr.wait_until_ready();
  12138. Client cli(HOST, PORT);
  12139. auto res = cli.Get("/ip");
  12140. ASSERT_TRUE(res);
  12141. EXPECT_EQ(StatusCode::OK_200, res->status);
  12142. EXPECT_EQ(observed_xff, "");
  12143. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12144. observed_remote_addr == "127.0.0.1");
  12145. }
  12146. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12147. Server svr;
  12148. svr.set_trusted_proxies({"203.0.113.66"});
  12149. std::string observed_remote_addr;
  12150. std::string observed_xff;
  12151. svr.Get("/ip", [&](const Request &req, Response &res) {
  12152. observed_remote_addr = req.remote_addr;
  12153. observed_xff = req.get_header_value("X-Forwarded-For");
  12154. res.set_content("ok", "text/plain");
  12155. });
  12156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12157. auto se = detail::scope_exit([&] {
  12158. svr.stop();
  12159. t.join();
  12160. ASSERT_FALSE(svr.is_running());
  12161. });
  12162. svr.wait_until_ready();
  12163. Client cli(HOST, PORT);
  12164. auto res =
  12165. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12166. ASSERT_TRUE(res);
  12167. EXPECT_EQ(StatusCode::OK_200, res->status);
  12168. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12169. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12170. }
  12171. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12172. Server svr;
  12173. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12174. std::string observed_remote_addr;
  12175. std::string observed_xff;
  12176. svr.Get("/ip", [&](const Request &req, Response &res) {
  12177. observed_remote_addr = req.remote_addr;
  12178. observed_xff = req.get_header_value("X-Forwarded-For");
  12179. res.set_content("ok", "text/plain");
  12180. });
  12181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12182. auto se = detail::scope_exit([&] {
  12183. svr.stop();
  12184. t.join();
  12185. ASSERT_FALSE(svr.is_running());
  12186. });
  12187. svr.wait_until_ready();
  12188. Client cli(HOST, PORT);
  12189. auto res = cli.Get(
  12190. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12191. ASSERT_TRUE(res);
  12192. EXPECT_EQ(StatusCode::OK_200, res->status);
  12193. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12194. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12195. }
  12196. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12197. Server svr;
  12198. svr.set_trusted_proxies({"192.0.2.45"});
  12199. std::string observed_remote_addr;
  12200. std::string observed_xff;
  12201. svr.Get("/ip", [&](const Request &req, Response &res) {
  12202. observed_remote_addr = req.remote_addr;
  12203. observed_xff = req.get_header_value("X-Forwarded-For");
  12204. res.set_content("ok", "text/plain");
  12205. });
  12206. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12207. auto se = detail::scope_exit([&] {
  12208. svr.stop();
  12209. t.join();
  12210. ASSERT_FALSE(svr.is_running());
  12211. });
  12212. svr.wait_until_ready();
  12213. Client cli(HOST, PORT);
  12214. auto res =
  12215. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12216. ASSERT_TRUE(res);
  12217. EXPECT_EQ(StatusCode::OK_200, res->status);
  12218. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12219. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12220. }
  12221. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12222. Server svr;
  12223. svr.set_trusted_proxies({"192.0.2.45"});
  12224. std::string observed_remote_addr;
  12225. std::string observed_xff;
  12226. svr.Get("/ip", [&](const Request &req, Response &res) {
  12227. observed_remote_addr = req.remote_addr;
  12228. observed_xff = req.get_header_value("X-Forwarded-For");
  12229. res.set_content("ok", "text/plain");
  12230. });
  12231. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12232. auto se = detail::scope_exit([&] {
  12233. svr.stop();
  12234. t.join();
  12235. ASSERT_FALSE(svr.is_running());
  12236. });
  12237. svr.wait_until_ready();
  12238. Client cli(HOST, PORT);
  12239. auto res = cli.Get(
  12240. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12241. ASSERT_TRUE(res);
  12242. EXPECT_EQ(StatusCode::OK_200, res->status);
  12243. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12244. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12245. }
  12246. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12247. Server svr;
  12248. svr.set_trusted_proxies({"192.0.2.45"});
  12249. std::string observed_remote_addr;
  12250. std::string observed_xff;
  12251. svr.Get("/ip", [&](const Request &req, Response &res) {
  12252. observed_remote_addr = req.remote_addr;
  12253. observed_xff = req.get_header_value("X-Forwarded-For");
  12254. res.set_content("ok", "text/plain");
  12255. });
  12256. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12257. auto se = detail::scope_exit([&] {
  12258. svr.stop();
  12259. t.join();
  12260. ASSERT_FALSE(svr.is_running());
  12261. });
  12262. svr.wait_until_ready();
  12263. std::string raw_req =
  12264. "GET /ip HTTP/1.1\r\n"
  12265. "Host: localhost\r\n"
  12266. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12267. "Connection: close\r\n"
  12268. "\r\n";
  12269. std::string out;
  12270. ASSERT_TRUE(send_request(5, raw_req, &out));
  12271. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12272. // Header parser trims surrounding whitespace of the header value
  12273. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12274. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12275. }
  12276. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12277. // crash the server (it used to call front() on an empty vector inside
  12278. // get_client_ip). The connection-level remote address must be retained instead.
  12279. static void run_malformed_xff_test(const std::string &xff_value) {
  12280. Server svr;
  12281. svr.set_trusted_proxies({"192.0.2.45"});
  12282. std::string observed_remote_addr;
  12283. svr.Get("/ip", [&](const Request &req, Response &res) {
  12284. observed_remote_addr = req.remote_addr;
  12285. res.set_content("ok", "text/plain");
  12286. });
  12287. int port = 0;
  12288. thread t = thread([&]() {
  12289. port = svr.bind_to_any_port(HOST);
  12290. svr.listen_after_bind();
  12291. });
  12292. auto se = detail::scope_exit([&] {
  12293. svr.stop();
  12294. t.join();
  12295. ASSERT_FALSE(svr.is_running());
  12296. });
  12297. svr.wait_until_ready();
  12298. Client cli(HOST, port);
  12299. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12300. ASSERT_TRUE(res);
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12303. observed_remote_addr == "127.0.0.1");
  12304. }
  12305. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12306. run_malformed_xff_test("");
  12307. }
  12308. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12309. run_malformed_xff_test(",");
  12310. }
  12311. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12312. run_malformed_xff_test(", , ,");
  12313. }
  12314. #ifndef _WIN32
  12315. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12316. Server svr;
  12317. svr.Post("/post", [&](const Request &req, Response &res) {
  12318. res.set_content(req.body, "text/plain");
  12319. });
  12320. svr.Put("/put", [&](const Request &req, Response &res) {
  12321. res.set_content(req.body, "text/plain");
  12322. });
  12323. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12324. res.set_content(req.body, "text/plain");
  12325. });
  12326. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12327. res.set_content(req.body, "text/plain");
  12328. });
  12329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. t.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. std::string resp;
  12337. // POST without Content-Length
  12338. ASSERT_TRUE(send_request(5,
  12339. "POST /post HTTP/1.1\r\n"
  12340. "Host: localhost\r\n"
  12341. "Connection: close\r\n"
  12342. "\r\n",
  12343. &resp));
  12344. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12345. // PUT without Content-Length
  12346. resp.clear();
  12347. ASSERT_TRUE(send_request(5,
  12348. "PUT /put HTTP/1.1\r\n"
  12349. "Host: localhost\r\n"
  12350. "Connection: close\r\n"
  12351. "\r\n",
  12352. &resp));
  12353. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12354. // PATCH without Content-Length
  12355. resp.clear();
  12356. ASSERT_TRUE(send_request(5,
  12357. "PATCH /patch HTTP/1.1\r\n"
  12358. "Host: localhost\r\n"
  12359. "Connection: close\r\n"
  12360. "\r\n",
  12361. &resp));
  12362. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12363. // DELETE without Content-Length
  12364. resp.clear();
  12365. ASSERT_TRUE(send_request(5,
  12366. "DELETE /delete HTTP/1.1\r\n"
  12367. "Host: localhost\r\n"
  12368. "Connection: close\r\n"
  12369. "\r\n",
  12370. &resp));
  12371. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12372. }
  12373. #endif
  12374. //==============================================================================
  12375. // open_stream() Tests
  12376. //==============================================================================
  12377. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12378. std::string result;
  12379. char buf[8192];
  12380. ssize_t n;
  12381. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12382. result.append(buf, static_cast<size_t>(n));
  12383. }
  12384. return result;
  12385. }
  12386. // Mock stream for unit tests
  12387. class MockStream : public Stream {
  12388. public:
  12389. std::string data;
  12390. size_t pos = 0;
  12391. ssize_t error_after = -1; // -1 = no error
  12392. explicit MockStream(const std::string &d, ssize_t err = -1)
  12393. : data(d), error_after(err) {}
  12394. bool is_readable() const override { return true; }
  12395. bool wait_readable() const override { return true; }
  12396. bool wait_writable() const override { return true; }
  12397. ssize_t read(char *ptr, size_t size) override {
  12398. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12399. if (pos >= data.size()) return 0;
  12400. size_t limit =
  12401. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12402. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12403. std::memcpy(ptr, data.data() + pos, to_read);
  12404. pos += to_read;
  12405. return static_cast<ssize_t>(to_read);
  12406. }
  12407. ssize_t write(const char *, size_t) override { return -1; }
  12408. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12409. ip = "127.0.0.1";
  12410. port = 0;
  12411. }
  12412. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12413. ip = "127.0.0.1";
  12414. port = 0;
  12415. }
  12416. socket_t socket() const override { return INVALID_SOCKET; }
  12417. time_t duration() const override { return 0; }
  12418. };
  12419. TEST(StreamHandleTest, Basic) {
  12420. ClientImpl::StreamHandle handle;
  12421. EXPECT_FALSE(handle.is_valid());
  12422. handle.response = detail::make_unique<Response>();
  12423. handle.error = Error::Connection;
  12424. EXPECT_FALSE(handle.is_valid());
  12425. handle.error = Error::Success;
  12426. EXPECT_TRUE(handle.is_valid());
  12427. }
  12428. TEST(BodyReaderTest, Basic) {
  12429. MockStream stream("Hello, World!");
  12430. detail::BodyReader reader;
  12431. reader.stream = &stream;
  12432. reader.content_length = 13;
  12433. char buf[32];
  12434. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12435. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12436. EXPECT_TRUE(reader.eof);
  12437. }
  12438. TEST(BodyReaderTest, NoStream) {
  12439. detail::BodyReader reader;
  12440. char buf[32];
  12441. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12442. EXPECT_EQ(Error::Connection, reader.last_error);
  12443. }
  12444. TEST(BodyReaderTest, Error) {
  12445. MockStream stream("Hello, World!", 5);
  12446. detail::BodyReader reader;
  12447. reader.stream = &stream;
  12448. reader.content_length = 13;
  12449. char buf[32];
  12450. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12451. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12452. EXPECT_EQ(Error::Read, reader.last_error);
  12453. }
  12454. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12455. // Mock-based StreamHandle tests relying on private internals are removed.
  12456. class OpenStreamTest : public ::testing::Test {
  12457. protected:
  12458. void SetUp() override {
  12459. svr_.Get("/hello", [](const Request &, Response &res) {
  12460. res.set_content("Hello World!", "text/plain");
  12461. });
  12462. svr_.Get("/large", [](const Request &, Response &res) {
  12463. res.set_content(std::string(10000, 'X'), "text/plain");
  12464. });
  12465. svr_.Get("/chunked", [](const Request &, Response &res) {
  12466. res.set_chunked_content_provider("text/plain",
  12467. [](size_t offset, DataSink &sink) {
  12468. if (offset < 15) {
  12469. sink.write("chunk", 5);
  12470. return true;
  12471. }
  12472. sink.done();
  12473. return true;
  12474. });
  12475. });
  12476. svr_.Get("/compressible", [](const Request &, Response &res) {
  12477. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12478. DataSink &sink) {
  12479. if (offset < 100 * 1024) {
  12480. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12481. sink.write(chunk.data(), chunk.size());
  12482. return true;
  12483. }
  12484. sink.done();
  12485. return true;
  12486. });
  12487. });
  12488. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12489. [](const Request & /*req*/, Response &res) {
  12490. auto i = new int(0);
  12491. res.set_header("Trailer", "Content-Length, X-Allowed");
  12492. res.set_chunked_content_provider(
  12493. "text/plain",
  12494. [i](size_t /*offset*/, DataSink &sink) {
  12495. switch (*i) {
  12496. case 0: sink.os << "123"; break;
  12497. case 1: sink.os << "456"; break;
  12498. case 2: sink.os << "789"; break;
  12499. case 3: {
  12500. sink.done_with_trailer(
  12501. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12502. } break;
  12503. }
  12504. (*i)++;
  12505. return true;
  12506. },
  12507. [i](bool success) {
  12508. EXPECT_TRUE(success);
  12509. delete i;
  12510. });
  12511. });
  12512. // Echo headers endpoint for header-related tests
  12513. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12514. std::string body;
  12515. for (const auto &h : req.headers) {
  12516. body.append(h.first);
  12517. body.push_back(':');
  12518. body.append(h.second);
  12519. body.push_back('\n');
  12520. }
  12521. res.set_content(body, "text/plain");
  12522. });
  12523. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12524. std::string body;
  12525. for (const auto &h : req.headers) {
  12526. body.append(h.first);
  12527. body.push_back(':');
  12528. body.append(h.second);
  12529. body.push_back('\n');
  12530. }
  12531. res.set_content(body, "text/plain");
  12532. });
  12533. port_ = svr_.bind_to_any_port("127.0.0.1");
  12534. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12535. svr_.wait_until_ready();
  12536. }
  12537. void TearDown() override {
  12538. svr_.stop();
  12539. if (thread_.joinable()) thread_.join();
  12540. }
  12541. Server svr_;
  12542. std::thread thread_;
  12543. int port_ = 0;
  12544. };
  12545. TEST_F(OpenStreamTest, Basic) {
  12546. Client cli("127.0.0.1", port_);
  12547. auto handle = cli.open_stream("GET", "/hello");
  12548. EXPECT_TRUE(handle.is_valid());
  12549. EXPECT_EQ("Hello World!", read_all(handle));
  12550. }
  12551. TEST_F(OpenStreamTest, SmallBuffer) {
  12552. Client cli("127.0.0.1", port_);
  12553. auto handle = cli.open_stream("GET", "/hello");
  12554. std::string result;
  12555. char buf[4];
  12556. ssize_t n;
  12557. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12558. result.append(buf, static_cast<size_t>(n));
  12559. EXPECT_EQ("Hello World!", result);
  12560. }
  12561. TEST_F(OpenStreamTest, DefaultHeaders) {
  12562. Client cli("127.0.0.1", port_);
  12563. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12564. {
  12565. auto handle = cli.open_stream("GET", "/echo-headers");
  12566. ASSERT_TRUE(handle.is_valid());
  12567. auto body = read_all(handle);
  12568. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12569. std::string::npos);
  12570. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12571. std::string::npos);
  12572. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12573. }
  12574. // open_stream POST with body and no explicit content_type should NOT add
  12575. // text/plain Content-Type (behavior differs from non-streaming path), but
  12576. // should include Content-Length
  12577. {
  12578. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12579. ASSERT_TRUE(handle.is_valid());
  12580. auto body = read_all(handle);
  12581. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12582. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12583. }
  12584. // open_stream POST with explicit Content-Type should preserve it
  12585. {
  12586. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12587. {{"Content-Type", "application/custom"}},
  12588. "{}", "application/custom");
  12589. ASSERT_TRUE(handle.is_valid());
  12590. auto body = read_all(handle);
  12591. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12592. }
  12593. // User-specified User-Agent must not be overwritten for stream API
  12594. {
  12595. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12596. {{"User-Agent", "MyAgent/1.2"}});
  12597. ASSERT_TRUE(handle.is_valid());
  12598. auto body = read_all(handle);
  12599. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12600. }
  12601. }
  12602. TEST_F(OpenStreamTest, Large) {
  12603. Client cli("127.0.0.1", port_);
  12604. auto handle = cli.open_stream("GET", "/large");
  12605. EXPECT_EQ(10000u, read_all(handle).size());
  12606. }
  12607. TEST_F(OpenStreamTest, ConnectionError) {
  12608. Client cli("127.0.0.1", 9999);
  12609. auto handle = cli.open_stream("GET", "/hello");
  12610. EXPECT_FALSE(handle.is_valid());
  12611. }
  12612. TEST_F(OpenStreamTest, Chunked) {
  12613. Client cli("127.0.0.1", port_);
  12614. auto handle = cli.open_stream("GET", "/chunked");
  12615. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12616. "Transfer-Encoding") == "chunked");
  12617. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12618. }
  12619. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12620. Client cli("127.0.0.1", port_);
  12621. auto handle =
  12622. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12623. ASSERT_TRUE(handle.is_valid());
  12624. // Consume body to allow trailers to be received/parsed
  12625. auto body = read_all(handle);
  12626. // Explicitly parse trailers (ensure trailers are available for assertion)
  12627. handle.parse_trailers_if_needed();
  12628. EXPECT_EQ(std::string("123456789"), body);
  12629. // The response should include a Trailer header declaring both names
  12630. ASSERT_TRUE(handle.response);
  12631. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12632. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12633. handle.response->get_header_value("Trailer"));
  12634. // Prohibited trailer must not be present
  12635. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12636. // Allowed trailer should be present
  12637. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12638. EXPECT_EQ(std::string("yes"),
  12639. handle.response->get_trailer_value("X-Allowed"));
  12640. // Verify trailers are NOT present as regular headers
  12641. EXPECT_EQ(std::string(""),
  12642. handle.response->get_header_value("Content-Length"));
  12643. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12644. }
  12645. static std::thread serve_single_response(std::promise<int> &port_promise,
  12646. const std::string &response) {
  12647. return std::thread([&port_promise, response] {
  12648. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12649. default_socket_options(srv);
  12650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12652. sockaddr_in addr{};
  12653. addr.sin_family = AF_INET;
  12654. addr.sin_port = htons(0); // Let OS assign a free port
  12655. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12656. int opt = 1;
  12657. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12658. #ifdef _WIN32
  12659. reinterpret_cast<const char *>(&opt),
  12660. #else
  12661. &opt,
  12662. #endif
  12663. sizeof(opt));
  12664. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12665. ::listen(srv, 1) != 0) {
  12666. port_promise.set_value(-1);
  12667. detail::close_socket(srv);
  12668. return;
  12669. }
  12670. socklen_t addr_len = sizeof(addr);
  12671. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12672. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12673. sockaddr_in cli_addr{};
  12674. socklen_t cli_len = sizeof(cli_addr);
  12675. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12676. if (cli != INVALID_SOCKET) {
  12677. // Read the complete HTTP request (until the blank line that terminates
  12678. // headers) before sending the response. If the server closes the socket
  12679. // while the client's request data is still unread in the kernel receive
  12680. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12681. // connection on both sides: it discards the client's receive buffer
  12682. // (which already holds our response) and causes any in-progress write on
  12683. // the client to fail with ECONNRESET. Reading all request data first
  12684. // ensures close() emits a graceful FIN.
  12685. {
  12686. char rbuf[256];
  12687. std::string req;
  12688. while (req.find("\r\n\r\n") == std::string::npos) {
  12689. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12690. if (n <= 0) { break; }
  12691. req.append(rbuf, static_cast<size_t>(n));
  12692. }
  12693. }
  12694. ::send(cli,
  12695. #ifdef _WIN32
  12696. static_cast<const char *>(response.c_str()),
  12697. static_cast<int>(response.size()),
  12698. #else
  12699. response.c_str(), response.size(),
  12700. #endif
  12701. 0);
  12702. detail::close_socket(cli);
  12703. }
  12704. detail::close_socket(srv);
  12705. });
  12706. }
  12707. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12708. #ifndef _WIN32
  12709. signal(SIGPIPE, SIG_IGN);
  12710. #endif
  12711. std::promise<int> port_promise;
  12712. auto port_future = port_promise.get_future();
  12713. auto server_thread =
  12714. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12715. "Content-Type: text/plain\r\n"
  12716. "Content-Length: not-a-number\r\n"
  12717. "Connection: close\r\n"
  12718. "\r\n"
  12719. "hello");
  12720. auto port = port_future.get();
  12721. ASSERT_GT(port, 0);
  12722. Client cli("127.0.0.1", port);
  12723. auto handle = cli.open_stream("GET", "/");
  12724. EXPECT_FALSE(handle.is_valid());
  12725. server_thread.join();
  12726. }
  12727. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12728. #ifndef _WIN32
  12729. signal(SIGPIPE, SIG_IGN);
  12730. #endif
  12731. std::promise<int> port_promise;
  12732. auto port_future = port_promise.get_future();
  12733. auto server_thread = serve_single_response(
  12734. port_promise, "HTTP/1.1 200 OK\r\n"
  12735. "Content-Type: text/plain\r\n"
  12736. "Content-Length: 99999999999999999999999999\r\n"
  12737. "Connection: close\r\n"
  12738. "\r\n"
  12739. "hello");
  12740. auto port = port_future.get();
  12741. ASSERT_GT(port, 0);
  12742. // Before the fix, std::stoull would throw std::out_of_range here and
  12743. // crash the process. After the fix, strtoull silently clamps to
  12744. // ULLONG_MAX so the stream opens without crashing. The important thing
  12745. // is that the process does NOT terminate.
  12746. Client cli("127.0.0.1", port);
  12747. auto handle = cli.open_stream("GET", "/");
  12748. EXPECT_TRUE(handle.is_valid());
  12749. server_thread.join();
  12750. }
  12751. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12752. TEST_F(OpenStreamTest, Gzip) {
  12753. Client cli("127.0.0.1", port_);
  12754. auto handle = cli.open_stream("GET", "/compressible", {},
  12755. {{"Accept-Encoding", "gzip"}});
  12756. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12757. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12758. }
  12759. #endif
  12760. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12761. TEST_F(OpenStreamTest, Brotli) {
  12762. Client cli("127.0.0.1", port_);
  12763. auto handle =
  12764. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12765. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12766. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12767. }
  12768. #endif
  12769. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12770. TEST_F(OpenStreamTest, Zstd) {
  12771. Client cli("127.0.0.1", port_);
  12772. auto handle = cli.open_stream("GET", "/compressible", {},
  12773. {{"Accept-Encoding", "zstd"}});
  12774. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12775. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12776. }
  12777. #endif
  12778. #ifdef CPPHTTPLIB_SSL_ENABLED
  12779. class SSLOpenStreamTest : public ::testing::Test {
  12780. protected:
  12781. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12782. void SetUp() override {
  12783. svr_.Get("/hello", [](const Request &, Response &res) {
  12784. res.set_content("Hello SSL World!", "text/plain");
  12785. });
  12786. svr_.Get("/chunked", [](const Request &, Response &res) {
  12787. res.set_chunked_content_provider("text/plain",
  12788. [](size_t offset, DataSink &sink) {
  12789. if (offset < 15) {
  12790. sink.write("chunk", 5);
  12791. return true;
  12792. }
  12793. sink.done();
  12794. return true;
  12795. });
  12796. });
  12797. svr_.Post("/echo", [](const Request &req, Response &res) {
  12798. res.set_content(req.body, req.get_header_value("Content-Type"));
  12799. });
  12800. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12801. std::string body = req.body;
  12802. res.set_chunked_content_provider(
  12803. "text/plain", [body](size_t offset, DataSink &sink) {
  12804. if (offset < body.size()) {
  12805. sink.write(body.data() + offset, body.size() - offset);
  12806. }
  12807. sink.done();
  12808. return true;
  12809. });
  12810. });
  12811. port_ = svr_.bind_to_any_port("127.0.0.1");
  12812. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12813. svr_.wait_until_ready();
  12814. }
  12815. void TearDown() override {
  12816. svr_.stop();
  12817. if (thread_.joinable()) thread_.join();
  12818. }
  12819. SSLServer svr_;
  12820. std::thread thread_;
  12821. int port_ = 0;
  12822. };
  12823. TEST_F(SSLOpenStreamTest, Basic) {
  12824. SSLClient cli("127.0.0.1", port_);
  12825. cli.enable_server_certificate_verification(false);
  12826. auto handle = cli.open_stream("GET", "/hello");
  12827. ASSERT_TRUE(handle.is_valid());
  12828. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12829. }
  12830. TEST_F(SSLOpenStreamTest, Chunked) {
  12831. SSLClient cli("127.0.0.1", port_);
  12832. cli.enable_server_certificate_verification(false);
  12833. auto handle = cli.open_stream("GET", "/chunked");
  12834. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12835. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12836. "Transfer-Encoding") == "chunked");
  12837. auto body = read_all(handle);
  12838. EXPECT_EQ("chunkchunkchunk", body);
  12839. }
  12840. TEST_F(SSLOpenStreamTest, Post) {
  12841. SSLClient cli("127.0.0.1", port_);
  12842. cli.enable_server_certificate_verification(false);
  12843. auto handle =
  12844. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12845. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12846. EXPECT_EQ(200, handle.response->status);
  12847. auto body = read_all(handle);
  12848. EXPECT_EQ("Hello SSL POST", body);
  12849. }
  12850. TEST_F(SSLOpenStreamTest, PostChunked) {
  12851. SSLClient cli("127.0.0.1", port_);
  12852. cli.enable_server_certificate_verification(false);
  12853. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12854. "Chunked SSL Data", "text/plain");
  12855. ASSERT_TRUE(handle.is_valid());
  12856. EXPECT_EQ(200, handle.response->status);
  12857. auto body = read_all(handle);
  12858. EXPECT_EQ("Chunked SSL Data", body);
  12859. }
  12860. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12861. // Content-Length is terminated by the server closing the connection. When the
  12862. // SSL peer sends a close_notify after the body, the client must treat it as a
  12863. // clean EOF and return a successful response rather than an error.
  12864. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12866. ASSERT_TRUE(svr.is_valid());
  12867. svr.set_keep_alive_max_count(1);
  12868. const std::string expected_body = "Hello from connection-close response!";
  12869. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12870. res.set_content_provider("text/plain",
  12871. [&](size_t offset, DataSink &sink) -> bool {
  12872. if (offset < expected_body.size()) {
  12873. sink.write(expected_body.data() + offset,
  12874. expected_body.size() - offset);
  12875. }
  12876. sink.done();
  12877. return true;
  12878. });
  12879. });
  12880. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12881. auto se = detail::scope_exit([&] {
  12882. svr.stop();
  12883. listen_thread.join();
  12884. ASSERT_FALSE(svr.is_running());
  12885. });
  12886. svr.wait_until_ready();
  12887. SSLClient cli(HOST, PORT);
  12888. cli.enable_server_certificate_verification(false);
  12889. auto res = cli.Get("/no-content-length");
  12890. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12891. EXPECT_EQ(StatusCode::OK_200, res->status);
  12892. EXPECT_EQ(expected_body, res->body);
  12893. }
  12894. #endif // CPPHTTPLIB_SSL_ENABLED
  12895. //==============================================================================
  12896. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12897. // results for various scenarios.
  12898. //==============================================================================
  12899. TEST(ParityTest, GetVsOpenStream) {
  12900. Server svr;
  12901. const std::string path = "/parity";
  12902. const std::string content = "Parity test content: hello world";
  12903. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12904. res.set_content(content, "text/plain");
  12905. });
  12906. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12907. auto se = detail::scope_exit([&] {
  12908. svr.stop();
  12909. t.join();
  12910. ASSERT_FALSE(svr.is_running());
  12911. });
  12912. svr.wait_until_ready();
  12913. Client cli(HOST, PORT);
  12914. // Non-stream path
  12915. auto r1 = cli.Get(path);
  12916. ASSERT_TRUE(r1);
  12917. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12918. // Stream path
  12919. auto h = cli.open_stream("GET", path);
  12920. ASSERT_TRUE(h.is_valid());
  12921. EXPECT_EQ(r1->body, read_all(h));
  12922. }
  12923. // Helper to compress data with provided compressor type T
  12924. template <typename Compressor>
  12925. static std::string compress_payload_for_parity(const std::string &in) {
  12926. std::string out;
  12927. Compressor compressor;
  12928. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12929. [&](const char *data, size_t n) {
  12930. out.append(data, n);
  12931. return true;
  12932. });
  12933. EXPECT_TRUE(ok);
  12934. return out;
  12935. }
  12936. // Helper function for compression parity tests
  12937. template <typename Compressor>
  12938. static void test_compression_parity(const std::string &original,
  12939. const std::string &path,
  12940. const std::string &encoding) {
  12941. const std::string compressed =
  12942. compress_payload_for_parity<Compressor>(original);
  12943. Server svr;
  12944. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12945. res.set_content(compressed, "application/octet-stream");
  12946. res.set_header("Content-Encoding", encoding);
  12947. });
  12948. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12949. auto se = detail::scope_exit([&] {
  12950. svr.stop();
  12951. t.join();
  12952. ASSERT_FALSE(svr.is_running());
  12953. });
  12954. svr.wait_until_ready();
  12955. Client cli(HOST, PORT);
  12956. // Non-streaming
  12957. {
  12958. auto res = cli.Get(path);
  12959. ASSERT_TRUE(res);
  12960. EXPECT_EQ(StatusCode::OK_200, res->status);
  12961. EXPECT_EQ(original, res->body);
  12962. }
  12963. // Streaming
  12964. {
  12965. auto h = cli.open_stream("GET", path);
  12966. ASSERT_TRUE(h.is_valid());
  12967. EXPECT_EQ(original, read_all(h));
  12968. }
  12969. }
  12970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12971. TEST(ParityTest, Gzip) {
  12972. test_compression_parity<detail::gzip_compressor>(
  12973. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12974. }
  12975. #endif
  12976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12977. TEST(ParityTest, Brotli) {
  12978. test_compression_parity<detail::brotli_compressor>(
  12979. "Hello, brotli parity test payload", "/parity-br", "br");
  12980. }
  12981. #endif
  12982. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12983. TEST(ParityTest, Zstd) {
  12984. test_compression_parity<detail::zstd_compressor>(
  12985. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12986. }
  12987. #endif
  12988. //==============================================================================
  12989. // New Stream API Tests
  12990. //==============================================================================
  12991. inline std::string read_body(httplib::stream::Result &result) {
  12992. std::string body;
  12993. while (result.next()) {
  12994. body.append(result.data(), result.size());
  12995. }
  12996. return body;
  12997. }
  12998. TEST(ClientConnectionTest, Basic) {
  12999. httplib::ClientConnection conn;
  13000. EXPECT_FALSE(conn.is_open());
  13001. conn.sock = 1;
  13002. EXPECT_TRUE(conn.is_open());
  13003. httplib::ClientConnection conn2(std::move(conn));
  13004. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13005. conn2.sock = INVALID_SOCKET;
  13006. }
  13007. // Unified test server for all stream::* tests
  13008. class StreamApiTest : public ::testing::Test {
  13009. protected:
  13010. void SetUp() override {
  13011. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13012. res.set_content("Hello World!", "text/plain");
  13013. });
  13014. svr_.Get("/echo-params",
  13015. [](const httplib::Request &req, httplib::Response &res) {
  13016. std::string r;
  13017. for (const auto &p : req.params) {
  13018. if (!r.empty()) r += "&";
  13019. r += p.first + "=" + p.second;
  13020. }
  13021. res.set_content(r, "text/plain");
  13022. });
  13023. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13024. res.set_content(req.body, req.get_header_value("Content-Type"));
  13025. });
  13026. svr_.Post("/echo-headers",
  13027. [](const httplib::Request &req, httplib::Response &res) {
  13028. std::string r;
  13029. for (const auto &h : req.headers)
  13030. r += h.first + ": " + h.second + "\n";
  13031. res.set_content(r, "text/plain");
  13032. });
  13033. svr_.Post("/echo-params",
  13034. [](const httplib::Request &req, httplib::Response &res) {
  13035. std::string r = "params:";
  13036. for (const auto &p : req.params)
  13037. r += p.first + "=" + p.second + ";";
  13038. res.set_content(r + " body:" + req.body, "text/plain");
  13039. });
  13040. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13041. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13042. });
  13043. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13044. res.set_content("PUT:" + req.body, "text/plain");
  13045. });
  13046. svr_.Patch("/echo",
  13047. [](const httplib::Request &req, httplib::Response &res) {
  13048. res.set_content("PATCH:" + req.body, "text/plain");
  13049. });
  13050. svr_.Delete(
  13051. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13052. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13053. "text/plain");
  13054. });
  13055. svr_.Get("/head-test",
  13056. [](const httplib::Request &, httplib::Response &res) {
  13057. res.set_content("body for HEAD", "text/plain");
  13058. });
  13059. svr_.Options("/options",
  13060. [](const httplib::Request &, httplib::Response &res) {
  13061. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13062. });
  13063. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13064. svr_.wait_until_ready();
  13065. }
  13066. void TearDown() override {
  13067. svr_.stop();
  13068. if (thread_.joinable()) thread_.join();
  13069. }
  13070. httplib::Server svr_;
  13071. std::thread thread_;
  13072. };
  13073. // stream::Get tests
  13074. TEST_F(StreamApiTest, GetBasic) {
  13075. httplib::Client cli(HOST, PORT);
  13076. auto result = httplib::stream::Get(cli, "/hello");
  13077. ASSERT_TRUE(result.is_valid());
  13078. EXPECT_EQ(200, result.status());
  13079. EXPECT_EQ("Hello World!", read_body(result));
  13080. }
  13081. TEST_F(StreamApiTest, GetWithParams) {
  13082. httplib::Client cli(HOST, PORT);
  13083. httplib::Params params{{"foo", "bar"}};
  13084. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13085. ASSERT_TRUE(result.is_valid());
  13086. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13087. }
  13088. TEST_F(StreamApiTest, GetConnectionError) {
  13089. httplib::Client cli(HOST, 9999);
  13090. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13091. }
  13092. TEST_F(StreamApiTest, Get404) {
  13093. httplib::Client cli(HOST, PORT);
  13094. auto result = httplib::stream::Get(cli, "/nonexistent");
  13095. EXPECT_TRUE(result.is_valid());
  13096. EXPECT_EQ(404, result.status());
  13097. }
  13098. // stream::Post tests
  13099. TEST_F(StreamApiTest, PostBasic) {
  13100. httplib::Client cli(HOST, PORT);
  13101. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13102. "application/json");
  13103. ASSERT_TRUE(result.is_valid());
  13104. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13105. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13106. }
  13107. TEST_F(StreamApiTest, PostWithHeaders) {
  13108. httplib::Client cli(HOST, PORT);
  13109. httplib::Headers headers{{"X-Custom", "value"}};
  13110. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13111. "text/plain");
  13112. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13113. }
  13114. TEST_F(StreamApiTest, PostWithParams) {
  13115. httplib::Client cli(HOST, PORT);
  13116. httplib::Params params{{"k", "v"}};
  13117. auto result =
  13118. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13119. auto body = read_body(result);
  13120. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13121. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13122. }
  13123. TEST_F(StreamApiTest, PostLarge) {
  13124. httplib::Client cli(HOST, PORT);
  13125. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13126. size_t total = 0;
  13127. while (result.next()) {
  13128. total += result.size();
  13129. }
  13130. EXPECT_EQ(100u * 1024u, total);
  13131. }
  13132. // stream::Put/Patch tests
  13133. TEST_F(StreamApiTest, PutAndPatch) {
  13134. httplib::Client cli(HOST, PORT);
  13135. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13136. EXPECT_EQ("PUT:test", read_body(put));
  13137. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13138. EXPECT_EQ("PATCH:test", read_body(patch));
  13139. }
  13140. // stream::Delete tests
  13141. TEST_F(StreamApiTest, Delete) {
  13142. httplib::Client cli(HOST, PORT);
  13143. auto del1 = httplib::stream::Delete(cli, "/resource");
  13144. EXPECT_EQ("Deleted", read_body(del1));
  13145. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13146. EXPECT_EQ("Deleted:data", read_body(del2));
  13147. }
  13148. // stream::Head/Options tests
  13149. TEST_F(StreamApiTest, HeadAndOptions) {
  13150. httplib::Client cli(HOST, PORT);
  13151. auto head = httplib::stream::Head(cli, "/head-test");
  13152. EXPECT_TRUE(head.is_valid());
  13153. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13154. auto opts = httplib::stream::Options(cli, "/options");
  13155. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13156. }
  13157. // SSL stream::* tests
  13158. #ifdef CPPHTTPLIB_SSL_ENABLED
  13159. class SSLStreamApiTest : public ::testing::Test {
  13160. protected:
  13161. void SetUp() override {
  13162. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13163. res.set_content("Hello SSL!", "text/plain");
  13164. });
  13165. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13166. res.set_content(req.body, "text/plain");
  13167. });
  13168. port_ = svr_.bind_to_any_port("127.0.0.1");
  13169. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13170. svr_.wait_until_ready();
  13171. }
  13172. void TearDown() override {
  13173. svr_.stop();
  13174. if (thread_.joinable()) thread_.join();
  13175. }
  13176. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13177. std::thread thread_;
  13178. int port_ = 0;
  13179. };
  13180. TEST_F(SSLStreamApiTest, GetAndPost) {
  13181. httplib::SSLClient cli("127.0.0.1", port_);
  13182. cli.enable_server_certificate_verification(false);
  13183. auto get = httplib::stream::Get(cli, "/hello");
  13184. EXPECT_EQ("Hello SSL!", read_body(get));
  13185. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13186. EXPECT_EQ("test", read_body(post));
  13187. }
  13188. #endif
  13189. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13190. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13191. // BodyReader
  13192. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13193. // Test that read timeout during streaming is detected
  13194. // Use a large content-length response where server delays mid-stream
  13195. Server svr;
  13196. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13197. // Send a large response with delay in the middle
  13198. res.set_content_provider(
  13199. 1000, // content_length
  13200. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13201. if (offset < 100) {
  13202. // Send first 100 bytes immediately
  13203. std::string data(100, 'A');
  13204. sink.write(data.c_str(), data.size());
  13205. return true;
  13206. }
  13207. // Then delay longer than client timeout
  13208. std::this_thread::sleep_for(std::chrono::seconds(3));
  13209. std::string data(900, 'B');
  13210. sink.write(data.c_str(), data.size());
  13211. return true;
  13212. });
  13213. });
  13214. auto port = 8091;
  13215. std::thread t([&]() { svr.listen("localhost", port); });
  13216. svr.wait_until_ready();
  13217. Client cli("localhost", port);
  13218. cli.set_read_timeout(1, 0); // 1 second timeout
  13219. auto handle = cli.open_stream("GET", "/slow-stream");
  13220. ASSERT_TRUE(handle.is_valid());
  13221. char buf[256];
  13222. ssize_t total = 0;
  13223. ssize_t n;
  13224. bool got_error = false;
  13225. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13226. total += n;
  13227. }
  13228. if (n < 0) {
  13229. got_error = true;
  13230. // Should be timeout or read error
  13231. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13232. handle.get_read_error() == Error::Read)
  13233. << "Actual error: " << to_string(handle.get_read_error());
  13234. }
  13235. // Either we got an error, or we got less data than expected
  13236. EXPECT_TRUE(got_error || total < 1000)
  13237. << "Expected timeout but got all " << total << " bytes";
  13238. svr.stop();
  13239. t.join();
  13240. }
  13241. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13242. // Test connection closed detection via BodyReader
  13243. Server svr;
  13244. std::atomic<bool> close_now{false};
  13245. svr.Get("/will-close", [&](const Request &, Response &res) {
  13246. res.set_content_provider(
  13247. 10000, // Large content_length that we won't fully send
  13248. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13249. if (offset < 100) {
  13250. std::string data(100, 'X');
  13251. sink.write(data.c_str(), data.size());
  13252. return true;
  13253. }
  13254. // Wait for signal then abort
  13255. while (!close_now) {
  13256. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13257. }
  13258. return false; // Abort - server will close connection
  13259. });
  13260. });
  13261. auto port = 8092;
  13262. std::thread t([&]() { svr.listen("localhost", port); });
  13263. svr.wait_until_ready();
  13264. Client cli("localhost", port);
  13265. auto handle = cli.open_stream("GET", "/will-close");
  13266. ASSERT_TRUE(handle.is_valid());
  13267. char buf[256];
  13268. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13269. EXPECT_GT(n, 0) << "First read should succeed";
  13270. // Signal server to close
  13271. close_now = true;
  13272. // Keep reading until error or EOF
  13273. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13274. // Keep reading
  13275. }
  13276. // Should get an error since content_length wasn't satisfied
  13277. if (n < 0) {
  13278. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13279. handle.get_read_error() == Error::Read)
  13280. << "Actual error: " << to_string(handle.get_read_error());
  13281. }
  13282. svr.stop();
  13283. t.join();
  13284. }
  13285. #ifdef CPPHTTPLIB_SSL_ENABLED
  13286. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13287. // Test that read timeout during SSL streaming is detected
  13288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13289. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13290. res.set_content_provider(
  13291. 1000, "text/plain",
  13292. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13293. if (offset < 100) {
  13294. std::string data(100, 'A');
  13295. sink.write(data.c_str(), data.size());
  13296. return true;
  13297. }
  13298. std::this_thread::sleep_for(std::chrono::seconds(3));
  13299. std::string data(900, 'B');
  13300. sink.write(data.c_str(), data.size());
  13301. return true;
  13302. });
  13303. });
  13304. auto port = 8093;
  13305. std::thread t([&]() { svr.listen("localhost", port); });
  13306. svr.wait_until_ready();
  13307. SSLClient cli("localhost", port);
  13308. cli.enable_server_certificate_verification(false);
  13309. cli.set_read_timeout(1, 0); // 1 second timeout
  13310. auto handle = cli.open_stream("GET", "/slow-stream");
  13311. ASSERT_TRUE(handle.is_valid());
  13312. char buf[256];
  13313. ssize_t total = 0;
  13314. ssize_t n;
  13315. bool got_error = false;
  13316. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13317. total += n;
  13318. }
  13319. if (n < 0) {
  13320. got_error = true;
  13321. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13322. handle.get_read_error() == Error::Read)
  13323. << "Actual error: " << to_string(handle.get_read_error());
  13324. }
  13325. EXPECT_TRUE(got_error || total < 1000)
  13326. << "Expected timeout but got all " << total << " bytes";
  13327. svr.stop();
  13328. t.join();
  13329. }
  13330. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13331. // Test SSL connection closed detection
  13332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13333. std::atomic<bool> close_now{false};
  13334. svr.Get("/will-close", [&](const Request &, Response &res) {
  13335. res.set_content_provider(
  13336. 10000, "text/plain",
  13337. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13338. if (offset < 100) {
  13339. std::string data(100, 'X');
  13340. sink.write(data.c_str(), data.size());
  13341. return true;
  13342. }
  13343. while (!close_now) {
  13344. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13345. }
  13346. return false;
  13347. });
  13348. });
  13349. auto port = 8094;
  13350. std::thread t([&]() { svr.listen("localhost", port); });
  13351. svr.wait_until_ready();
  13352. SSLClient cli("localhost", port);
  13353. cli.enable_server_certificate_verification(false);
  13354. auto handle = cli.open_stream("GET", "/will-close");
  13355. ASSERT_TRUE(handle.is_valid());
  13356. char buf[256];
  13357. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13358. EXPECT_GT(n, 0);
  13359. // Signal server to close
  13360. close_now = true;
  13361. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13362. // Keep reading
  13363. }
  13364. if (n < 0) {
  13365. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13366. handle.get_read_error() == Error::Read)
  13367. << "Actual error: " << to_string(handle.get_read_error());
  13368. }
  13369. svr.stop();
  13370. t.join();
  13371. }
  13372. #endif
  13373. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13374. using namespace httplib;
  13375. // Create a test file
  13376. const char *fname = "etag_testfile.txt";
  13377. const char *content = "etag-content";
  13378. {
  13379. std::ofstream ofs(fname);
  13380. ofs << content;
  13381. ASSERT_TRUE(ofs.good());
  13382. }
  13383. Server svr;
  13384. svr.set_mount_point("/static", ".");
  13385. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13386. svr.wait_until_ready();
  13387. Client cli(HOST, PORT);
  13388. // First request: should get 200 with ETag header
  13389. auto res1 = cli.Get("/static/etag_testfile.txt");
  13390. ASSERT_TRUE(res1);
  13391. ASSERT_EQ(200, res1->status);
  13392. ASSERT_TRUE(res1->has_header("ETag"));
  13393. std::string etag = res1->get_header_value("ETag");
  13394. EXPECT_FALSE(etag.empty());
  13395. // Verify ETag format: W/"hex-hex"
  13396. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13397. EXPECT_EQ('W', etag[0]);
  13398. EXPECT_EQ('/', etag[1]);
  13399. EXPECT_EQ('"', etag[2]);
  13400. EXPECT_EQ('"', etag.back());
  13401. // Exact match: expect 304 Not Modified
  13402. Headers h2 = {{"If-None-Match", etag}};
  13403. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13404. ASSERT_TRUE(res2);
  13405. EXPECT_EQ(304, res2->status);
  13406. // Wildcard match: expect 304 Not Modified
  13407. Headers h3 = {{"If-None-Match", "*"}};
  13408. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13409. ASSERT_TRUE(res3);
  13410. EXPECT_EQ(304, res3->status);
  13411. // Non-matching ETag: expect 200
  13412. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13413. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13414. ASSERT_TRUE(res4);
  13415. EXPECT_EQ(200, res4->status);
  13416. // Multiple ETags with one matching: expect 304
  13417. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13418. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13419. ASSERT_TRUE(res5);
  13420. EXPECT_EQ(304, res5->status);
  13421. svr.stop();
  13422. t.join();
  13423. std::remove(fname);
  13424. }
  13425. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13426. using namespace httplib;
  13427. Server svr;
  13428. svr.set_mount_point("/static", ".");
  13429. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13430. svr.wait_until_ready();
  13431. Client cli(HOST, PORT);
  13432. // Send If-None-Match: * to a non-existent file
  13433. Headers h = {{"If-None-Match", "*"}};
  13434. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13435. ASSERT_TRUE(res);
  13436. EXPECT_EQ(404, res->status);
  13437. svr.stop();
  13438. t.join();
  13439. }
  13440. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13441. using namespace httplib;
  13442. // Create a test file
  13443. const char *fname = "etag_boundary_testfile.txt";
  13444. const char *content = "boundary-test";
  13445. {
  13446. std::ofstream ofs(fname);
  13447. ofs << content;
  13448. ASSERT_TRUE(ofs.good());
  13449. }
  13450. Server svr;
  13451. svr.set_mount_point("/static", ".");
  13452. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13453. svr.wait_until_ready();
  13454. Client cli(HOST, PORT);
  13455. // Get the actual ETag
  13456. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13457. ASSERT_TRUE(res1);
  13458. ASSERT_EQ(200, res1->status);
  13459. ASSERT_TRUE(res1->has_header("ETag"));
  13460. std::string etag = res1->get_header_value("ETag");
  13461. // Test 1: Very long ETag value (longer than actual ETag)
  13462. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13463. Headers h1 = {{"If-None-Match", "W/"
  13464. "\"very-long-etag-value-that-is-much-longer-"
  13465. "than-the-actual-etag-value\""}};
  13466. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13467. ASSERT_TRUE(res2);
  13468. EXPECT_EQ(200, res2->status); // Should not match
  13469. // Test 2: Long string followed by wildcard
  13470. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13471. // string)
  13472. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13473. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13474. ASSERT_TRUE(res3);
  13475. EXPECT_EQ(304, res3->status); // Should match on "*"
  13476. // Test 3: Wildcard followed by long string
  13477. // Should match on "*" immediately and return 304
  13478. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13479. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13480. ASSERT_TRUE(res4);
  13481. EXPECT_EQ(304, res4->status); // Should match on "*"
  13482. // Test 4: Multiple long non-matching values
  13483. // Should NOT match and return 200 (test that all comparisons are safe)
  13484. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13485. "W/\"second-long-non-matching-value\", "
  13486. "W/\"third-long-non-matching-value\""}};
  13487. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13488. ASSERT_TRUE(res5);
  13489. EXPECT_EQ(200, res5->status); // Should not match
  13490. // Test 5: Single character that is not "*" (edge case)
  13491. Headers h5 = {{"If-None-Match", "X"}};
  13492. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13493. ASSERT_TRUE(res6);
  13494. EXPECT_EQ(200, res6->status); // Should not match
  13495. svr.stop();
  13496. t.join();
  13497. std::remove(fname);
  13498. }
  13499. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13500. using namespace httplib;
  13501. // Create a test file
  13502. const char *fname = "ims_testfile.txt";
  13503. const char *content = "if-modified-since-test";
  13504. {
  13505. std::ofstream ofs(fname);
  13506. ofs << content;
  13507. ASSERT_TRUE(ofs.good());
  13508. }
  13509. Server svr;
  13510. svr.set_mount_point("/static", ".");
  13511. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13512. svr.wait_until_ready();
  13513. Client cli(HOST, PORT);
  13514. // First request: should get 200 with Last-Modified header
  13515. auto res1 = cli.Get("/static/ims_testfile.txt");
  13516. ASSERT_TRUE(res1);
  13517. ASSERT_EQ(200, res1->status);
  13518. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13519. std::string last_modified = res1->get_header_value("Last-Modified");
  13520. EXPECT_FALSE(last_modified.empty());
  13521. // If-Modified-Since with same time: expect 304
  13522. Headers h2 = {{"If-Modified-Since", last_modified}};
  13523. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13524. ASSERT_TRUE(res2);
  13525. EXPECT_EQ(304, res2->status);
  13526. // If-Modified-Since with future time: expect 304
  13527. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13528. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13529. ASSERT_TRUE(res3);
  13530. EXPECT_EQ(304, res3->status);
  13531. // If-Modified-Since with past time: expect 200
  13532. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13533. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13534. ASSERT_TRUE(res4);
  13535. EXPECT_EQ(200, res4->status);
  13536. // If-None-Match takes precedence over If-Modified-Since
  13537. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13538. ASSERT_TRUE(res1->has_header("ETag"));
  13539. std::string etag = res1->get_header_value("ETag");
  13540. Headers h5 = {{"If-None-Match", etag},
  13541. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13542. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13543. ASSERT_TRUE(res5);
  13544. EXPECT_EQ(304, res5->status);
  13545. svr.stop();
  13546. t.join();
  13547. std::remove(fname);
  13548. }
  13549. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13550. using namespace httplib;
  13551. Server svr;
  13552. // Endpoint that returns compressible content
  13553. svr.Get("/compressible", [](const Request &, Response &res) {
  13554. // Return a large enough body to trigger compression
  13555. std::string body(1000, 'a');
  13556. res.set_content(body, "text/plain");
  13557. });
  13558. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13559. svr.wait_until_ready();
  13560. Client cli(HOST, PORT);
  13561. // Request with gzip support: should get Vary header when compressed
  13562. cli.set_compress(true);
  13563. auto res1 = cli.Get("/compressible");
  13564. ASSERT_TRUE(res1);
  13565. EXPECT_EQ(200, res1->status);
  13566. // If Content-Encoding is set, Vary should also be set
  13567. if (res1->has_header("Content-Encoding")) {
  13568. EXPECT_TRUE(res1->has_header("Vary"));
  13569. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13570. }
  13571. // Request without Accept-Encoding header: should not have compression
  13572. Headers h_no_compress;
  13573. auto res2 = cli.Get("/compressible", h_no_compress);
  13574. ASSERT_TRUE(res2);
  13575. EXPECT_EQ(200, res2->status);
  13576. // Verify Vary header is present when compression is applied
  13577. // (the exact behavior depends on server configuration)
  13578. svr.stop();
  13579. t.join();
  13580. }
  13581. TEST(ETagTest, IfRangeWithETag) {
  13582. using namespace httplib;
  13583. // Create a test file with known content
  13584. const char *fname = "if_range_testfile.txt";
  13585. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13586. {
  13587. std::ofstream ofs(fname);
  13588. ofs << content;
  13589. ASSERT_TRUE(ofs.good());
  13590. }
  13591. Server svr;
  13592. svr.set_mount_point("/static", ".");
  13593. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13594. svr.wait_until_ready();
  13595. Client cli(HOST, PORT);
  13596. // First request: get ETag
  13597. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13598. ASSERT_TRUE(res1);
  13599. ASSERT_EQ(200, res1->status);
  13600. ASSERT_TRUE(res1->has_header("ETag"));
  13601. std::string etag = res1->get_header_value("ETag");
  13602. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13603. // Since our server generates weak ETags (W/"..."), If-Range with our
  13604. // ETag should NOT result in partial content - it should return full content.
  13605. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13606. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13607. ASSERT_TRUE(res2);
  13608. // Weak ETag in If-Range -> full content (200), not partial (206)
  13609. EXPECT_EQ(200, res2->status);
  13610. EXPECT_EQ(content, res2->body);
  13611. EXPECT_FALSE(res2->has_header("Content-Range"));
  13612. // Range request with non-matching If-Range (ETag): should get 200 (full
  13613. // content)
  13614. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13615. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13616. ASSERT_TRUE(res3);
  13617. EXPECT_EQ(200, res3->status);
  13618. EXPECT_EQ(content, res3->body);
  13619. EXPECT_FALSE(res3->has_header("Content-Range"));
  13620. // Range request with strong ETag (hypothetical - our server doesn't generate
  13621. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13622. // should return full content)
  13623. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13624. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13625. ASSERT_TRUE(res4);
  13626. EXPECT_EQ(200, res4->status);
  13627. EXPECT_EQ(content, res4->body);
  13628. EXPECT_FALSE(res4->has_header("Content-Range"));
  13629. svr.stop();
  13630. t.join();
  13631. std::remove(fname);
  13632. }
  13633. TEST(ETagTest, IfRangeWithDate) {
  13634. using namespace httplib;
  13635. // Create a test file
  13636. const char *fname = "if_range_date_testfile.txt";
  13637. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13638. {
  13639. std::ofstream ofs(fname);
  13640. ofs << content;
  13641. ASSERT_TRUE(ofs.good());
  13642. }
  13643. Server svr;
  13644. svr.set_mount_point("/static", ".");
  13645. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13646. svr.wait_until_ready();
  13647. Client cli(HOST, PORT);
  13648. // First request: get Last-Modified
  13649. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13650. ASSERT_TRUE(res1);
  13651. ASSERT_EQ(200, res1->status);
  13652. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13653. std::string last_modified = res1->get_header_value("Last-Modified");
  13654. // Range request with matching If-Range (date): should get 206
  13655. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13656. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13657. ASSERT_TRUE(res2);
  13658. EXPECT_EQ(206, res2->status);
  13659. EXPECT_EQ("FGHIJ", res2->body);
  13660. // Range request with old If-Range date: should get 200 (full content)
  13661. Headers h3 = {{"Range", "bytes=5-9"},
  13662. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13663. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13664. ASSERT_TRUE(res3);
  13665. EXPECT_EQ(200, res3->status);
  13666. EXPECT_EQ(content, res3->body);
  13667. // Range request with future If-Range date: should get 206
  13668. Headers h4 = {{"Range", "bytes=0-4"},
  13669. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13670. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13671. ASSERT_TRUE(res4);
  13672. EXPECT_EQ(206, res4->status);
  13673. EXPECT_EQ("ABCDE", res4->body);
  13674. svr.stop();
  13675. t.join();
  13676. std::remove(fname);
  13677. }
  13678. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13679. using namespace httplib;
  13680. const char *fname = "etag_malformed.txt";
  13681. const char *content = "malformed-etag";
  13682. {
  13683. std::ofstream ofs(fname);
  13684. ofs << content;
  13685. ASSERT_TRUE(ofs.good());
  13686. }
  13687. Server svr;
  13688. svr.set_mount_point("/static", ".");
  13689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13690. svr.wait_until_ready();
  13691. Client cli(HOST, PORT);
  13692. // baseline: should get 200 and an ETag
  13693. auto res1 = cli.Get("/static/etag_malformed.txt");
  13694. ASSERT_TRUE(res1);
  13695. ASSERT_EQ(200, res1->status);
  13696. ASSERT_TRUE(res1->has_header("ETag"));
  13697. // Malformed ETag value (missing quotes) should be treated as non-matching
  13698. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13699. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13700. ASSERT_TRUE(res_bad);
  13701. EXPECT_EQ(200, res_bad->status);
  13702. // Whitespace-only header value should be considered invalid / non-matching
  13703. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13704. "Host: localhost\r\n"
  13705. "If-None-Match: \r\n"
  13706. "Connection: close\r\n"
  13707. "\r\n";
  13708. std::string out;
  13709. ASSERT_TRUE(send_request(5, raw_req, &out));
  13710. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13711. svr.stop();
  13712. t.join();
  13713. std::remove(fname);
  13714. }
  13715. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13716. using namespace httplib;
  13717. const char *fname = "ims_invalid_format.txt";
  13718. const char *content = "ims-bad-format";
  13719. {
  13720. std::ofstream ofs(fname);
  13721. ofs << content;
  13722. ASSERT_TRUE(ofs.good());
  13723. }
  13724. Server svr;
  13725. svr.set_mount_point("/static", ".");
  13726. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13727. svr.wait_until_ready();
  13728. Client cli(HOST, PORT);
  13729. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13730. ASSERT_TRUE(res1);
  13731. ASSERT_EQ(200, res1->status);
  13732. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13733. // If-Modified-Since with invalid format should not result in 304
  13734. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13735. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13736. ASSERT_TRUE(res_bad);
  13737. EXPECT_EQ(200, res_bad->status);
  13738. // If-Range with invalid date format should be treated as mismatch -> full
  13739. // content (200)
  13740. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13741. {"If-Range", "invalid-date"}};
  13742. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13743. ASSERT_TRUE(res_ifrange);
  13744. EXPECT_EQ(200, res_ifrange->status);
  13745. svr.stop();
  13746. t.join();
  13747. std::remove(fname);
  13748. }
  13749. TEST(ETagTest, IfRangeWithMalformedETag) {
  13750. using namespace httplib;
  13751. const char *fname = "ifrange_malformed.txt";
  13752. const std::string content = "0123456789";
  13753. {
  13754. std::ofstream ofs(fname);
  13755. ofs << content;
  13756. ASSERT_TRUE(ofs.good());
  13757. }
  13758. Server svr;
  13759. svr.set_mount_point("/static", ".");
  13760. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13761. svr.wait_until_ready();
  13762. Client cli(HOST, PORT);
  13763. // First request: get ETag
  13764. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13765. ASSERT_TRUE(res1);
  13766. ASSERT_EQ(200, res1->status);
  13767. ASSERT_TRUE(res1->has_header("ETag"));
  13768. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13769. // full content (200)
  13770. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13771. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13772. ASSERT_TRUE(res2);
  13773. EXPECT_EQ(200, res2->status);
  13774. EXPECT_EQ(content, res2->body);
  13775. svr.stop();
  13776. t.join();
  13777. std::remove(fname);
  13778. }
  13779. TEST(ETagTest, ExtremeLargeDateValues) {
  13780. using namespace httplib;
  13781. const char *fname = "ims_extreme_date.txt";
  13782. const char *content = "ims-extreme-date";
  13783. {
  13784. std::ofstream ofs(fname);
  13785. ofs << content;
  13786. ASSERT_TRUE(ofs.good());
  13787. }
  13788. Server svr;
  13789. svr.set_mount_point("/static", ".");
  13790. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13791. svr.wait_until_ready();
  13792. Client cli(HOST, PORT);
  13793. auto res1 = cli.Get(std::string("/static/") + fname);
  13794. ASSERT_TRUE(res1);
  13795. ASSERT_EQ(200, res1->status);
  13796. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13797. // Extremely large year that may overflow date parsing routines.
  13798. Headers h_large_date = {
  13799. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13800. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13801. ASSERT_TRUE(res_bad);
  13802. // Expect server to treat this as invalid/mismatch and return full content
  13803. EXPECT_EQ(200, res_bad->status);
  13804. // If-Range with extremely large date should be treated as mismatch -> full
  13805. // content (200)
  13806. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13807. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13808. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13809. ASSERT_TRUE(res_ifrange);
  13810. EXPECT_EQ(200, res_ifrange->status);
  13811. svr.stop();
  13812. t.join();
  13813. std::remove(fname);
  13814. }
  13815. TEST(ETagTest, NegativeFileModificationTime) {
  13816. using namespace httplib;
  13817. const char *fname = "ims_negative_mtime.txt";
  13818. const std::string content = "negative-mtime";
  13819. {
  13820. std::ofstream ofs(fname);
  13821. ofs << content;
  13822. ASSERT_TRUE(ofs.good());
  13823. }
  13824. // Try to set file mtime to a negative value. This may fail on some
  13825. // platforms/filesystems; if it fails, the test will still verify server
  13826. // behaves safely by performing a regular conditional request.
  13827. #if defined(__APPLE__) || defined(__linux__)
  13828. bool set_negative = false;
  13829. do {
  13830. struct timeval times[2];
  13831. // access time: now
  13832. times[0].tv_sec = time(nullptr);
  13833. times[0].tv_usec = 0;
  13834. // modification time: negative (e.g., -1)
  13835. times[1].tv_sec = -1;
  13836. times[1].tv_usec = 0;
  13837. if (utimes(fname, times) == 0) { set_negative = true; }
  13838. } while (0);
  13839. #else
  13840. bool set_negative = false;
  13841. #endif
  13842. Server svr;
  13843. svr.set_mount_point("/static", ".");
  13844. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13845. svr.wait_until_ready();
  13846. Client cli(HOST, PORT);
  13847. auto res1 = cli.Get(std::string("/static/") + fname);
  13848. ASSERT_TRUE(res1);
  13849. ASSERT_EQ(200, res1->status);
  13850. bool has_last_modified = res1->has_header("Last-Modified");
  13851. std::string last_modified;
  13852. if (has_last_modified) {
  13853. last_modified = res1->get_header_value("Last-Modified");
  13854. }
  13855. if (set_negative) {
  13856. // If we successfully set a negative mtime, ensure server returns a
  13857. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13858. // with an old date and ensure server handles it without crash.
  13859. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13860. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13861. ASSERT_TRUE(res2);
  13862. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13863. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13864. } else {
  13865. // Could not set negative mtime on this platform; fall back to verifying
  13866. // that normal invalid/malformed dates are treated safely (non-304).
  13867. Headers h_bad_date = {
  13868. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13869. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13870. ASSERT_TRUE(res_bad);
  13871. EXPECT_EQ(200, res_bad->status);
  13872. }
  13873. svr.stop();
  13874. t.join();
  13875. std::remove(fname);
  13876. }
  13877. //==============================================================================
  13878. // SSE Parsing Tests
  13879. //==============================================================================
  13880. class SSEParsingTest : public ::testing::Test {
  13881. protected:
  13882. // Test helper that mimics SSE parsing behavior
  13883. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13884. int &retry_ms) {
  13885. // Blank line signals end of event
  13886. if (line.empty() || line == "\r") { return true; }
  13887. // Lines starting with ':' are comments (ignored)
  13888. if (!line.empty() && line[0] == ':') { return false; }
  13889. // Find the colon separator
  13890. auto colon_pos = line.find(':');
  13891. if (colon_pos == std::string::npos) {
  13892. // Line with no colon is treated as field name with empty value
  13893. return false;
  13894. }
  13895. std::string field = line.substr(0, colon_pos);
  13896. std::string value;
  13897. // Value starts after colon, skip optional single space
  13898. if (colon_pos + 1 < line.size()) {
  13899. size_t value_start = colon_pos + 1;
  13900. if (line[value_start] == ' ') { value_start++; }
  13901. value = line.substr(value_start);
  13902. // Remove trailing \r if present
  13903. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13904. }
  13905. // Handle known fields
  13906. if (field == "event") {
  13907. msg.event = value;
  13908. } else if (field == "data") {
  13909. // Multiple data lines are concatenated with newlines
  13910. if (!msg.data.empty()) { msg.data += "\n"; }
  13911. msg.data += value;
  13912. } else if (field == "id") {
  13913. // Empty id is valid (clears the last event ID)
  13914. msg.id = value;
  13915. } else if (field == "retry") {
  13916. // Parse retry interval in milliseconds
  13917. {
  13918. int v = 0;
  13919. auto res =
  13920. detail::from_chars(value.data(), value.data() + value.size(), v);
  13921. if (res.ec == std::errc{}) { retry_ms = v; }
  13922. }
  13923. }
  13924. // Unknown fields are ignored per SSE spec
  13925. return false;
  13926. }
  13927. };
  13928. // Test: Single-line data
  13929. TEST_F(SSEParsingTest, SingleLineData) {
  13930. sse::SSEMessage msg;
  13931. int retry_ms = 3000;
  13932. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13933. EXPECT_EQ(msg.data, "hello");
  13934. EXPECT_EQ(msg.event, "message");
  13935. // Blank line ends event
  13936. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13937. }
  13938. // Test: Multi-line data
  13939. TEST_F(SSEParsingTest, MultiLineData) {
  13940. sse::SSEMessage msg;
  13941. int retry_ms = 3000;
  13942. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13943. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13944. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13945. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13946. }
  13947. // Test: Custom event types
  13948. TEST_F(SSEParsingTest, CustomEventType) {
  13949. sse::SSEMessage msg;
  13950. int retry_ms = 3000;
  13951. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13952. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13953. EXPECT_EQ(msg.event, "update");
  13954. EXPECT_EQ(msg.data, "payload");
  13955. }
  13956. // Test: Event ID handling
  13957. TEST_F(SSEParsingTest, EventIdHandling) {
  13958. sse::SSEMessage msg;
  13959. int retry_ms = 3000;
  13960. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13961. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13962. EXPECT_EQ(msg.id, "12345");
  13963. }
  13964. // Test: Empty event ID (clears last event ID)
  13965. TEST_F(SSEParsingTest, EmptyEventId) {
  13966. sse::SSEMessage msg;
  13967. msg.id = "previous";
  13968. int retry_ms = 3000;
  13969. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13970. EXPECT_EQ(msg.id, "");
  13971. }
  13972. // Test: Retry field parsing
  13973. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13974. sse::SSEMessage msg;
  13975. int retry_ms = 3000;
  13976. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13977. EXPECT_EQ(retry_ms, 5000);
  13978. }
  13979. // Test: Invalid retry value
  13980. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13981. sse::SSEMessage msg;
  13982. int retry_ms = 3000;
  13983. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13984. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13985. }
  13986. // Test: Comments (lines starting with :)
  13987. TEST_F(SSEParsingTest, CommentsIgnored) {
  13988. sse::SSEMessage msg;
  13989. int retry_ms = 3000;
  13990. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13991. EXPECT_EQ(msg.data, "");
  13992. EXPECT_EQ(msg.event, "message");
  13993. }
  13994. // Test: Colon in value
  13995. TEST_F(SSEParsingTest, ColonInValue) {
  13996. sse::SSEMessage msg;
  13997. int retry_ms = 3000;
  13998. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13999. EXPECT_EQ(msg.data, "hello:world:test");
  14000. }
  14001. // Test: Line with no colon (field name only)
  14002. TEST_F(SSEParsingTest, FieldNameOnly) {
  14003. sse::SSEMessage msg;
  14004. int retry_ms = 3000;
  14005. // According to SSE spec, this is treated as field name with empty value
  14006. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14007. // Since we don't recognize "data" without colon, data should be empty
  14008. EXPECT_EQ(msg.data, "");
  14009. }
  14010. // Test: Trailing \r handling
  14011. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14012. sse::SSEMessage msg;
  14013. int retry_ms = 3000;
  14014. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14015. EXPECT_EQ(msg.data, "hello");
  14016. }
  14017. // Test: Unknown fields ignored
  14018. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14019. sse::SSEMessage msg;
  14020. int retry_ms = 3000;
  14021. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14022. EXPECT_EQ(msg.data, "");
  14023. EXPECT_EQ(msg.event, "message");
  14024. }
  14025. // Test: Space after colon is optional
  14026. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14027. sse::SSEMessage msg1, msg2;
  14028. int retry_ms = 3000;
  14029. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14030. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14031. EXPECT_EQ(msg1.data, "hello");
  14032. EXPECT_EQ(msg2.data, "hello");
  14033. }
  14034. // Test: SSEMessage clear
  14035. TEST_F(SSEParsingTest, MessageClear) {
  14036. sse::SSEMessage msg;
  14037. msg.event = "custom";
  14038. msg.data = "some data";
  14039. msg.id = "123";
  14040. msg.clear();
  14041. EXPECT_EQ(msg.event, "message");
  14042. EXPECT_EQ(msg.data, "");
  14043. EXPECT_EQ(msg.id, "");
  14044. }
  14045. // Test: Complete event parsing
  14046. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14047. sse::SSEMessage msg;
  14048. int retry_ms = 3000;
  14049. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14050. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14051. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14052. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14053. // Blank line ends event
  14054. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14055. EXPECT_EQ(msg.event, "notification");
  14056. EXPECT_EQ(msg.id, "evt-42");
  14057. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14058. EXPECT_EQ(retry_ms, 1000);
  14059. }
  14060. //==============================================================================
  14061. // Integration Tests with Server
  14062. //==============================================================================
  14063. class SSEIntegrationTest : public ::testing::Test {
  14064. protected:
  14065. void SetUp() override {
  14066. stop_server_.store(false);
  14067. events_.clear();
  14068. server_ = httplib::detail::make_unique<Server>();
  14069. setup_server();
  14070. start_server();
  14071. }
  14072. void TearDown() override {
  14073. stop_server_.store(true);
  14074. event_cv_.notify_all();
  14075. server_->stop();
  14076. if (server_thread_.joinable()) { server_thread_.join(); }
  14077. }
  14078. void setup_server() {
  14079. // Simple SSE endpoint
  14080. server_->Get("/events", [this](const Request &req, Response &res) {
  14081. auto last_id = req.get_header_value("Last-Event-ID");
  14082. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14083. res.set_chunked_content_provider(
  14084. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14085. std::unique_lock<std::mutex> lock(event_mutex_);
  14086. if (event_cv_.wait_for(
  14087. lock, std::chrono::milliseconds(200), [this] {
  14088. return !events_.empty() || stop_server_.load();
  14089. })) {
  14090. if (stop_server_.load()) { return false; }
  14091. if (!events_.empty()) {
  14092. std::string event = events_.front();
  14093. events_.erase(events_.begin());
  14094. sink.write(event.data(), event.size());
  14095. return true;
  14096. }
  14097. }
  14098. return !stop_server_.load();
  14099. });
  14100. });
  14101. // Endpoint that returns error
  14102. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14103. res.status = 500;
  14104. res.set_content("Internal Server Error", "text/plain");
  14105. });
  14106. // Endpoint for custom event types
  14107. server_->Get("/custom-events", [](const Request &, Response &res) {
  14108. res.set_chunked_content_provider(
  14109. "text/event-stream", [](size_t offset, DataSink &sink) {
  14110. if (offset == 0) {
  14111. std::string event = "event: update\ndata: updated\n\n"
  14112. "event: delete\ndata: deleted\n\n";
  14113. sink.write(event.data(), event.size());
  14114. }
  14115. return false; // End stream after sending
  14116. });
  14117. });
  14118. }
  14119. void start_server() {
  14120. port_ = server_->bind_to_any_port(HOST);
  14121. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14122. // Wait for server to start
  14123. while (!server_->is_running()) {
  14124. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14125. }
  14126. }
  14127. int get_port() const { return port_; }
  14128. void send_event(const std::string &event) {
  14129. std::lock_guard<std::mutex> lock(event_mutex_);
  14130. events_.push_back(event);
  14131. event_cv_.notify_all();
  14132. }
  14133. std::unique_ptr<Server> server_;
  14134. std::thread server_thread_;
  14135. std::mutex event_mutex_;
  14136. std::condition_variable event_cv_;
  14137. std::vector<std::string> events_;
  14138. std::atomic<bool> stop_server_{false};
  14139. std::string last_received_event_id_;
  14140. int port_ = 0;
  14141. };
  14142. // Test: Successful connection and on_open callback
  14143. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14144. // Add a simple endpoint that sends one event and closes
  14145. server_->Get("/simple-event", [](const Request &, Response &res) {
  14146. res.set_chunked_content_provider(
  14147. "text/event-stream", [](size_t offset, DataSink &sink) {
  14148. if (offset == 0) {
  14149. std::string event = "data: hello\n\n";
  14150. sink.write(event.data(), event.size());
  14151. }
  14152. return false; // Close stream after sending
  14153. });
  14154. });
  14155. Client client("localhost", get_port());
  14156. sse::SSEClient sse(client, "/simple-event");
  14157. std::atomic<bool> open_called{false};
  14158. std::atomic<bool> message_received{false};
  14159. sse.on_open([&open_called]() { open_called.store(true); });
  14160. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14161. if (msg.data == "hello") { message_received.store(true); }
  14162. });
  14163. sse.set_reconnect_interval(100);
  14164. sse.set_max_reconnect_attempts(1);
  14165. // Start async
  14166. sse.start_async();
  14167. // Wait for message to be processed
  14168. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14169. sse.stop();
  14170. EXPECT_TRUE(open_called.load());
  14171. EXPECT_TRUE(message_received.load());
  14172. }
  14173. // Test: on_message callback
  14174. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14175. // Endpoint that sends multiple events then closes
  14176. server_->Get("/multi-event", [](const Request &, Response &res) {
  14177. res.set_chunked_content_provider(
  14178. "text/event-stream", [](size_t offset, DataSink &sink) {
  14179. if (offset == 0) {
  14180. std::string events = "data: message1\n\ndata: message2\n\n";
  14181. sink.write(events.data(), events.size());
  14182. }
  14183. return false;
  14184. });
  14185. });
  14186. Client client("localhost", get_port());
  14187. sse::SSEClient sse(client, "/multi-event");
  14188. std::vector<std::string> received_messages;
  14189. std::mutex messages_mutex;
  14190. sse.on_message([&](const sse::SSEMessage &msg) {
  14191. std::lock_guard<std::mutex> lock(messages_mutex);
  14192. received_messages.push_back(msg.data);
  14193. });
  14194. sse.set_reconnect_interval(100);
  14195. sse.set_max_reconnect_attempts(1);
  14196. sse.start_async();
  14197. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14198. sse.stop();
  14199. std::lock_guard<std::mutex> lock(messages_mutex);
  14200. EXPECT_GE(received_messages.size(), 2u);
  14201. if (received_messages.size() >= 2) {
  14202. EXPECT_EQ(received_messages[0], "message1");
  14203. EXPECT_EQ(received_messages[1], "message2");
  14204. }
  14205. }
  14206. // Test: on_event for specific types
  14207. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14208. Client client("localhost", get_port());
  14209. sse::SSEClient sse(client, "/custom-events");
  14210. std::atomic<bool> update_received{false};
  14211. std::atomic<bool> delete_received{false};
  14212. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14213. if (msg.data == "updated") { update_received.store(true); }
  14214. });
  14215. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14216. if (msg.data == "deleted") { delete_received.store(true); }
  14217. });
  14218. sse.set_max_reconnect_attempts(1);
  14219. sse.start_async();
  14220. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14221. sse.stop();
  14222. EXPECT_TRUE(update_received.load());
  14223. EXPECT_TRUE(delete_received.load());
  14224. }
  14225. // Test: on_error callback on connection failure
  14226. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14227. // Connect to a non-existent port
  14228. Client client("localhost", 59999);
  14229. sse::SSEClient sse(client, "/events");
  14230. std::atomic<bool> error_called{false};
  14231. Error received_error = Error::Success;
  14232. sse.on_error([&](Error err) {
  14233. error_called.store(true);
  14234. received_error = err;
  14235. });
  14236. sse.set_reconnect_interval(50);
  14237. sse.set_max_reconnect_attempts(1);
  14238. sse.start_async();
  14239. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14240. sse.stop();
  14241. EXPECT_TRUE(error_called.load());
  14242. EXPECT_NE(received_error, Error::Success);
  14243. }
  14244. // Test: Last-Event-ID header sent on reconnect
  14245. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14246. // Endpoint that sends event with ID
  14247. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14248. res.set_chunked_content_provider(
  14249. "text/event-stream", [](size_t offset, DataSink &sink) {
  14250. if (offset == 0) {
  14251. std::string event = "id: evt-123\ndata: test\n\n";
  14252. sink.write(event.data(), event.size());
  14253. }
  14254. return false;
  14255. });
  14256. });
  14257. Client client("localhost", get_port());
  14258. sse::SSEClient sse(client, "/event-with-id");
  14259. std::atomic<bool> id_received{false};
  14260. sse.on_message([&](const sse::SSEMessage &msg) {
  14261. if (!msg.id.empty()) { id_received.store(true); }
  14262. });
  14263. sse.set_reconnect_interval(100);
  14264. sse.set_max_reconnect_attempts(1);
  14265. sse.start_async();
  14266. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14267. sse.stop();
  14268. EXPECT_TRUE(id_received.load());
  14269. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14270. }
  14271. // Test: Manual stop
  14272. TEST_F(SSEIntegrationTest, ManualStop) {
  14273. // Endpoint that sends one event and stays open briefly
  14274. std::atomic<bool> handler_running{true};
  14275. server_->Get("/stay-open", [&handler_running](const Request &,
  14276. Response &res) {
  14277. res.set_chunked_content_provider(
  14278. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14279. if (offset == 0) {
  14280. std::string event = "data: connected\n\n";
  14281. sink.write(event.data(), event.size());
  14282. }
  14283. // Keep connection open while handler_running is true
  14284. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14285. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14286. }
  14287. return false;
  14288. });
  14289. });
  14290. Client client("localhost", get_port());
  14291. sse::SSEClient sse(client, "/stay-open");
  14292. std::atomic<bool> connected{false};
  14293. sse.on_open([&connected]() { connected.store(true); });
  14294. sse.set_reconnect_interval(100);
  14295. sse.set_max_reconnect_attempts(1);
  14296. sse.start_async();
  14297. // Wait for connection to establish
  14298. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14299. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14300. }
  14301. EXPECT_TRUE(connected.load());
  14302. EXPECT_TRUE(sse.is_connected());
  14303. // Signal handler to stop
  14304. handler_running.store(false);
  14305. // Stop SSE client
  14306. sse.stop();
  14307. EXPECT_FALSE(sse.is_connected());
  14308. }
  14309. // Test: SSEClient with custom headers
  14310. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14311. // Setup a server endpoint that checks for custom header
  14312. std::atomic<bool> header_received{false};
  14313. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14314. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14315. header_received.store(true);
  14316. }
  14317. res.set_chunked_content_provider("text/event-stream",
  14318. [](size_t, DataSink &) { return false; });
  14319. });
  14320. Client client("localhost", get_port());
  14321. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14322. sse::SSEClient sse(client, "/header-check", headers);
  14323. sse.set_max_reconnect_attempts(1);
  14324. sse.start_async();
  14325. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14326. sse.stop();
  14327. EXPECT_TRUE(header_received.load());
  14328. }
  14329. // Test: Reconnect interval configuration
  14330. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14331. Client client("localhost", get_port());
  14332. sse::SSEClient sse(client, "/events");
  14333. auto &result = sse.set_reconnect_interval(500);
  14334. // Builder pattern should return reference to self
  14335. EXPECT_EQ(&result, &sse);
  14336. }
  14337. // Test: Max reconnect attempts
  14338. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14339. // Connect to non-existent port to force reconnects
  14340. Client client("localhost", 59998);
  14341. sse::SSEClient sse(client, "/events");
  14342. std::atomic<int> error_count{0};
  14343. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14344. sse.set_reconnect_interval(50);
  14345. sse.set_max_reconnect_attempts(2);
  14346. auto start = std::chrono::steady_clock::now();
  14347. sse.start(); // Blocking call
  14348. auto end = std::chrono::steady_clock::now();
  14349. // Should have stopped after 2 failed attempts
  14350. EXPECT_GE(error_count.load(), 2);
  14351. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14352. auto duration =
  14353. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14354. #ifdef _WIN32
  14355. // Windows is much slower for socket connection failures
  14356. EXPECT_LT(duration.count(), 7000);
  14357. #else
  14358. EXPECT_LT(duration.count(), 1000);
  14359. #endif
  14360. }
  14361. // Test: Multi-line data in integration
  14362. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14363. // Endpoint with multi-line data
  14364. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14365. res.set_chunked_content_provider(
  14366. "text/event-stream", [](size_t offset, DataSink &sink) {
  14367. if (offset == 0) {
  14368. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14369. sink.write(event.data(), event.size());
  14370. }
  14371. return false;
  14372. });
  14373. });
  14374. Client client("localhost", get_port());
  14375. sse::SSEClient sse(client, "/multiline-data");
  14376. std::string received_data;
  14377. std::mutex data_mutex;
  14378. sse.on_message([&](const sse::SSEMessage &msg) {
  14379. std::lock_guard<std::mutex> lock(data_mutex);
  14380. received_data = msg.data;
  14381. });
  14382. sse.set_reconnect_interval(100);
  14383. sse.set_max_reconnect_attempts(1);
  14384. sse.start_async();
  14385. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14386. sse.stop();
  14387. std::lock_guard<std::mutex> lock(data_mutex);
  14388. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14389. }
  14390. // Test: Auto-reconnect after server disconnection
  14391. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14392. std::atomic<int> connection_count{0};
  14393. std::atomic<int> message_count{0};
  14394. // Endpoint that sends one event and closes, forcing reconnect
  14395. server_->Get("/reconnect-test",
  14396. [&connection_count](const Request &, Response &res) {
  14397. connection_count.fetch_add(1);
  14398. res.set_chunked_content_provider(
  14399. "text/event-stream", [](size_t offset, DataSink &sink) {
  14400. if (offset == 0) {
  14401. std::string event = "data: hello\n\n";
  14402. sink.write(event.data(), event.size());
  14403. }
  14404. return false; // Close connection after sending
  14405. });
  14406. });
  14407. Client client("localhost", get_port());
  14408. sse::SSEClient sse(client, "/reconnect-test");
  14409. sse.on_message([&message_count](const sse::SSEMessage &) {
  14410. message_count.fetch_add(1);
  14411. });
  14412. sse.set_reconnect_interval(100);
  14413. sse.set_max_reconnect_attempts(3);
  14414. sse.start_async();
  14415. // Wait long enough for multiple reconnects
  14416. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14417. sse.stop();
  14418. // Should have connected multiple times (initial + reconnects)
  14419. EXPECT_GE(connection_count.load(), 2);
  14420. // Should have received messages from multiple connections
  14421. EXPECT_GE(message_count.load(), 2);
  14422. }
  14423. // Test: Last-Event-ID sent on reconnect
  14424. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14425. std::atomic<int> connection_count{0};
  14426. std::vector<std::string> received_last_event_ids;
  14427. std::mutex id_mutex;
  14428. // Endpoint that checks Last-Event-ID header and sends event with ID
  14429. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14430. int conn = connection_count.fetch_add(1);
  14431. // Capture the Last-Event-ID header from each connection
  14432. {
  14433. std::lock_guard<std::mutex> lock(id_mutex);
  14434. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14435. }
  14436. res.set_chunked_content_provider(
  14437. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14438. if (offset == 0) {
  14439. std::string event =
  14440. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14441. sink.write(event.data(), event.size());
  14442. }
  14443. return false;
  14444. });
  14445. });
  14446. Client client("localhost", get_port());
  14447. sse::SSEClient sse(client, "/reconnect-with-id");
  14448. sse.set_reconnect_interval(100);
  14449. sse.set_max_reconnect_attempts(3);
  14450. sse.start_async();
  14451. // Wait for at least 2 connections
  14452. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14453. sse.stop();
  14454. // Verify behavior
  14455. std::lock_guard<std::mutex> lock(id_mutex);
  14456. EXPECT_GE(received_last_event_ids.size(), 2u);
  14457. // First connection should have no Last-Event-ID
  14458. if (!received_last_event_ids.empty()) {
  14459. EXPECT_EQ(received_last_event_ids[0], "");
  14460. }
  14461. // Second connection should have Last-Event-ID from first connection
  14462. if (received_last_event_ids.size() >= 2) {
  14463. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14464. }
  14465. }
  14466. // Test: set_headers updates headers used on reconnect
  14467. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14468. std::vector<std::string> received_tokens;
  14469. std::mutex token_mutex;
  14470. // Endpoint that captures Authorization header
  14471. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14472. {
  14473. std::lock_guard<std::mutex> lock(token_mutex);
  14474. received_tokens.push_back(req.get_header_value("Authorization"));
  14475. }
  14476. res.set_chunked_content_provider(
  14477. "text/event-stream", [](size_t offset, DataSink &sink) {
  14478. if (offset == 0) {
  14479. std::string event = "data: hello\n\n";
  14480. sink.write(event.data(), event.size());
  14481. }
  14482. return false; // Close connection to trigger reconnect
  14483. });
  14484. });
  14485. Client client("localhost", get_port());
  14486. Headers headers = {{"Authorization", "Bearer old-token"}};
  14487. sse::SSEClient sse(client, "/auth-check", headers);
  14488. // Update headers on each successful connection
  14489. sse.on_open(
  14490. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14491. sse.set_reconnect_interval(100);
  14492. sse.set_max_reconnect_attempts(3);
  14493. sse.start_async();
  14494. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14495. sse.stop();
  14496. std::lock_guard<std::mutex> lock(token_mutex);
  14497. ASSERT_GE(received_tokens.size(), 2u);
  14498. // First connection uses original header
  14499. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14500. // Second connection uses updated header from set_headers
  14501. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14502. }
  14503. // Test: 401 allows reconnection (so on_error can refresh headers)
  14504. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14505. std::atomic<int> connection_count{0};
  14506. // Endpoint: returns 401 on first attempt, 200 on second
  14507. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14508. int conn = connection_count.fetch_add(1);
  14509. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14510. res.status = StatusCode::Unauthorized_401;
  14511. res.set_content("Unauthorized", "text/plain");
  14512. return;
  14513. }
  14514. res.set_chunked_content_provider(
  14515. "text/event-stream", [](size_t offset, DataSink &sink) {
  14516. if (offset == 0) {
  14517. std::string event = "data: authenticated\n\n";
  14518. sink.write(event.data(), event.size());
  14519. }
  14520. return false;
  14521. });
  14522. });
  14523. Client client("localhost", get_port());
  14524. Headers headers = {{"Authorization", "Bearer expired"}};
  14525. sse::SSEClient sse(client, "/auth-retry", headers);
  14526. std::atomic<bool> message_received{false};
  14527. // Refresh token on error
  14528. sse.on_error(
  14529. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14530. sse.on_message([&](const sse::SSEMessage &msg) {
  14531. if (msg.data == "authenticated") { message_received.store(true); }
  14532. });
  14533. sse.set_reconnect_interval(100);
  14534. sse.set_max_reconnect_attempts(3);
  14535. sse.start_async();
  14536. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14537. sse.stop();
  14538. // Should have reconnected after 401 and succeeded with new token
  14539. EXPECT_GE(connection_count.load(), 2);
  14540. EXPECT_TRUE(message_received.load());
  14541. }
  14542. TEST(Issue2318Test, EmptyHostString) {
  14543. {
  14544. httplib::Client cli_empty("", PORT);
  14545. auto res = cli_empty.Get("/");
  14546. ASSERT_FALSE(res);
  14547. EXPECT_EQ(httplib::Error::Connection, res.error());
  14548. }
  14549. {
  14550. httplib::Client cli(" ", PORT);
  14551. auto res = cli.Get("/");
  14552. ASSERT_FALSE(res);
  14553. EXPECT_EQ(httplib::Error::Connection, res.error());
  14554. }
  14555. }
  14556. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14557. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14558. Server svr;
  14559. // Set a small payload limit (1KB)
  14560. svr.set_payload_max_length(1024);
  14561. svr.Post("/test", [&](const Request &req, Response &res) {
  14562. res.set_content("Body size: " + std::to_string(req.body.size()),
  14563. "text/plain");
  14564. });
  14565. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14566. auto se = detail::scope_exit([&] {
  14567. svr.stop();
  14568. listen_thread.join();
  14569. });
  14570. svr.wait_until_ready();
  14571. // Create data that compresses well but exceeds limit when decompressed
  14572. // 8KB of repeated null bytes compresses to a very small size
  14573. std::string original_data(8 * 1024, '\0');
  14574. // Compress the data using gzip
  14575. std::string compressed_data;
  14576. detail::gzip_compressor compressor;
  14577. compressor.compress(original_data.data(), original_data.size(), true,
  14578. [&](const char *data, size_t size) {
  14579. compressed_data.append(data, size);
  14580. return true;
  14581. });
  14582. // Verify compression worked (compressed should be much smaller)
  14583. ASSERT_LT(compressed_data.size(), original_data.size());
  14584. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14585. // Send compressed data with Content-Encoding: gzip
  14586. Client cli(HOST, PORT);
  14587. Headers headers = {{"Content-Encoding", "gzip"}};
  14588. auto res =
  14589. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14590. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14591. ASSERT_TRUE(res);
  14592. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14593. }
  14594. #endif
  14595. // ============================================================================
  14596. // OpenSSL-Specific Tests
  14597. // ============================================================================
  14598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14599. X509 *readCertificate(const std::string &strFileName) {
  14600. std::ifstream inStream(strFileName);
  14601. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14602. std::istreambuf_iterator<char>());
  14603. if (strCertPEM.empty()) return (nullptr);
  14604. BIO *pbCert = BIO_new(BIO_s_mem());
  14605. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14606. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14607. BIO_free(pbCert);
  14608. return (pCert);
  14609. }
  14610. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14611. std::ifstream inStream(strFileName);
  14612. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14613. std::istreambuf_iterator<char>());
  14614. if (strPrivateKeyPEM.empty()) return (nullptr);
  14615. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14616. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14617. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14618. BIO_free(pbPrivKey);
  14619. return (pPrivateKey);
  14620. }
  14621. TEST(BindServerTest, UpdateCerts) {
  14622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14623. int port = svr.bind_to_any_port("0.0.0.0");
  14624. ASSERT_TRUE(svr.is_valid());
  14625. ASSERT_TRUE(port > 0);
  14626. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14627. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14628. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(cert != nullptr);
  14630. ASSERT_TRUE(ca_cert != nullptr);
  14631. ASSERT_TRUE(key != nullptr);
  14632. X509_STORE *cert_store = X509_STORE_new();
  14633. X509_STORE_add_cert(cert_store, ca_cert);
  14634. // svr.update_certs(cert, key, cert_store); // deprecated
  14635. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14636. CLIENT_CA_CERT_FILE);
  14637. ASSERT_TRUE(svr.is_valid());
  14638. svr.stop();
  14639. X509_STORE_free(cert_store);
  14640. X509_free(cert);
  14641. X509_free(ca_cert);
  14642. EVP_PKEY_free(key);
  14643. }
  14644. // Test that update_certs() updates client CA list correctly
  14645. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14646. // Start with file-based constructor
  14647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14648. ASSERT_TRUE(svr.is_valid());
  14649. // Initially no client CA list should be set
  14650. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14651. ASSERT_TRUE(ssl_ctx != nullptr);
  14652. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14653. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14654. EXPECT_EQ(0, count_before);
  14655. // Now update with client CA (PEM string)
  14656. std::string cert_pem, key_pem, ca_pem;
  14657. read_file(SERVER_CERT_FILE, cert_pem);
  14658. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14659. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14660. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14661. ASSERT_TRUE(svr.is_valid());
  14662. // Now client CA list should be set
  14663. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14664. ASSERT_TRUE(ca_list_after != nullptr);
  14665. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14666. }
  14667. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14668. // Test that the file-path SSLServer constructor properly sets the client CA
  14669. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14673. ASSERT_TRUE(ssl_ctx != nullptr);
  14674. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14675. ASSERT_TRUE(ca_list != nullptr);
  14676. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14677. }
  14678. #endif
  14679. // ============================================================================
  14680. // MbedTLS-Specific Tests
  14681. // ============================================================================
  14682. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14683. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14684. using namespace httplib::tls;
  14685. // Track if callback was invoked
  14686. bool callback_invoked = false;
  14687. // The callback receives void* ctx which is actually MbedTlsContext*
  14688. // We can access the mbedtls_ssl_config via the context
  14689. auto setup_callback = [&callback_invoked](void *ctx) {
  14690. callback_invoked = true;
  14691. // Cast to MbedTlsContext* to access the ssl config
  14692. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14693. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14694. // Use static variables to hold certificate data (simplified for test)
  14695. static mbedtls_x509_crt own_cert;
  14696. static mbedtls_pk_context own_key;
  14697. static mbedtls_x509_crt ca_chain;
  14698. static bool initialized = false;
  14699. if (!initialized) {
  14700. mbedtls_x509_crt_init(&own_cert);
  14701. mbedtls_pk_init(&own_key);
  14702. mbedtls_x509_crt_init(&ca_chain);
  14703. // Load server certificate
  14704. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14705. return false;
  14706. }
  14707. // Load server private key
  14708. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14709. #if MBEDTLS_VERSION_MAJOR >= 3
  14710. ,
  14711. mbedtls_ctr_drbg_random, nullptr
  14712. #endif
  14713. ) != 0) {
  14714. return false;
  14715. }
  14716. // Load CA chain for client verification
  14717. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14718. return false;
  14719. }
  14720. initialized = true;
  14721. }
  14722. // Configure the SSL config
  14723. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14724. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14725. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14726. // Set minimum TLS version using mbedTLS native API
  14727. #if MBEDTLS_VERSION_MAJOR >= 3
  14728. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14729. #else
  14730. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14731. MBEDTLS_SSL_MINOR_VERSION_3);
  14732. #endif
  14733. return true;
  14734. };
  14735. SSLServer svr(setup_callback);
  14736. ASSERT_TRUE(svr.is_valid());
  14737. ASSERT_TRUE(callback_invoked);
  14738. svr.Get("/test", [&](const Request &req, Response &res) {
  14739. res.set_content("test", "text/plain");
  14740. auto cert = req.peer_cert();
  14741. ASSERT_TRUE(static_cast<bool>(cert));
  14742. auto common_name = cert.subject_cn();
  14743. EXPECT_EQ("Common Name", common_name);
  14744. });
  14745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14746. auto se = detail::scope_exit([&] {
  14747. svr.stop();
  14748. t.join();
  14749. ASSERT_FALSE(svr.is_running());
  14750. });
  14751. svr.wait_until_ready();
  14752. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14753. cli.enable_server_certificate_verification(false);
  14754. cli.set_connection_timeout(30);
  14755. auto res = cli.Get("/test");
  14756. ASSERT_TRUE(res);
  14757. ASSERT_EQ(StatusCode::OK_200, res->status);
  14758. }
  14759. #endif
  14760. // WebSocket Tests
  14761. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14762. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14763. // defining the meaning of these bits has been negotiated.
  14764. auto make_frame = [](uint8_t first_byte) {
  14765. std::string frame;
  14766. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14767. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14768. frame += "Hello";
  14769. return frame;
  14770. };
  14771. // RSV1 set (0x40)
  14772. {
  14773. detail::BufferStream strm;
  14774. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14775. ws::Opcode opcode;
  14776. std::string payload;
  14777. bool fin;
  14778. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14779. false, 1024));
  14780. }
  14781. // RSV2 set (0x20)
  14782. {
  14783. detail::BufferStream strm;
  14784. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14785. ws::Opcode opcode;
  14786. std::string payload;
  14787. bool fin;
  14788. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14789. false, 1024));
  14790. }
  14791. // RSV3 set (0x10)
  14792. {
  14793. detail::BufferStream strm;
  14794. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14795. ws::Opcode opcode;
  14796. std::string payload;
  14797. bool fin;
  14798. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14799. false, 1024));
  14800. }
  14801. // No RSV bits set - should succeed
  14802. {
  14803. detail::BufferStream strm;
  14804. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14805. ws::Opcode opcode;
  14806. std::string payload;
  14807. bool fin;
  14808. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14809. false, 1024));
  14810. EXPECT_EQ(ws::Opcode::Text, opcode);
  14811. EXPECT_EQ("Hello", payload);
  14812. EXPECT_TRUE(fin);
  14813. }
  14814. }
  14815. TEST(WebSocketTest, ControlFrameValidation) {
  14816. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14817. // payload length <= 125.
  14818. // Ping with FIN=0 - must be rejected
  14819. {
  14820. detail::BufferStream strm;
  14821. std::string frame;
  14822. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14823. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14824. strm.write(frame.data(), frame.size());
  14825. ws::Opcode opcode;
  14826. std::string payload;
  14827. bool fin;
  14828. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14829. false, 1024));
  14830. }
  14831. // Close with FIN=0 - must be rejected
  14832. {
  14833. detail::BufferStream strm;
  14834. std::string frame;
  14835. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14836. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14837. strm.write(frame.data(), frame.size());
  14838. ws::Opcode opcode;
  14839. std::string payload;
  14840. bool fin;
  14841. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14842. false, 1024));
  14843. }
  14844. // Ping with payload_len=126 (extended length) - must be rejected
  14845. {
  14846. detail::BufferStream strm;
  14847. std::string frame;
  14848. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14849. frame += static_cast<char>(126); // payload_len=126 (>125)
  14850. frame += static_cast<char>(0x00); // extended length high byte
  14851. frame += static_cast<char>(126); // extended length low byte
  14852. frame += std::string(126, 'x');
  14853. strm.write(frame.data(), frame.size());
  14854. ws::Opcode opcode;
  14855. std::string payload;
  14856. bool fin;
  14857. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14858. false, 1024));
  14859. }
  14860. // Ping with FIN=1 and payload_len=125 - should succeed
  14861. {
  14862. detail::BufferStream strm;
  14863. std::string frame;
  14864. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14865. frame += static_cast<char>(125); // payload_len=125
  14866. frame += std::string(125, 'x');
  14867. strm.write(frame.data(), frame.size());
  14868. ws::Opcode opcode;
  14869. std::string payload;
  14870. bool fin;
  14871. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14872. false, 1024));
  14873. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14874. EXPECT_EQ(125u, payload.size());
  14875. EXPECT_TRUE(fin);
  14876. }
  14877. }
  14878. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14879. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14880. // length MUST be 0.
  14881. // MSB set - must be rejected
  14882. {
  14883. detail::BufferStream strm;
  14884. std::string frame;
  14885. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14886. frame += static_cast<char>(127); // 64-bit extended length
  14887. frame += static_cast<char>(0x80); // MSB set (invalid)
  14888. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14889. strm.write(frame.data(), frame.size());
  14890. ws::Opcode opcode;
  14891. std::string payload;
  14892. bool fin;
  14893. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14894. false, 1024));
  14895. }
  14896. // MSB clear - should pass length parsing (will be rejected by max_len,
  14897. // but that's a different check; use a small length to verify)
  14898. {
  14899. detail::BufferStream strm;
  14900. std::string frame;
  14901. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14902. frame += static_cast<char>(127); // 64-bit extended length
  14903. frame += std::string(7, '\0'); // high bytes = 0
  14904. frame += static_cast<char>(0x03); // length = 3
  14905. frame += "abc";
  14906. strm.write(frame.data(), frame.size());
  14907. ws::Opcode opcode;
  14908. std::string payload;
  14909. bool fin;
  14910. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14911. false, 1024));
  14912. EXPECT_EQ(ws::Opcode::Text, opcode);
  14913. EXPECT_EQ("abc", payload);
  14914. }
  14915. }
  14916. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14917. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14918. // Valid UTF-8
  14919. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14920. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14921. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14922. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14923. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14924. // Invalid UTF-8
  14925. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14926. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14927. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14928. EXPECT_FALSE(
  14929. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14930. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14931. }
  14932. TEST(WebSocketTest, ConnectAndDisconnect) {
  14933. Server svr;
  14934. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14935. std::string msg;
  14936. while (ws.read(msg)) {}
  14937. });
  14938. auto port = svr.bind_to_any_port(HOST);
  14939. std::thread t([&]() { svr.listen_after_bind(); });
  14940. svr.wait_until_ready();
  14941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14942. ASSERT_TRUE(client.connect());
  14943. EXPECT_TRUE(client.is_open());
  14944. client.close();
  14945. EXPECT_FALSE(client.is_open());
  14946. svr.stop();
  14947. t.join();
  14948. }
  14949. TEST(WebSocketTest, ValidURL) {
  14950. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14951. EXPECT_TRUE(ws1.is_valid());
  14952. ws::WebSocketClient ws2("ws://example.com/path");
  14953. EXPECT_TRUE(ws2.is_valid());
  14954. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14955. EXPECT_TRUE(ws3.is_valid());
  14956. #ifdef CPPHTTPLIB_SSL_ENABLED
  14957. ws::WebSocketClient wss1("wss://example.com/path");
  14958. EXPECT_TRUE(wss1.is_valid());
  14959. ws::WebSocketClient wss2("wss://example.com:443/path");
  14960. EXPECT_TRUE(wss2.is_valid());
  14961. #endif
  14962. }
  14963. TEST(WebSocketTest, InvalidURL) {
  14964. // No scheme
  14965. ws::WebSocketClient ws1("localhost:8080/path");
  14966. EXPECT_FALSE(ws1.is_valid());
  14967. // No path
  14968. ws::WebSocketClient ws2("ws://localhost:8080");
  14969. EXPECT_FALSE(ws2.is_valid());
  14970. // Empty string
  14971. ws::WebSocketClient ws3("");
  14972. EXPECT_FALSE(ws3.is_valid());
  14973. // Missing host
  14974. ws::WebSocketClient ws4("ws://:8080/path");
  14975. EXPECT_FALSE(ws4.is_valid());
  14976. // Port number overflow — should not crash
  14977. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14978. EXPECT_FALSE(ws5.is_valid());
  14979. // Port out of range
  14980. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14981. EXPECT_FALSE(ws6.is_valid());
  14982. }
  14983. TEST(WebSocketTest, UnsupportedScheme) {
  14984. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14985. ws::WebSocketClient ws1("http://localhost:8080/path");
  14986. EXPECT_FALSE(ws1.is_valid());
  14987. ws::WebSocketClient ws2("https://localhost:8080/path");
  14988. EXPECT_FALSE(ws2.is_valid());
  14989. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14990. EXPECT_FALSE(ws3.is_valid());
  14991. #else
  14992. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14993. std::invalid_argument);
  14994. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14995. std::invalid_argument);
  14996. #endif
  14997. }
  14998. TEST(WebSocketTest, ConnectWhenInvalid) {
  14999. ws::WebSocketClient ws("not a valid url");
  15000. EXPECT_FALSE(ws.is_valid());
  15001. EXPECT_FALSE(ws.connect());
  15002. }
  15003. TEST(WebSocketTest, DefaultPort) {
  15004. ws::WebSocketClient ws1("ws://example.com/path");
  15005. EXPECT_TRUE(ws1.is_valid());
  15006. // ws:// defaults to port 80 (verified by successful parse)
  15007. #ifdef CPPHTTPLIB_SSL_ENABLED
  15008. ws::WebSocketClient ws2("wss://example.com/path");
  15009. EXPECT_TRUE(ws2.is_valid());
  15010. // wss:// defaults to port 443 (verified by successful parse)
  15011. #endif
  15012. }
  15013. TEST(WebSocketTest, IPv6LiteralAddress) {
  15014. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15015. EXPECT_TRUE(ws1.is_valid());
  15016. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15017. EXPECT_TRUE(ws2.is_valid());
  15018. }
  15019. TEST(WebSocketTest, ComplexPath) {
  15020. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15021. EXPECT_TRUE(ws1.is_valid());
  15022. ws::WebSocketClient ws2("ws://localhost:8080/");
  15023. EXPECT_TRUE(ws2.is_valid());
  15024. }
  15025. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15026. Server svr;
  15027. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15028. std::string msg;
  15029. while (ws.read(msg)) {}
  15030. });
  15031. auto port = svr.bind_to_any_port(HOST);
  15032. std::thread t([&]() { svr.listen_after_bind(); });
  15033. svr.wait_until_ready();
  15034. auto another_host = "example.com";
  15035. auto wrong_ip = "192.0.2.1";
  15036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15037. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15038. ASSERT_TRUE(client.connect());
  15039. EXPECT_TRUE(client.is_open());
  15040. client.close();
  15041. svr.stop();
  15042. t.join();
  15043. }
  15044. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15045. Server svr;
  15046. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15047. std::string msg;
  15048. while (ws.read(msg)) {}
  15049. });
  15050. auto port = svr.bind_to_any_port(HOST);
  15051. std::thread t([&]() { svr.listen_after_bind(); });
  15052. svr.wait_until_ready();
  15053. auto wrong_ip = "192.0.2.1";
  15054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15055. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15056. client.set_connection_timeout(1);
  15057. client.set_read_timeout(1);
  15058. client.set_write_timeout(1);
  15059. EXPECT_FALSE(client.connect());
  15060. EXPECT_FALSE(client.is_open());
  15061. svr.stop();
  15062. t.join();
  15063. }
  15064. class WebSocketIntegrationTest : public ::testing::Test {
  15065. protected:
  15066. void SetUp() override {
  15067. server_ = httplib::detail::make_unique<Server>();
  15068. setup_server();
  15069. start_server();
  15070. }
  15071. void TearDown() override {
  15072. server_->stop();
  15073. if (server_thread_.joinable()) { server_thread_.join(); }
  15074. }
  15075. void setup_server() {
  15076. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15077. std::string msg;
  15078. ws::ReadResult ret;
  15079. while ((ret = ws.read(msg))) {
  15080. if (ret == ws::Binary) {
  15081. ws.send(msg.data(), msg.size());
  15082. } else {
  15083. ws.send(msg);
  15084. }
  15085. }
  15086. });
  15087. server_->WebSocket("/ws-echo-string",
  15088. [](const Request &, ws::WebSocket &ws) {
  15089. std::string msg;
  15090. while (ws.read(msg)) {
  15091. ws.send("echo: " + msg);
  15092. }
  15093. });
  15094. server_->WebSocket(
  15095. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15096. // Echo back request metadata
  15097. ws.send("path:" + req.path);
  15098. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15099. std::string msg;
  15100. while (ws.read(msg)) {}
  15101. });
  15102. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15103. std::string msg;
  15104. ws.read(msg); // wait for a message
  15105. ws.close();
  15106. });
  15107. server_->WebSocket("/ws-close-status",
  15108. [](const Request &, ws::WebSocket &ws) {
  15109. std::string msg;
  15110. ws.read(msg); // wait for a message
  15111. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15112. });
  15113. server_->WebSocket(
  15114. "/ws-subprotocol",
  15115. [](const Request &, ws::WebSocket &ws) {
  15116. std::string msg;
  15117. while (ws.read(msg)) {
  15118. ws.send(msg);
  15119. }
  15120. },
  15121. [](const std::vector<std::string> &protocols) -> std::string {
  15122. for (const auto &p : protocols) {
  15123. if (p == "graphql-ws") { return p; }
  15124. }
  15125. return "";
  15126. });
  15127. }
  15128. void start_server() {
  15129. port_ = server_->bind_to_any_port(HOST);
  15130. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15131. server_->wait_until_ready();
  15132. }
  15133. std::unique_ptr<Server> server_;
  15134. std::thread server_thread_;
  15135. int port_ = 0;
  15136. };
  15137. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15138. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15139. "/ws-echo");
  15140. ASSERT_TRUE(client.connect());
  15141. ASSERT_TRUE(client.is_open());
  15142. ASSERT_TRUE(client.send("Hello WebSocket"));
  15143. std::string msg;
  15144. EXPECT_EQ(ws::Text, client.read(msg));
  15145. EXPECT_EQ("Hello WebSocket", msg);
  15146. client.close();
  15147. }
  15148. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15150. "/ws-echo");
  15151. ASSERT_TRUE(client.connect());
  15152. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15153. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15154. std::string msg;
  15155. EXPECT_EQ(ws::Binary, client.read(msg));
  15156. EXPECT_EQ(binary_data, msg);
  15157. client.close();
  15158. }
  15159. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15161. "/ws-echo");
  15162. ASSERT_TRUE(client.connect());
  15163. for (int i = 0; i < 10; i++) {
  15164. auto text = "message " + std::to_string(i);
  15165. ASSERT_TRUE(client.send(text));
  15166. std::string msg;
  15167. ASSERT_TRUE(client.read(msg));
  15168. EXPECT_EQ(text, msg);
  15169. }
  15170. client.close();
  15171. }
  15172. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15174. "/ws-close");
  15175. ASSERT_TRUE(client.connect());
  15176. // Send a message to trigger the server to close
  15177. ASSERT_TRUE(client.send("trigger close"));
  15178. // The server will close, so read should return false
  15179. std::string msg;
  15180. EXPECT_FALSE(client.read(msg));
  15181. EXPECT_FALSE(client.is_open());
  15182. }
  15183. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15184. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15185. "/ws-echo");
  15186. ASSERT_TRUE(client.connect());
  15187. // 128KB message
  15188. std::string large_data(128 * 1024, 'X');
  15189. ASSERT_TRUE(client.send(large_data));
  15190. std::string msg;
  15191. ASSERT_TRUE(client.read(msg));
  15192. EXPECT_EQ(large_data, msg);
  15193. client.close();
  15194. }
  15195. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15197. "/ws-echo");
  15198. ASSERT_TRUE(client.connect());
  15199. const int num_threads = 4;
  15200. std::vector<std::thread> threads;
  15201. std::atomic<int> send_count{0};
  15202. for (int t = 0; t < num_threads; t++) {
  15203. threads.emplace_back([&client, &send_count, t]() {
  15204. for (int i = 0; i < 5; i++) {
  15205. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15206. if (client.send(text)) { send_count++; }
  15207. }
  15208. });
  15209. }
  15210. for (auto &th : threads) {
  15211. th.join();
  15212. }
  15213. int received = 0;
  15214. std::string msg;
  15215. while (received < send_count.load()) {
  15216. if (!client.read(msg)) { break; }
  15217. received++;
  15218. }
  15219. EXPECT_EQ(send_count.load(), received);
  15220. client.close();
  15221. }
  15222. TEST_F(WebSocketIntegrationTest, ReadString) {
  15223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15224. "/ws-echo-string");
  15225. ASSERT_TRUE(client.connect());
  15226. ASSERT_TRUE(client.send("hello"));
  15227. std::string msg;
  15228. ASSERT_TRUE(client.read(msg));
  15229. EXPECT_EQ("echo: hello", msg);
  15230. ASSERT_TRUE(client.send("world"));
  15231. ASSERT_TRUE(client.read(msg));
  15232. EXPECT_EQ("echo: world", msg);
  15233. client.close();
  15234. }
  15235. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15236. Headers headers = {{"X-Test-Header", "test-value"}};
  15237. ws::WebSocketClient client(
  15238. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15239. ASSERT_TRUE(client.connect());
  15240. std::string msg;
  15241. ASSERT_TRUE(client.read(msg));
  15242. EXPECT_EQ("path:/ws-request-info", msg);
  15243. ASSERT_TRUE(client.read(msg));
  15244. EXPECT_EQ("header:test-value", msg);
  15245. client.close();
  15246. }
  15247. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15248. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15249. "/ws-echo");
  15250. client.set_read_timeout(1, 0); // 1 second
  15251. ASSERT_TRUE(client.connect());
  15252. // Don't send anything — server echo handler waits for a message,
  15253. // so read() should time out and return false.
  15254. std::string msg;
  15255. EXPECT_FALSE(client.read(msg));
  15256. }
  15257. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15259. "/ws-echo");
  15260. client.set_read_timeout(5, 0);
  15261. ASSERT_TRUE(client.connect());
  15262. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15263. // The server should reject it and close the connection.
  15264. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15265. client.send(oversized);
  15266. // The server's read() should have failed due to payload limit,
  15267. // so our read() should return false (connection closed).
  15268. std::string msg;
  15269. EXPECT_FALSE(client.read(msg));
  15270. }
  15271. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15273. "/ws-echo");
  15274. client.set_read_timeout(10, 0);
  15275. ASSERT_TRUE(client.connect());
  15276. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15277. // This should succeed.
  15278. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15279. ASSERT_TRUE(client.send(at_limit));
  15280. std::string msg;
  15281. ASSERT_TRUE(client.read(msg));
  15282. EXPECT_EQ(at_limit.size(), msg.size());
  15283. client.close();
  15284. }
  15285. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15286. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15287. "/nonexistent");
  15288. EXPECT_FALSE(client.connect());
  15289. EXPECT_FALSE(client.is_open());
  15290. }
  15291. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15292. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15293. "/ws-echo");
  15294. ASSERT_TRUE(client.connect());
  15295. ASSERT_TRUE(client.send(""));
  15296. std::string msg;
  15297. EXPECT_EQ(ws::Text, client.read(msg));
  15298. EXPECT_EQ("", msg);
  15299. client.close();
  15300. }
  15301. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15303. "/ws-echo");
  15304. // First connection
  15305. ASSERT_TRUE(client.connect());
  15306. ASSERT_TRUE(client.send("first"));
  15307. std::string msg;
  15308. ASSERT_TRUE(client.read(msg));
  15309. EXPECT_EQ("first", msg);
  15310. client.close();
  15311. EXPECT_FALSE(client.is_open());
  15312. // Reconnect using the same client object
  15313. ASSERT_TRUE(client.connect());
  15314. ASSERT_TRUE(client.is_open());
  15315. ASSERT_TRUE(client.send("second"));
  15316. ASSERT_TRUE(client.read(msg));
  15317. EXPECT_EQ("second", msg);
  15318. client.close();
  15319. }
  15320. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15321. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15322. "/ws-close-status");
  15323. ASSERT_TRUE(client.connect());
  15324. // Trigger the server to close with GoingAway status
  15325. ASSERT_TRUE(client.send("trigger"));
  15326. // read() should return false after receiving the close frame
  15327. std::string msg;
  15328. EXPECT_FALSE(client.read(msg));
  15329. EXPECT_FALSE(client.is_open());
  15330. }
  15331. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15333. "/ws-echo");
  15334. ASSERT_TRUE(client.connect());
  15335. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15336. EXPECT_FALSE(client.is_open());
  15337. }
  15338. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15339. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15340. ws::WebSocketClient client(
  15341. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15342. ASSERT_TRUE(client.connect());
  15343. // Server should have selected graphql-ws
  15344. EXPECT_EQ("graphql-ws", client.subprotocol());
  15345. client.close();
  15346. }
  15347. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15348. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15349. ws::WebSocketClient client(
  15350. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15351. ASSERT_TRUE(client.connect());
  15352. // Server should not have selected any subprotocol
  15353. EXPECT_TRUE(client.subprotocol().empty());
  15354. client.close();
  15355. }
  15356. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15357. // Connect without requesting any subprotocol
  15358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15359. "/ws-subprotocol");
  15360. ASSERT_TRUE(client.connect());
  15361. EXPECT_TRUE(client.subprotocol().empty());
  15362. client.close();
  15363. }
  15364. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15366. "/ws-echo");
  15367. client.set_tcp_nodelay(true);
  15368. client.set_connection_timeout(3, 0);
  15369. bool socket_options_called = false;
  15370. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15371. ASSERT_TRUE(client.connect());
  15372. ASSERT_TRUE(client.is_open());
  15373. EXPECT_TRUE(socket_options_called);
  15374. ASSERT_TRUE(client.send("hello"));
  15375. std::string msg;
  15376. auto result = client.read(msg);
  15377. EXPECT_EQ(result, ws::ReadResult::Text);
  15378. EXPECT_EQ(msg, "hello");
  15379. client.close();
  15380. }
  15381. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15382. Server svr;
  15383. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15384. if (!req.has_header("Authorization")) {
  15385. res.status = StatusCode::Unauthorized_401;
  15386. res.set_content("Unauthorized", "text/plain");
  15387. return Server::HandlerResponse::Handled;
  15388. }
  15389. return Server::HandlerResponse::Unhandled;
  15390. });
  15391. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15392. std::string msg;
  15393. while (ws.read(msg)) {
  15394. ws.send(msg);
  15395. }
  15396. });
  15397. auto port = svr.bind_to_any_port("localhost");
  15398. std::thread t([&]() { svr.listen_after_bind(); });
  15399. svr.wait_until_ready();
  15400. // Without Authorization header - should be rejected before upgrade
  15401. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15402. EXPECT_FALSE(client1.connect());
  15403. // With Authorization header - should succeed
  15404. Headers headers = {{"Authorization", "Bearer token123"}};
  15405. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15406. headers);
  15407. ASSERT_TRUE(client2.connect());
  15408. ASSERT_TRUE(client2.send("hello"));
  15409. std::string msg;
  15410. ASSERT_TRUE(client2.read(msg));
  15411. EXPECT_EQ("hello", msg);
  15412. client2.close();
  15413. svr.stop();
  15414. t.join();
  15415. }
  15416. TEST(WebSocketTest, QueryStringInHandshake) {
  15417. Server svr;
  15418. std::mutex mtx;
  15419. std::string received_target;
  15420. std::string received_token;
  15421. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15422. {
  15423. std::lock_guard<std::mutex> lock(mtx);
  15424. received_target = req.target;
  15425. if (req.has_param("token")) {
  15426. received_token = req.get_param_value("token");
  15427. }
  15428. }
  15429. std::string msg;
  15430. while (ws.read(msg)) {
  15431. ws.send(msg);
  15432. }
  15433. });
  15434. auto port = svr.bind_to_any_port("localhost");
  15435. std::thread t([&]() { svr.listen_after_bind(); });
  15436. svr.wait_until_ready();
  15437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15438. "/ws?token=ABC&session=123");
  15439. ASSERT_TRUE(client.connect());
  15440. // Round-trip ensures the handler has run and captured the request.
  15441. ASSERT_TRUE(client.send("hello"));
  15442. std::string msg;
  15443. ASSERT_TRUE(client.read(msg));
  15444. EXPECT_EQ("hello", msg);
  15445. client.close();
  15446. {
  15447. std::lock_guard<std::mutex> lock(mtx);
  15448. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15449. EXPECT_EQ("ABC", received_token);
  15450. }
  15451. svr.stop();
  15452. t.join();
  15453. }
  15454. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15455. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15456. protected:
  15457. void SetUp() override {
  15458. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15459. SERVER_PRIVATE_KEY_FILE);
  15460. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15461. std::string msg;
  15462. ws::ReadResult ret;
  15463. while ((ret = ws.read(msg))) {
  15464. if (ret == ws::Binary) {
  15465. ws.send(msg.data(), msg.size());
  15466. } else {
  15467. ws.send(msg);
  15468. }
  15469. }
  15470. });
  15471. port_ = server_->bind_to_any_port(HOST);
  15472. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15473. server_->wait_until_ready();
  15474. }
  15475. void TearDown() override {
  15476. server_->stop();
  15477. if (server_thread_.joinable()) { server_thread_.join(); }
  15478. }
  15479. std::unique_ptr<SSLServer> server_;
  15480. std::thread server_thread_;
  15481. int port_ = 0;
  15482. };
  15483. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15484. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15485. "/ws-echo");
  15486. client.enable_server_certificate_verification(false);
  15487. ASSERT_TRUE(client.connect());
  15488. ASSERT_TRUE(client.is_open());
  15489. ASSERT_TRUE(client.send("Hello WSS"));
  15490. std::string msg;
  15491. EXPECT_EQ(ws::Text, client.read(msg));
  15492. EXPECT_EQ("Hello WSS", msg);
  15493. client.close();
  15494. }
  15495. #endif
  15496. #ifdef CPPHTTPLIB_SSL_ENABLED
  15497. class WebSocketSSLCATest : public ::testing::Test {
  15498. protected:
  15499. void SetUp() override {
  15500. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15501. SERVER_PRIVATE_KEY_FILE);
  15502. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15503. std::string msg;
  15504. while (ws.read(msg)) {
  15505. ws.send(msg);
  15506. }
  15507. });
  15508. port_ = server_->bind_to_any_port("127.0.0.1");
  15509. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15510. server_->wait_until_ready();
  15511. }
  15512. void TearDown() override {
  15513. server_->stop();
  15514. if (server_thread_.joinable()) { server_thread_.join(); }
  15515. }
  15516. std::string url() const {
  15517. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15518. }
  15519. std::unique_ptr<SSLServer> server_;
  15520. std::thread server_thread_;
  15521. int port_ = 0;
  15522. };
  15523. // A custom CA loaded as PEM verifies the server with full certificate
  15524. // verification enabled
  15525. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15526. ws::WebSocketClient client(url());
  15527. std::string cert;
  15528. read_file(SERVER_CERT2_FILE, cert);
  15529. client.load_ca_cert_store(cert.c_str(), cert.size());
  15530. ASSERT_TRUE(client.connect());
  15531. ASSERT_TRUE(client.send("hello"));
  15532. std::string msg;
  15533. EXPECT_EQ(ws::Text, client.read(msg));
  15534. EXPECT_EQ("hello", msg);
  15535. client.close();
  15536. }
  15537. // A custom CA that does not cover the server must fail verification (the
  15538. // custom CA is exclusive; system certs are not loaded alongside it)
  15539. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15540. ws::WebSocketClient client(url());
  15541. std::string cert;
  15542. read_file(CLIENT_CA_CERT_FILE, cert);
  15543. client.load_ca_cert_store(cert.c_str(), cert.size());
  15544. ASSERT_FALSE(client.connect());
  15545. }
  15546. // Regression test: reconnecting with a native custom CA store used to reuse
  15547. // a store handle the previous TLS context had already freed (use-after-free
  15548. // under the OpenSSL backend). The context now lives as long as the client.
  15549. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15550. ws::WebSocketClient client(url());
  15551. std::string cert;
  15552. read_file(SERVER_CERT2_FILE, cert);
  15553. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15554. ASSERT_TRUE(client.connect());
  15555. client.close();
  15556. ASSERT_TRUE(client.connect());
  15557. ASSERT_TRUE(client.send("again"));
  15558. std::string msg;
  15559. EXPECT_EQ(ws::Text, client.read(msg));
  15560. EXPECT_EQ("again", msg);
  15561. client.close();
  15562. }
  15563. // Regression test: a certificate with a trusted chain but no identity match
  15564. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15565. // verification entirely for IP hosts, so this connection succeeded there.
  15566. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15567. // chain verification while the identity check must still fail.
  15568. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15570. ASSERT_TRUE(svr.is_valid());
  15571. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15572. std::string msg;
  15573. while (ws.read(msg)) {
  15574. ws.send(msg);
  15575. }
  15576. });
  15577. auto port = svr.bind_to_any_port("127.0.0.1");
  15578. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15579. auto se = detail::scope_exit([&] {
  15580. svr.stop();
  15581. t.join();
  15582. });
  15583. svr.wait_until_ready();
  15584. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  15585. "/echo");
  15586. std::string cert;
  15587. read_file(SERVER_CERT_FILE, cert);
  15588. client.load_ca_cert_store(cert.c_str(), cert.size());
  15589. ASSERT_FALSE(client.connect());
  15590. }
  15591. #endif
  15592. #if !defined(_WIN32)
  15593. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15594. auto secret_dir = std::string("./symlink_test_secret");
  15595. auto served_dir = std::string("./symlink_test_served");
  15596. auto secret_file = secret_dir + "/secret.txt";
  15597. auto symlink_path = served_dir + "/escape";
  15598. // Setup: create directories and files
  15599. mkdir(secret_dir.c_str(), 0755);
  15600. mkdir(served_dir.c_str(), 0755);
  15601. {
  15602. std::ofstream ofs(secret_file);
  15603. ofs << "SECRET_DATA";
  15604. }
  15605. // Create symlink using absolute path so it resolves correctly
  15606. #ifdef PATH_MAX
  15607. char abs_secret[PATH_MAX];
  15608. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15609. #else
  15610. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15611. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15612. ASSERT_NE(nullptr, abs_secret);
  15613. #endif
  15614. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15615. auto se = detail::scope_exit([&] {
  15616. unlink(symlink_path.c_str());
  15617. unlink(secret_file.c_str());
  15618. rmdir(served_dir.c_str());
  15619. rmdir(secret_dir.c_str());
  15620. });
  15621. Server svr;
  15622. svr.set_mount_point("/", served_dir);
  15623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15624. auto se2 = detail::scope_exit([&] {
  15625. svr.stop();
  15626. listen_thread.join();
  15627. });
  15628. svr.wait_until_ready();
  15629. Client cli("localhost", PORT);
  15630. // Symlink pointing outside base dir should be blocked
  15631. auto res = cli.Get("/escape/secret.txt");
  15632. ASSERT_TRUE(res);
  15633. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15634. }
  15635. #endif
  15636. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15637. // A GET request with Content-Length to a static file handler must have its
  15638. // body drained before the keep-alive connection is reused. Otherwise the
  15639. // unread body bytes are interpreted as the next HTTP request.
  15640. //
  15641. // The body is sent AFTER receiving the first response (as in the original
  15642. // PoC) so that the stream_line_reader cannot buffer it together with the
  15643. // headers of the first request.
  15644. Server svr;
  15645. svr.set_mount_point("/", "./www");
  15646. std::atomic<int> smuggled_count(0);
  15647. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15648. smuggled_count++;
  15649. res.set_content("oops", "text/plain");
  15650. });
  15651. auto port = svr.bind_to_any_port("localhost");
  15652. thread t = thread([&] { svr.listen_after_bind(); });
  15653. auto se = detail::scope_exit([&] {
  15654. svr.stop();
  15655. t.join();
  15656. });
  15657. svr.wait_until_ready();
  15658. auto error = Error::Success;
  15659. auto sock = detail::create_client_socket(
  15660. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15661. /*connection_timeout_sec=*/2, 0,
  15662. /*read_timeout_sec=*/2, 0,
  15663. /*write_timeout_sec=*/2, 0, std::string(), error);
  15664. ASSERT_NE(INVALID_SOCKET, sock);
  15665. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15666. // The "smuggled" request will be sent as the body of the outer GET
  15667. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15668. "Host: localhost\r\n"
  15669. "Connection: close\r\n"
  15670. "\r\n";
  15671. // Step 1: Send only the outer request headers (no body yet)
  15672. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15673. "Host: localhost\r\n"
  15674. "Content-Length: " +
  15675. std::to_string(smuggled.size()) +
  15676. "\r\n"
  15677. "\r\n";
  15678. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15679. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15680. // Step 2: Read the first response (server serves file without reading body)
  15681. std::string first_response;
  15682. char buf[4096];
  15683. for (;;) {
  15684. auto n = recv(sock, buf, sizeof(buf), 0);
  15685. if (n <= 0) break;
  15686. first_response.append(buf, static_cast<size_t>(n));
  15687. // Stop once we have a complete response (headers + body)
  15688. auto hdr_end = first_response.find("\r\n\r\n");
  15689. if (hdr_end != std::string::npos) {
  15690. // Check for Content-Length to know when the body is complete
  15691. auto cl_pos = first_response.find("Content-Length:");
  15692. if (cl_pos != std::string::npos) {
  15693. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15694. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15695. auto cl = std::stoul(
  15696. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15697. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15698. } else {
  15699. break; // No Content-Length, assume headers-only response
  15700. }
  15701. }
  15702. }
  15703. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15704. // Step 3: Now send the body, which looks like a new HTTP request.
  15705. // On a vulnerable server the keep-alive loop reads this as a second request.
  15706. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15707. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15708. // Step 4: Try to read a second response (should NOT exist after fix)
  15709. std::string second_response;
  15710. for (;;) {
  15711. auto n = recv(sock, buf, sizeof(buf), 0);
  15712. if (n <= 0) break;
  15713. second_response.append(buf, static_cast<size_t>(n));
  15714. }
  15715. // The smuggled request must NOT have been processed
  15716. EXPECT_EQ(0, smuggled_count.load());
  15717. }
  15718. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15719. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15720. // must be rejected with 400 Bad Request.
  15721. Server svr;
  15722. svr.Post("/test", [&](const Request &, Response &res) {
  15723. res.set_content("ok", "text/plain");
  15724. });
  15725. thread t = thread([&] { svr.listen(HOST, PORT); });
  15726. auto se = detail::scope_exit([&] {
  15727. svr.stop();
  15728. t.join();
  15729. ASSERT_FALSE(svr.is_running());
  15730. });
  15731. svr.wait_until_ready();
  15732. // Exact "chunked"
  15733. {
  15734. auto req = "POST /test HTTP/1.1\r\n"
  15735. "Host: localhost\r\n"
  15736. "Content-Length: 5\r\n"
  15737. "Transfer-Encoding: chunked\r\n"
  15738. "Connection: close\r\n"
  15739. "\r\n"
  15740. "hello";
  15741. std::string response;
  15742. ASSERT_TRUE(send_request(1, req, &response));
  15743. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15744. response.substr(0, response.find("\r\n")));
  15745. }
  15746. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15747. {
  15748. auto req = "POST /test HTTP/1.1\r\n"
  15749. "Host: localhost\r\n"
  15750. "Content-Length: 5\r\n"
  15751. "Transfer-Encoding: gzip, chunked\r\n"
  15752. "Connection: close\r\n"
  15753. "\r\n"
  15754. "hello";
  15755. std::string response;
  15756. ASSERT_TRUE(send_request(1, req, &response));
  15757. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15758. response.substr(0, response.find("\r\n")));
  15759. }
  15760. }
  15761. // Regression for issue #2450: a DELETE without Content-Length on a
  15762. // keep-alive connection must not let the post-response drain consume the
  15763. // next request's bytes.
  15764. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15765. Server svr;
  15766. std::atomic<int> delete_count(0);
  15767. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15768. delete_count++;
  15769. res.status = StatusCode::NoContent_204;
  15770. });
  15771. auto port = svr.bind_to_any_port(HOST);
  15772. thread t = thread([&] { svr.listen_after_bind(); });
  15773. auto se = detail::scope_exit([&] {
  15774. svr.stop();
  15775. t.join();
  15776. });
  15777. svr.wait_until_ready();
  15778. auto error = Error::Success;
  15779. auto sock = detail::create_client_socket(
  15780. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15781. /*connection_timeout_sec=*/2, 0,
  15782. /*read_timeout_sec=*/2, 0,
  15783. /*write_timeout_sec=*/2, 0, std::string(), error);
  15784. ASSERT_NE(INVALID_SOCKET, sock);
  15785. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15786. auto send_request_and_read_response = [&](const std::string &req,
  15787. std::string &out) -> bool {
  15788. auto sent = send(sock, req.data(), req.size(), 0);
  15789. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15790. char buf[4096];
  15791. for (;;) {
  15792. auto n = recv(sock, buf, sizeof(buf), 0);
  15793. if (n <= 0) { return !out.empty(); }
  15794. out.append(buf, static_cast<size_t>(n));
  15795. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15796. }
  15797. };
  15798. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15799. "Host: localhost\r\n"
  15800. "\r\n";
  15801. std::string resp1;
  15802. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15803. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15804. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15805. "Host: localhost\r\n"
  15806. "Connection: close\r\n"
  15807. "\r\n";
  15808. std::string resp2;
  15809. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15810. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15811. EXPECT_EQ(2, delete_count.load());
  15812. }
  15813. namespace no_proxy_test {
  15814. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15815. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15816. // calling listen().
  15817. class ScopedServer {
  15818. public:
  15819. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15820. ~ScopedServer() {
  15821. svr_.stop();
  15822. if (th_.joinable()) { th_.join(); }
  15823. }
  15824. Server &svr() { return svr_; }
  15825. int port() const { return port_; }
  15826. void listen() {
  15827. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15828. svr_.wait_until_ready();
  15829. }
  15830. private:
  15831. Server svr_;
  15832. std::thread th_;
  15833. int port_ = 0;
  15834. };
  15835. class ProxyAndTargetServers {
  15836. public:
  15837. ProxyAndTargetServers() {
  15838. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15839. proxy_hits_++;
  15840. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15841. res.set_content("via-proxy", "text/plain");
  15842. });
  15843. target_.Get(".*", [this](const Request &req, Response &res) {
  15844. target_hits_++;
  15845. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15846. res.set_content("direct", "text/plain");
  15847. });
  15848. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15849. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15850. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15851. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15852. proxy_mock_.wait_until_ready();
  15853. target_.wait_until_ready();
  15854. }
  15855. ~ProxyAndTargetServers() {
  15856. proxy_mock_.stop();
  15857. target_.stop();
  15858. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15859. if (target_thread_.joinable()) { target_thread_.join(); }
  15860. }
  15861. Server &proxy_mock() { return proxy_mock_; }
  15862. Server &target() { return target_; }
  15863. int proxy_port() const { return proxy_port_; }
  15864. int target_port() const { return target_port_; }
  15865. int proxy_hits() const { return proxy_hits_.load(); }
  15866. int target_hits() const { return target_hits_.load(); }
  15867. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15868. void reset_counters() {
  15869. proxy_hits_ = 0;
  15870. target_hits_ = 0;
  15871. last_had_proxy_authz_ = false;
  15872. }
  15873. private:
  15874. Server proxy_mock_;
  15875. Server target_;
  15876. std::thread proxy_thread_;
  15877. std::thread target_thread_;
  15878. int proxy_port_ = 0;
  15879. int target_port_ = 0;
  15880. std::atomic<int> proxy_hits_{0};
  15881. std::atomic<int> target_hits_{0};
  15882. std::atomic<bool> last_had_proxy_authz_{false};
  15883. };
  15884. inline std::unique_ptr<Client> make_client(const std::string &host,
  15885. ProxyAndTargetServers &s) {
  15886. auto cli = detail::make_unique<Client>(host, s.target_port());
  15887. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15888. cli->set_proxy("127.0.0.1", s.proxy_port());
  15889. return cli;
  15890. }
  15891. } // namespace no_proxy_test
  15892. using no_proxy_test::make_client;
  15893. using no_proxy_test::ProxyAndTargetServers;
  15894. TEST(NoProxyTest, ExactHostnameBypasses) {
  15895. ProxyAndTargetServers s;
  15896. auto cli = make_client("example.com", s);
  15897. cli->set_no_proxy({"example.com"});
  15898. auto res = cli->Get("/");
  15899. ASSERT_TRUE(res);
  15900. EXPECT_EQ(0, s.proxy_hits());
  15901. EXPECT_EQ(1, s.target_hits());
  15902. }
  15903. TEST(NoProxyTest, SubdomainBypasses) {
  15904. ProxyAndTargetServers s;
  15905. auto cli = make_client("foo.example.com", s);
  15906. cli->set_no_proxy({"example.com"});
  15907. auto res = cli->Get("/");
  15908. ASSERT_TRUE(res);
  15909. EXPECT_EQ(0, s.proxy_hits());
  15910. EXPECT_EQ(1, s.target_hits());
  15911. }
  15912. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15913. // Regression guard: "evilexample.com" must not be considered a subdomain
  15914. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15915. // check would let traffic bypass the proxy and leak credentials direct
  15916. // to the attacker host.
  15917. ProxyAndTargetServers s;
  15918. auto cli = make_client("evilexample.com", s);
  15919. cli->set_no_proxy({"example.com"});
  15920. auto res = cli->Get("/");
  15921. ASSERT_TRUE(res);
  15922. EXPECT_GE(s.proxy_hits(), 1);
  15923. EXPECT_EQ(0, s.target_hits());
  15924. }
  15925. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15926. ProxyAndTargetServers s;
  15927. auto cli = make_client("example.com.evil.com", s);
  15928. cli->set_no_proxy({"example.com"});
  15929. auto res = cli->Get("/");
  15930. ASSERT_TRUE(res);
  15931. EXPECT_GE(s.proxy_hits(), 1);
  15932. EXPECT_EQ(0, s.target_hits());
  15933. }
  15934. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15935. ProxyAndTargetServers s;
  15936. auto cli = make_client("example.com", s);
  15937. cli->set_no_proxy({".example.com"});
  15938. auto res = cli->Get("/");
  15939. ASSERT_TRUE(res);
  15940. EXPECT_EQ(0, s.proxy_hits());
  15941. EXPECT_EQ(1, s.target_hits());
  15942. }
  15943. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15944. ProxyAndTargetServers s;
  15945. auto cli = make_client("Example.COM", s);
  15946. cli->set_no_proxy({"EXAMPLE.com"});
  15947. auto res = cli->Get("/");
  15948. ASSERT_TRUE(res);
  15949. EXPECT_EQ(0, s.proxy_hits());
  15950. EXPECT_EQ(1, s.target_hits());
  15951. }
  15952. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15953. ProxyAndTargetServers s;
  15954. auto cli = make_client("example.com.", s);
  15955. cli->set_no_proxy({"example.com"});
  15956. auto res = cli->Get("/");
  15957. ASSERT_TRUE(res);
  15958. EXPECT_EQ(0, s.proxy_hits());
  15959. EXPECT_EQ(1, s.target_hits());
  15960. }
  15961. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15962. // Trailing dots must be normalized on BOTH sides — host and entry.
  15963. // An implementation that only strips the host-side trailing dot would
  15964. // fail to match host "example.com" against entry "example.com." because
  15965. // a literal substring search would compare 11 chars against 12.
  15966. ProxyAndTargetServers s;
  15967. auto cli = make_client("example.com", s);
  15968. cli->set_no_proxy({"example.com."});
  15969. auto res = cli->Get("/");
  15970. ASSERT_TRUE(res);
  15971. EXPECT_EQ(0, s.proxy_hits());
  15972. EXPECT_EQ(1, s.target_hits());
  15973. }
  15974. TEST(NoProxyTest, WildcardBypassesEverything) {
  15975. ProxyAndTargetServers s;
  15976. auto cli = make_client("anything.invalid.test", s);
  15977. cli->set_no_proxy({"*"});
  15978. auto res = cli->Get("/");
  15979. ASSERT_TRUE(res);
  15980. EXPECT_EQ(0, s.proxy_hits());
  15981. EXPECT_EQ(1, s.target_hits());
  15982. }
  15983. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15984. ProxyAndTargetServers s;
  15985. Client cli("127.0.0.1", s.target_port());
  15986. cli.set_proxy("127.0.0.1", s.proxy_port());
  15987. cli.set_no_proxy({"127.0.0.1"});
  15988. auto res = cli.Get("/");
  15989. ASSERT_TRUE(res);
  15990. EXPECT_EQ(0, s.proxy_hits());
  15991. EXPECT_EQ(1, s.target_hits());
  15992. }
  15993. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  15994. ProxyAndTargetServers s;
  15995. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  15996. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  15997. cli.set_proxy("127.0.0.1", s.proxy_port());
  15998. cli.set_no_proxy({"::1"});
  15999. auto res = cli.Get("/");
  16000. ASSERT_TRUE(res);
  16001. EXPECT_EQ(0, s.proxy_hits());
  16002. EXPECT_EQ(1, s.target_hits());
  16003. }
  16004. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16005. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16006. // must still be recognized as IPv6 for CIDR matching. Implementations
  16007. // that detect IPv6 only when the host begins with '[' would parse the
  16008. // host as a hostname and miss the match.
  16009. ProxyAndTargetServers s;
  16010. Client cli("fe80::1", s.target_port());
  16011. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16012. cli.set_proxy("127.0.0.1", s.proxy_port());
  16013. cli.set_no_proxy({"fe80::/10"});
  16014. auto res = cli.Get("/");
  16015. ASSERT_TRUE(res);
  16016. EXPECT_EQ(0, s.proxy_hits());
  16017. EXPECT_EQ(1, s.target_hits());
  16018. }
  16019. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16020. ProxyAndTargetServers s;
  16021. Client cli("::1", s.target_port());
  16022. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16023. cli.set_proxy("127.0.0.1", s.proxy_port());
  16024. cli.set_no_proxy({"[::1]"});
  16025. auto res = cli.Get("/");
  16026. ASSERT_TRUE(res);
  16027. EXPECT_EQ(0, s.proxy_hits());
  16028. EXPECT_EQ(1, s.target_hits());
  16029. }
  16030. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16031. ProxyAndTargetServers s;
  16032. Client cli("fe80::1", s.target_port());
  16033. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16034. cli.set_proxy("127.0.0.1", s.proxy_port());
  16035. cli.set_no_proxy({"[fe80::]/10"});
  16036. auto res = cli.Get("/");
  16037. ASSERT_TRUE(res);
  16038. EXPECT_EQ(0, s.proxy_hits());
  16039. EXPECT_EQ(1, s.target_hits());
  16040. }
  16041. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16042. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16043. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16044. // tricks via address-family conversion.
  16045. ProxyAndTargetServers s;
  16046. Client cli("::ffff:127.0.0.1", s.target_port());
  16047. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16048. cli.set_proxy("127.0.0.1", s.proxy_port());
  16049. cli.set_no_proxy({"127.0.0.1"});
  16050. auto res = cli.Get("/");
  16051. ASSERT_TRUE(res);
  16052. EXPECT_GE(s.proxy_hits(), 1);
  16053. EXPECT_EQ(0, s.target_hits());
  16054. }
  16055. TEST(NoProxyTest, IPv4CidrMatch) {
  16056. ProxyAndTargetServers s;
  16057. Client cli("127.0.0.1", s.target_port());
  16058. cli.set_proxy("127.0.0.1", s.proxy_port());
  16059. cli.set_no_proxy({"127.0.0.0/8"});
  16060. auto res = cli.Get("/");
  16061. ASSERT_TRUE(res);
  16062. EXPECT_EQ(0, s.proxy_hits());
  16063. EXPECT_EQ(1, s.target_hits());
  16064. }
  16065. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16066. ProxyAndTargetServers s;
  16067. Client cli("127.0.0.1", s.target_port());
  16068. cli.set_proxy("127.0.0.1", s.proxy_port());
  16069. cli.set_no_proxy({"10.0.0.0/8"});
  16070. auto res = cli.Get("/");
  16071. ASSERT_TRUE(res);
  16072. EXPECT_GE(s.proxy_hits(), 1);
  16073. EXPECT_EQ(0, s.target_hits());
  16074. }
  16075. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16076. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16077. // IPv4 target matches.
  16078. ProxyAndTargetServers s;
  16079. Client cli("127.0.0.1", s.target_port());
  16080. cli.set_proxy("127.0.0.1", s.proxy_port());
  16081. cli.set_no_proxy({"0.0.0.0/0"});
  16082. auto res = cli.Get("/");
  16083. ASSERT_TRUE(res);
  16084. EXPECT_EQ(0, s.proxy_hits());
  16085. EXPECT_EQ(1, s.target_hits());
  16086. }
  16087. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16088. ProxyAndTargetServers s;
  16089. Client cli("127.0.0.1", s.target_port());
  16090. cli.set_proxy("127.0.0.1", s.proxy_port());
  16091. cli.set_no_proxy({"127.0.0.1"});
  16092. auto res = cli.Get("/");
  16093. ASSERT_TRUE(res);
  16094. EXPECT_EQ(0, s.proxy_hits());
  16095. EXPECT_EQ(1, s.target_hits());
  16096. }
  16097. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16098. ProxyAndTargetServers s;
  16099. Client cli("127.0.0.1", s.target_port());
  16100. cli.set_proxy("127.0.0.1", s.proxy_port());
  16101. cli.set_no_proxy({"127.0.0.0/33"});
  16102. auto res = cli.Get("/");
  16103. ASSERT_TRUE(res);
  16104. EXPECT_GE(s.proxy_hits(), 1);
  16105. EXPECT_EQ(0, s.target_hits());
  16106. }
  16107. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16108. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16109. ProxyAndTargetServers s;
  16110. Client cli("127.0.0.1", s.target_port());
  16111. cli.set_proxy("127.0.0.1", s.proxy_port());
  16112. cli.set_no_proxy({"127.0.0.1/"});
  16113. auto res = cli.Get("/");
  16114. ASSERT_TRUE(res);
  16115. EXPECT_GE(s.proxy_hits(), 1);
  16116. EXPECT_EQ(0, s.target_hits());
  16117. }
  16118. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16119. ProxyAndTargetServers s;
  16120. auto cli = make_client("internal.corp", s);
  16121. cli->set_proxy_basic_auth("u", "p");
  16122. cli->set_no_proxy({"internal.corp"});
  16123. auto res = cli->Get("/");
  16124. ASSERT_TRUE(res);
  16125. EXPECT_EQ(1, s.target_hits());
  16126. EXPECT_EQ(0, s.proxy_hits());
  16127. EXPECT_FALSE(s.last_had_proxy_authz())
  16128. << "Proxy-Authorization must not be sent direct to the target";
  16129. }
  16130. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16131. ProxyAndTargetServers s;
  16132. auto cli = make_client("public.example", s);
  16133. cli->set_proxy_basic_auth("u", "p");
  16134. cli->set_no_proxy({"internal.corp"}); // does not match
  16135. auto res = cli->Get("/");
  16136. ASSERT_TRUE(res);
  16137. EXPECT_GE(s.proxy_hits(), 1);
  16138. EXPECT_TRUE(s.last_had_proxy_authz());
  16139. }
  16140. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16141. ProxyAndTargetServers s;
  16142. auto cli = make_client("anything.test", s);
  16143. auto res = cli->Get("/");
  16144. ASSERT_TRUE(res);
  16145. EXPECT_GE(s.proxy_hits(), 1);
  16146. EXPECT_EQ(0, s.target_hits());
  16147. }
  16148. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16149. ProxyAndTargetServers s;
  16150. auto cli = make_client("example.com", s);
  16151. cli->set_no_proxy({"example.com:8080"});
  16152. auto res = cli->Get("/");
  16153. ASSERT_TRUE(res);
  16154. EXPECT_GE(s.proxy_hits(), 1);
  16155. EXPECT_EQ(0, s.target_hits());
  16156. }
  16157. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16158. ProxyAndTargetServers s;
  16159. auto cli = make_client("anything.test", s);
  16160. cli->set_no_proxy({"", " ", "\t"});
  16161. auto res = cli->Get("/");
  16162. ASSERT_TRUE(res);
  16163. EXPECT_GE(s.proxy_hits(), 1);
  16164. EXPECT_EQ(0, s.target_hits());
  16165. }
  16166. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16167. // An entry with leading/trailing whitespace must still match — env-style
  16168. // values are commonly pasted with stray spaces and an implementation
  16169. // that feeds the raw token directly to inet_pton would fail to match
  16170. // valid CIDRs because of the spaces.
  16171. ProxyAndTargetServers s;
  16172. Client cli("127.0.0.1", s.target_port());
  16173. cli.set_proxy("127.0.0.1", s.proxy_port());
  16174. cli.set_no_proxy({" 127.0.0.0/8 "});
  16175. auto res = cli.Get("/");
  16176. ASSERT_TRUE(res);
  16177. EXPECT_EQ(0, s.proxy_hits());
  16178. EXPECT_EQ(1, s.target_hits());
  16179. }
  16180. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16181. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16182. // go direct and must NOT carry Proxy-Authorization.
  16183. std::atomic<int> proxy_hits{0};
  16184. std::atomic<int> target_hits{0};
  16185. std::atomic<bool> target_saw_authz{false};
  16186. no_proxy_test::ScopedServer proxy_mock, target;
  16187. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16188. proxy_hits++;
  16189. res.status = 302;
  16190. res.set_header("Location", "http://127.0.0.1:" +
  16191. std::to_string(target.port()) + "/landed");
  16192. });
  16193. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16194. target_hits++;
  16195. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16196. res.set_content("direct", "text/plain");
  16197. });
  16198. proxy_mock.listen();
  16199. target.listen();
  16200. Client cli("public.example", target.port());
  16201. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16202. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16203. cli.set_proxy_basic_auth("u", "p");
  16204. cli.set_no_proxy({"127.0.0.1"});
  16205. cli.set_follow_location(true);
  16206. auto res = cli.Get("/redir");
  16207. ASSERT_TRUE(res);
  16208. EXPECT_GE(proxy_hits.load(), 1);
  16209. EXPECT_GE(target_hits.load(), 1);
  16210. EXPECT_FALSE(target_saw_authz.load());
  16211. }
  16212. #ifdef CPPHTTPLIB_SSL_ENABLED
  16213. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16214. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16215. // proxy creds would be sent to the (possibly hostile) origin.
  16216. std::atomic<int> target_hits{0};
  16217. std::atomic<bool> target_saw_proxy_authz{false};
  16218. no_proxy_test::ScopedServer target;
  16219. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16220. target_hits++;
  16221. if (req.has_header("Proxy-Authorization")) {
  16222. target_saw_proxy_authz = true;
  16223. }
  16224. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16225. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16226. "nonce=\"abc\", algorithm=MD5");
  16227. });
  16228. target.listen();
  16229. // The proxy address is set to the target's port: the bypass MUST kick in;
  16230. // if it doesn't, the test still routes "via proxy" to the same server and
  16231. // the Proxy-Authorization assertion below catches the leak.
  16232. Client cli("evil.example", target.port());
  16233. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16234. cli.set_proxy("127.0.0.1", target.port());
  16235. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16236. cli.set_no_proxy({"evil.example"});
  16237. auto res = cli.Get("/x");
  16238. ASSERT_TRUE(res);
  16239. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16240. EXPECT_EQ(1, target_hits.load());
  16241. EXPECT_FALSE(target_saw_proxy_authz.load());
  16242. }
  16243. #endif
  16244. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16245. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16246. std::atomic<int> proxy_hits{0};
  16247. std::atomic<int> bypass_hits{0};
  16248. std::atomic<bool> proxy_saw_c_url{false};
  16249. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16250. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16251. proxy_hits++;
  16252. if (req.path.find("/start") != std::string::npos) {
  16253. res.status = 302;
  16254. res.set_header("Location", "http://127.0.0.1:" +
  16255. std::to_string(bypass_server.port()) +
  16256. "/middle");
  16257. return;
  16258. }
  16259. if (req.path.find("/end") != std::string::npos) {
  16260. proxy_saw_c_url = true;
  16261. res.set_content("c-via-proxy", "text/plain");
  16262. return;
  16263. }
  16264. res.set_content("unexpected", "text/plain");
  16265. });
  16266. // public.example's "advertised" port is arbitrary (the request never lands
  16267. // there — it goes through the proxy), but use a dynamic value to stay
  16268. // friendly with sharded parallel runs.
  16269. int public_port = bypass_server.port();
  16270. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16271. bypass_hits++;
  16272. res.status = 302;
  16273. res.set_header("Location", "http://public.example:" +
  16274. std::to_string(public_port) + "/end");
  16275. });
  16276. proxy_mock.listen();
  16277. bypass_server.listen();
  16278. Client cli("public.example", public_port);
  16279. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16280. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16281. cli.set_no_proxy({"127.0.0.1"});
  16282. cli.set_follow_location(true);
  16283. auto res = cli.Get("/start");
  16284. ASSERT_TRUE(res);
  16285. EXPECT_EQ(StatusCode::OK_200, res->status);
  16286. EXPECT_EQ("c-via-proxy", res->body);
  16287. EXPECT_GE(proxy_hits.load(), 2);
  16288. EXPECT_GE(bypass_hits.load(), 1);
  16289. EXPECT_TRUE(proxy_saw_c_url.load());
  16290. }
  16291. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16292. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16293. // request reconnects to the correct endpoint.
  16294. std::atomic<int> proxy_hits{0};
  16295. std::atomic<int> target_hits{0};
  16296. no_proxy_test::ScopedServer proxy_mock, target;
  16297. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16298. proxy_hits++;
  16299. res.set_content("via-proxy", "text/plain");
  16300. });
  16301. target.svr().Get(".*", [&](const Request &, Response &res) {
  16302. target_hits++;
  16303. res.set_content("direct", "text/plain");
  16304. });
  16305. proxy_mock.listen();
  16306. target.listen();
  16307. Client cli("public.example", target.port());
  16308. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16309. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16310. cli.set_keep_alive(true);
  16311. auto res1 = cli.Get("/a");
  16312. ASSERT_TRUE(res1);
  16313. EXPECT_EQ("via-proxy", res1->body);
  16314. EXPECT_EQ(1, proxy_hits.load());
  16315. EXPECT_EQ(0, target_hits.load());
  16316. cli.set_no_proxy({"public.example"});
  16317. auto res2 = cli.Get("/b");
  16318. ASSERT_TRUE(res2);
  16319. EXPECT_EQ("direct", res2->body);
  16320. EXPECT_EQ(1, proxy_hits.load());
  16321. EXPECT_EQ(1, target_hits.load());
  16322. }
  16323. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16324. namespace proxy_tunnel_test {
  16325. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16326. class ScopedSSLServer {
  16327. public:
  16328. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16329. port_ = svr_.bind_to_any_port("127.0.0.1");
  16330. }
  16331. ~ScopedSSLServer() {
  16332. svr_.stop();
  16333. if (th_.joinable()) { th_.join(); }
  16334. }
  16335. SSLServer &svr() { return svr_; }
  16336. int port() const { return port_; }
  16337. void listen() {
  16338. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16339. svr_.wait_until_ready();
  16340. }
  16341. private:
  16342. SSLServer svr_;
  16343. std::thread th_;
  16344. int port_ = 0;
  16345. };
  16346. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16347. class ScopedConnectProxy {
  16348. public:
  16349. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16350. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16351. if (listen_fd_ < 0) { return; }
  16352. int yes = 1;
  16353. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16354. sockaddr_in a{};
  16355. a.sin_family = AF_INET;
  16356. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16357. a.sin_port = 0;
  16358. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16359. return;
  16360. }
  16361. socklen_t alen = sizeof(a);
  16362. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16363. 0) {
  16364. return;
  16365. }
  16366. port_ = ntohs(a.sin_port);
  16367. if (::listen(listen_fd_, 1) != 0) { return; }
  16368. th_ = std::thread([this] { run(); });
  16369. }
  16370. ~ScopedConnectProxy() {
  16371. stop_ = true;
  16372. if (listen_fd_ >= 0) {
  16373. ::shutdown(listen_fd_, SHUT_RDWR);
  16374. ::close(listen_fd_);
  16375. }
  16376. if (th_.joinable()) { th_.join(); }
  16377. }
  16378. int port() const { return port_; }
  16379. int connect_hits() const { return connect_hits_.load(); }
  16380. private:
  16381. void run() {
  16382. while (!stop_.load()) {
  16383. fd_set rfds;
  16384. FD_ZERO(&rfds);
  16385. FD_SET(listen_fd_, &rfds);
  16386. timeval tv{0, 100 * 1000};
  16387. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16388. if (sel <= 0) { continue; }
  16389. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16390. if (client_fd < 0) { continue; }
  16391. std::string req;
  16392. char buf[2048];
  16393. while (req.find("\r\n\r\n") == std::string::npos) {
  16394. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16395. if (n <= 0) { break; }
  16396. req.append(buf, static_cast<size_t>(n));
  16397. }
  16398. if (req.compare(0, 7, "CONNECT") != 0) {
  16399. ::close(client_fd);
  16400. continue;
  16401. }
  16402. connect_hits_++;
  16403. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16404. ::send(client_fd, ok, std::strlen(ok), 0);
  16405. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16406. sockaddr_in o{};
  16407. o.sin_family = AF_INET;
  16408. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16409. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16410. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16411. 0) {
  16412. ::close(client_fd);
  16413. ::close(origin_fd);
  16414. continue;
  16415. }
  16416. auto forward = [](int from, int to) {
  16417. char b[8192];
  16418. for (;;) {
  16419. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16420. if (n <= 0) { break; }
  16421. ssize_t off = 0;
  16422. while (off < n) {
  16423. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16424. if (s <= 0) {
  16425. off = n;
  16426. break;
  16427. }
  16428. off += s;
  16429. }
  16430. }
  16431. ::shutdown(to, SHUT_WR);
  16432. };
  16433. std::thread t1([&] { forward(client_fd, origin_fd); });
  16434. std::thread t2([&] { forward(origin_fd, client_fd); });
  16435. t1.join();
  16436. t2.join();
  16437. ::close(client_fd);
  16438. ::close(origin_fd);
  16439. }
  16440. }
  16441. int forward_port_ = -1;
  16442. int listen_fd_ = -1;
  16443. int port_ = 0;
  16444. std::thread th_;
  16445. std::atomic<bool> stop_{false};
  16446. std::atomic<int> connect_hits_{0};
  16447. };
  16448. } // namespace proxy_tunnel_test
  16449. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16450. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16451. // retry; otherwise proxy creds would be sent to the origin.
  16452. std::atomic<int> origin_hits{0};
  16453. std::atomic<bool> origin_saw_proxy_authz{false};
  16454. proxy_tunnel_test::ScopedSSLServer origin;
  16455. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16456. origin_hits++;
  16457. if (req.has_header("Proxy-Authorization")) {
  16458. origin_saw_proxy_authz = true;
  16459. }
  16460. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16461. res.set_header("Proxy-Authenticate",
  16462. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16463. "algorithm=MD5");
  16464. });
  16465. origin.listen();
  16466. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16467. ASSERT_NE(0, proxy.port());
  16468. SSLClient cli(HOST, origin.port());
  16469. cli.enable_server_certificate_verification(false);
  16470. cli.set_proxy(HOST, proxy.port());
  16471. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16472. auto res = cli.Get("/x");
  16473. ASSERT_TRUE(res);
  16474. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16475. EXPECT_EQ(1, origin_hits.load());
  16476. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16477. EXPECT_EQ(1, proxy.connect_hits());
  16478. }
  16479. #endif