test.cc 589 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4331. // rather than treat them as valid lengths.
  4332. template <typename ClientT>
  4333. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4334. Request req;
  4335. req.method = "POST";
  4336. req.path = "/chunked";
  4337. std::string host_and_port;
  4338. host_and_port += HOST;
  4339. host_and_port += ":";
  4340. host_and_port += std::to_string(PORT);
  4341. req.headers.emplace("Host", host_and_port.c_str());
  4342. req.headers.emplace("Content-Length", "0");
  4343. req.headers.emplace("Transfer-Encoding", "chunked");
  4344. req.body = body;
  4345. auto res = std::make_shared<Response>();
  4346. auto error = Error::Success;
  4347. ASSERT_TRUE(cli.send(req, *res, error));
  4348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4349. }
  4350. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4351. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4352. }
  4353. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4354. expect_chunked_body_rejected(
  4355. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4356. }
  4357. TEST_F(ServerTest, GetStreamed2) {
  4358. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("ab"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetStreamed) {
  4367. auto res = cli_.Get("/streamed");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(std::string("aaabbb"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRange1) {
  4374. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4377. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(true, res->has_header("Content-Range"));
  4379. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4380. EXPECT_EQ(std::string("def"), res->body);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRange2) {
  4383. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("bcdefg"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4392. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4395. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4396. EXPECT_EQ(true, res->has_header("Content-Range"));
  4397. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4398. EXPECT_EQ(std::string("efg"), res->body);
  4399. }
  4400. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4401. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4405. EXPECT_EQ(false, res->has_header("Content-Range"));
  4406. EXPECT_EQ(0U, res->body.size());
  4407. }
  4408. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4409. auto res = cli_.Get("/streamed-with-range",
  4410. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4411. "92233720368547758079223372036854775807"}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4415. EXPECT_EQ(false, res->has_header("Content-Range"));
  4416. EXPECT_EQ(0U, res->body.size());
  4417. }
  4418. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4419. auto res = cli_.Get(
  4420. "/with-range",
  4421. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4422. {"Accept-Encoding", ""}});
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4425. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4426. EXPECT_EQ(true, res->has_header("Content-Range"));
  4427. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4428. EXPECT_EQ(std::string("abcdefg"), res->body);
  4429. }
  4430. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4431. auto res = cli_.Get("/with-range", {
  4432. {"Range", "bytes=0-"},
  4433. {"Accept-Encoding", ""},
  4434. });
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4437. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ(true, res->has_header("Content-Range"));
  4439. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4440. EXPECT_EQ(std::string("abcdefg"), res->body);
  4441. }
  4442. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4443. auto res =
  4444. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4447. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(267U, res->body.size());
  4450. // Check that both range contents are present
  4451. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4452. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4453. // Check that Content-Range headers are present for both ranges
  4454. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4455. std::string::npos);
  4456. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4457. std::string::npos);
  4458. }
  4459. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4460. Ranges ranges;
  4461. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4462. ranges.emplace_back(0, -1);
  4463. }
  4464. auto res =
  4465. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4468. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(0U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4473. auto res =
  4474. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4477. EXPECT_EQ(5U, res->body.size());
  4478. // Check that overlapping ranges are coalesced into a single range
  4479. EXPECT_EQ("bcdef", res->body);
  4480. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4481. // Should be single range, not multipart
  4482. EXPECT_TRUE(res->has_header("Content-Range"));
  4483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4486. auto res =
  4487. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4490. EXPECT_EQ(268U, res->body.size());
  4491. // Check that both range contents are present
  4492. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4493. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4494. // Check that Content-Range headers are present for both ranges
  4495. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4496. std::string::npos);
  4497. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4498. std::string::npos);
  4499. }
  4500. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4501. auto res =
  4502. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4505. EXPECT_EQ(269U, res->body.size());
  4506. // Check that both duplicate range contents are present
  4507. size_t first_abc = res->body.find("abc\r\n");
  4508. EXPECT_TRUE(first_abc != std::string::npos);
  4509. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4510. EXPECT_TRUE(second_abc != std::string::npos);
  4511. // Check that Content-Range headers are present for both ranges
  4512. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4513. EXPECT_TRUE(first_range != std::string::npos);
  4514. size_t second_range =
  4515. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4516. EXPECT_TRUE(second_range != std::string::npos);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4519. auto res = cli_.Get("/streamed-with-range?error",
  4520. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4523. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4524. EXPECT_EQ(false, res->has_header("Content-Range"));
  4525. EXPECT_EQ(0U, res->body.size());
  4526. }
  4527. TEST_F(ServerTest, GetStreamedEndless) {
  4528. uint64_t offset = 0;
  4529. auto res = cli_.Get("/streamed-cancel",
  4530. [&](const char * /*data*/, uint64_t data_length) {
  4531. if (offset < 100) {
  4532. offset += data_length;
  4533. return true;
  4534. }
  4535. return false;
  4536. });
  4537. ASSERT_TRUE(!res);
  4538. EXPECT_EQ(Error::Canceled, res.error());
  4539. }
  4540. TEST_F(ServerTest, ClientStop) {
  4541. std::atomic_size_t count{4};
  4542. std::vector<std::thread> threads;
  4543. for (auto i = count.load(); i != 0; --i) {
  4544. threads.emplace_back([&]() {
  4545. auto res = cli_.Get("/streamed-cancel",
  4546. [&](const char *, uint64_t) { return true; });
  4547. --count;
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_TRUE(res.error() == Error::Canceled ||
  4550. res.error() == Error::Read || res.error() == Error::Write);
  4551. });
  4552. }
  4553. std::this_thread::sleep_for(std::chrono::seconds(2));
  4554. while (count != 0) {
  4555. cli_.stop();
  4556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4557. }
  4558. for (auto &t : threads) {
  4559. t.join();
  4560. }
  4561. }
  4562. TEST_F(ServerTest, GetWithRange1) {
  4563. auto res = cli_.Get("/with-range", {
  4564. make_range_header({{3, 5}}),
  4565. {"Accept-Encoding", ""},
  4566. });
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4569. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4570. EXPECT_EQ(true, res->has_header("Content-Range"));
  4571. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4572. EXPECT_EQ(std::string("def"), res->body);
  4573. }
  4574. TEST_F(ServerTest, GetWithRange2) {
  4575. auto res = cli_.Get("/with-range", {
  4576. make_range_header({{1, -1}}),
  4577. {"Accept-Encoding", ""},
  4578. });
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ(true, res->has_header("Content-Range"));
  4583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4584. EXPECT_EQ(std::string("bcdefg"), res->body);
  4585. }
  4586. TEST_F(ServerTest, GetWithRange3) {
  4587. auto res = cli_.Get("/with-range", {
  4588. make_range_header({{0, 0}}),
  4589. {"Accept-Encoding", ""},
  4590. });
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4593. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4594. EXPECT_EQ(true, res->has_header("Content-Range"));
  4595. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4596. EXPECT_EQ(std::string("a"), res->body);
  4597. }
  4598. TEST_F(ServerTest, GetWithRange4) {
  4599. auto res = cli_.Get("/with-range", {
  4600. make_range_header({{-1, 2}}),
  4601. {"Accept-Encoding", ""},
  4602. });
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ(true, res->has_header("Content-Range"));
  4607. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4608. EXPECT_EQ(std::string("fg"), res->body);
  4609. }
  4610. TEST_F(ServerTest, GetWithRange5) {
  4611. auto res = cli_.Get("/with-range", {
  4612. make_range_header({{0, 5}}),
  4613. {"Accept-Encoding", ""},
  4614. });
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4618. EXPECT_EQ(true, res->has_header("Content-Range"));
  4619. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4620. EXPECT_EQ(std::string("abcdef"), res->body);
  4621. }
  4622. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4623. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4626. }
  4627. TEST_F(ServerTest, GetWithRangeMultipart) {
  4628. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4631. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4632. EXPECT_EQ(false, res->has_header("Content-Range"));
  4633. EXPECT_EQ(267U, res->body.size());
  4634. }
  4635. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4636. auto res =
  4637. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4640. }
  4641. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4642. auto res = cli_.Get("/with-range-customized-response",
  4643. {{make_range_header({{1, 2}})}});
  4644. ASSERT_TRUE(res);
  4645. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4646. EXPECT_EQ(true, res->has_header("Content-Length"));
  4647. EXPECT_EQ(false, res->has_header("Content-Range"));
  4648. EXPECT_EQ(JSON_DATA, res->body);
  4649. }
  4650. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4651. auto res = cli_.Get("/with-range-customized-response",
  4652. {{make_range_header({{1, 2}, {4, 5}})}});
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4655. EXPECT_EQ(true, res->has_header("Content-Length"));
  4656. EXPECT_EQ(false, res->has_header("Content-Range"));
  4657. EXPECT_EQ(JSON_DATA, res->body);
  4658. }
  4659. TEST_F(ServerTest, Issue1772) {
  4660. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4663. }
  4664. TEST_F(ServerTest, Issue609) {
  4665. auto res = cli_.Delete("/issue609");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("ok"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedChunked) {
  4671. auto res = cli_.Get("/streamed-chunked");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. EXPECT_EQ(std::string("123456789"), res->body);
  4675. }
  4676. TEST_F(ServerTest, GetStreamedChunked2) {
  4677. auto res = cli_.Get("/streamed-chunked2");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ(std::string("123456789"), res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4683. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4684. ASSERT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. EXPECT_EQ(std::string("123456789"), res->body);
  4687. EXPECT_TRUE(res->has_header("Trailer"));
  4688. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4689. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4690. // Trailers are now stored separately from headers (security fix)
  4691. EXPECT_EQ(2U, res->trailers.size());
  4692. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4693. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4694. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4695. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4696. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4697. // Verify trailers are NOT in headers (security verification)
  4698. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4699. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4700. }
  4701. TEST_F(ServerTest, LargeChunkedPost) {
  4702. Request req;
  4703. req.method = "POST";
  4704. req.path = "/large-chunked";
  4705. std::string host_and_port;
  4706. host_and_port += HOST;
  4707. host_and_port += ":";
  4708. host_and_port += std::to_string(PORT);
  4709. req.headers.emplace("Host", host_and_port.c_str());
  4710. req.headers.emplace("Accept", "*/*");
  4711. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4712. req.headers.emplace("Content-Type", "text/plain");
  4713. req.headers.emplace("Content-Length", "0");
  4714. req.headers.emplace("Transfer-Encoding", "chunked");
  4715. std::string long_string(30 * 1024u, 'a');
  4716. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4717. // Attempt to make a large enough post to exceed OS buffers, to test that
  4718. // the server handles short reads if the full chunk data isn't available.
  4719. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4720. auto res = std::make_shared<Response>();
  4721. auto error = Error::Success;
  4722. auto ret = cli_.send(req, *res, error);
  4723. ASSERT_TRUE(ret);
  4724. EXPECT_EQ(StatusCode::OK_200, res->status);
  4725. }
  4726. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4727. auto res = cli_.Get("/remote_addr");
  4728. ASSERT_TRUE(res);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4732. }
  4733. TEST_F(ServerTest, GetMethodLocalAddr) {
  4734. auto res = cli_.Get("/local_addr");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4738. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4739. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4740. }
  4741. TEST_F(ServerTest, HTTPResponseSplitting) {
  4742. auto res = cli_.Get("/http_response_splitting");
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. }
  4746. TEST_F(ServerTest, SlowRequest) {
  4747. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4748. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4749. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4750. }
  4751. #if 0
  4752. TEST_F(ServerTest, SlowPost) {
  4753. char buffer[64 * 1024];
  4754. memset(buffer, 0x42, sizeof(buffer));
  4755. auto res = cli_.Post(
  4756. "/slowpost", 64 * 1024 * 1024,
  4757. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4758. auto ret = sink.write(buffer, sizeof(buffer));
  4759. EXPECT_TRUE(ret);
  4760. return true;
  4761. },
  4762. "text/plain");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST_F(ServerTest, SlowPostFail) {
  4767. char buffer[64 * 1024];
  4768. memset(buffer, 0x42, sizeof(buffer));
  4769. cli_.set_write_timeout(std::chrono::seconds(0));
  4770. auto res = cli_.Post(
  4771. "/slowpost", 64 * 1024 * 1024,
  4772. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4773. sink.write(buffer, sizeof(buffer));
  4774. return true;
  4775. },
  4776. "text/plain");
  4777. ASSERT_TRUE(!res);
  4778. EXPECT_EQ(Error::Write, res.error());
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Put) {
  4782. auto res = cli_.Put("/put", "PUT", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PutWithContentProvider) {
  4788. auto res = cli_.Put(
  4789. "/put", 3,
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4791. sink.os << "PUT";
  4792. return true;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("PUT", res->body);
  4798. }
  4799. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4800. auto res = cli_.Post(
  4801. "/post", 42,
  4802. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4803. return false;
  4804. },
  4805. "text/plain");
  4806. ASSERT_TRUE(!res);
  4807. EXPECT_EQ(Error::Canceled, res.error());
  4808. }
  4809. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4810. auto res = cli_.Put(
  4811. "/put",
  4812. [](size_t /*offset*/, DataSink &sink) {
  4813. sink.os << "PUT";
  4814. sink.done();
  4815. return true;
  4816. },
  4817. "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("PUT", res->body);
  4821. }
  4822. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4823. auto res = cli_.Post(
  4824. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4825. "text/plain");
  4826. ASSERT_TRUE(!res);
  4827. EXPECT_EQ(Error::Canceled, res.error());
  4828. }
  4829. TEST_F(ServerTest, PostLoopBack) {
  4830. std::string body;
  4831. auto res = cli_.Post(
  4832. "/post-loopback", 9,
  4833. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4834. EXPECT_EQ(9u, length);
  4835. sink.write("123", 3);
  4836. sink.write("456", 3);
  4837. sink.write("789", 3);
  4838. return true;
  4839. },
  4840. "text/plain",
  4841. [&body](const char *data, size_t data_length) {
  4842. body.append(data, data_length);
  4843. return true;
  4844. });
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("123456789", body);
  4848. }
  4849. TEST_F(ServerTest, PutLoopBack) {
  4850. std::string body;
  4851. auto res = cli_.Put(
  4852. "/put-loopback", 9,
  4853. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4854. EXPECT_EQ(9u, length);
  4855. sink.write("123", 3);
  4856. sink.write("456", 3);
  4857. sink.write("789", 3);
  4858. return true;
  4859. },
  4860. "text/plain",
  4861. [&body](const char *data, size_t data_length) {
  4862. body.append(data, data_length);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(res);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. EXPECT_EQ("123456789", body);
  4868. }
  4869. TEST_F(ServerTest, PatchLoopBack) {
  4870. std::string body;
  4871. auto res = cli_.Patch(
  4872. "/patch-loopback", 9,
  4873. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4874. EXPECT_EQ(9u, length);
  4875. sink.write("123", 3);
  4876. sink.write("456", 3);
  4877. sink.write("789", 3);
  4878. return true;
  4879. },
  4880. "text/plain",
  4881. [&body](const char *data, size_t data_length) {
  4882. body.append(data, data_length);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("123456789", body);
  4888. }
  4889. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4890. std::string body;
  4891. auto res = cli_.Post(
  4892. "/post-loopback",
  4893. [](size_t /*offset*/, DataSink &sink) {
  4894. sink.write("123", 3);
  4895. sink.write("456", 3);
  4896. sink.write("789", 3);
  4897. sink.done();
  4898. return true;
  4899. },
  4900. "text/plain",
  4901. [&body](const char *data, size_t data_length) {
  4902. body.append(data, data_length);
  4903. return true;
  4904. });
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("123456789", body);
  4908. }
  4909. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4910. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4911. cli_.set_compress(true);
  4912. auto res = cli_.Put(
  4913. "/put", 3,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4915. sink.os << "PUT";
  4916. return true;
  4917. },
  4918. "text/plain");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("PUT", res->body);
  4922. }
  4923. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4924. cli_.set_compress(true);
  4925. auto res = cli_.Post(
  4926. "/post", 42,
  4927. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4928. return false;
  4929. },
  4930. "text/plain");
  4931. ASSERT_TRUE(!res);
  4932. EXPECT_EQ(Error::Canceled, res.error());
  4933. }
  4934. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4935. cli_.set_compress(true);
  4936. auto res = cli_.Put(
  4937. "/put",
  4938. [](size_t /*offset*/, DataSink &sink) {
  4939. sink.os << "PUT";
  4940. sink.done();
  4941. return true;
  4942. },
  4943. "text/plain");
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("PUT", res->body);
  4947. }
  4948. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4949. cli_.set_compress(true);
  4950. auto res = cli_.Post(
  4951. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4952. "text/plain");
  4953. ASSERT_TRUE(!res);
  4954. EXPECT_EQ(Error::Canceled, res.error());
  4955. }
  4956. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4957. cli_.set_compress(true);
  4958. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. EXPECT_EQ(LARGE_DATA, res->body);
  4962. }
  4963. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4964. #ifdef CPPHTTPLIB_SSL_ENABLED
  4965. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4966. Client cli(s.c_str());
  4967. cli.enable_server_certificate_verification(false);
  4968. #else
  4969. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4970. Client cli(s.c_str());
  4971. #endif
  4972. cli.set_compress(true);
  4973. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ(LARGE_DATA, res->body);
  4977. // The compressed size should be less than a 10th of the original. May vary
  4978. // depending on the zlib library.
  4979. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4980. static_cast<uint64_t>(10 * 1024 * 1024));
  4981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4982. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4983. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4984. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4985. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4986. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4987. #endif
  4988. }
  4989. TEST_F(ServerTest, PutContentWithDeflate) {
  4990. cli_.set_compress(false);
  4991. Headers headers;
  4992. headers.emplace("Content-Encoding", "deflate");
  4993. // PUT in deflate format:
  4994. auto res = cli_.Put("/put", headers,
  4995. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("PUT", res->body);
  4999. }
  5000. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/streamed-chunked", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(StatusCode::OK_200, res->status);
  5006. EXPECT_EQ(std::string("123456789"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5009. Headers headers;
  5010. headers.emplace("Accept-Encoding", "gzip, deflate");
  5011. auto res = cli_.Get("/streamed-chunked2", headers);
  5012. ASSERT_TRUE(res);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ(std::string("123456789"), res->body);
  5015. }
  5016. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5017. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST(GzipDecompressor, ChunkedDecompression) {
  5022. std::string data;
  5023. for (size_t i = 0; i < 32 * 1024; ++i) {
  5024. data.push_back(static_cast<char>('a' + i % 26));
  5025. }
  5026. std::string compressed_data;
  5027. {
  5028. httplib::detail::gzip_compressor compressor;
  5029. bool result = compressor.compress(
  5030. data.data(), data.size(),
  5031. /*last=*/true,
  5032. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5033. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5034. compressed_data_size);
  5035. return true;
  5036. });
  5037. ASSERT_TRUE(result);
  5038. }
  5039. std::string decompressed_data;
  5040. {
  5041. httplib::detail::gzip_decompressor decompressor;
  5042. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5043. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5044. size_t chunk_size = 130;
  5045. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5046. chunk_begin += chunk_size) {
  5047. size_t current_chunk_size =
  5048. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5049. bool result = decompressor.decompress(
  5050. compressed_data.data() + chunk_begin, current_chunk_size,
  5051. [&](const char *decompressed_data_chunk,
  5052. size_t decompressed_data_chunk_size) {
  5053. decompressed_data.insert(decompressed_data.size(),
  5054. decompressed_data_chunk,
  5055. decompressed_data_chunk_size);
  5056. return true;
  5057. });
  5058. ASSERT_TRUE(result);
  5059. }
  5060. }
  5061. ASSERT_EQ(data, decompressed_data);
  5062. }
  5063. TEST(GzipDecompressor, DeflateDecompression) {
  5064. std::string original_text = "Raw deflate without gzip";
  5065. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5066. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5067. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5068. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5069. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5070. std::string decompressed_data;
  5071. {
  5072. httplib::detail::gzip_decompressor decompressor;
  5073. bool result = decompressor.decompress(
  5074. compressed_data.data(), compressed_data.size(),
  5075. [&](const char *decompressed_data_chunk,
  5076. size_t decompressed_data_chunk_size) {
  5077. decompressed_data.insert(decompressed_data.size(),
  5078. decompressed_data_chunk,
  5079. decompressed_data_chunk_size);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(result);
  5083. }
  5084. ASSERT_EQ(original_text, decompressed_data);
  5085. }
  5086. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5087. std::string original_text = "Raw deflate without gzip";
  5088. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5089. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5090. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5091. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5092. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5093. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5094. std::string decompressed_data;
  5095. {
  5096. httplib::detail::gzip_decompressor decompressor;
  5097. bool result = decompressor.decompress(
  5098. compressed_data.data(), compressed_data.size(),
  5099. [&](const char *decompressed_data_chunk,
  5100. size_t decompressed_data_chunk_size) {
  5101. decompressed_data.insert(decompressed_data.size(),
  5102. decompressed_data_chunk,
  5103. decompressed_data_chunk_size);
  5104. return true;
  5105. });
  5106. ASSERT_TRUE(result);
  5107. }
  5108. ASSERT_EQ(original_text, decompressed_data);
  5109. }
  5110. #endif
  5111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5112. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5113. Headers headers;
  5114. headers.emplace("Accept-Encoding", "br");
  5115. auto res = cli_.Get("/streamed-chunked", headers);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ(std::string("123456789"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5121. Headers headers;
  5122. headers.emplace("Accept-Encoding", "br");
  5123. auto res = cli_.Get("/streamed-chunked2", headers);
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ(std::string("123456789"), res->body);
  5127. }
  5128. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put(
  5131. "/put", 3,
  5132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5133. sink.os << "PUT";
  5134. return true;
  5135. },
  5136. "text/plain");
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("PUT", res->body);
  5140. }
  5141. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5142. cli_.set_compress(true);
  5143. auto res = cli_.Put(
  5144. "/put",
  5145. [](size_t /*offset*/, DataSink &sink) {
  5146. sink.os << "PUT";
  5147. sink.done();
  5148. return true;
  5149. },
  5150. "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("PUT", res->body);
  5154. }
  5155. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5156. cli_.set_compress(true);
  5157. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ(LARGE_DATA, res->body);
  5161. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5162. }
  5163. #endif
  5164. TEST_F(ServerTest, Patch) {
  5165. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. EXPECT_EQ("PATCH", res->body);
  5169. }
  5170. TEST_F(ServerTest, Delete) {
  5171. auto res = cli_.Delete("/delete");
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("DELETE", res->body);
  5175. }
  5176. TEST_F(ServerTest, DeleteContentReceiver) {
  5177. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("content", res->body);
  5181. }
  5182. TEST_F(ServerTest, Options) {
  5183. auto res = cli_.Options("*");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5187. EXPECT_TRUE(res->body.empty());
  5188. }
  5189. TEST_F(ServerTest, URL) {
  5190. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, ArrayParam) {
  5195. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, ArrayParamValues) {
  5200. auto res =
  5201. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. TEST_F(ServerTest, NoMultipleHeaders) {
  5206. Headers headers = {{"Content-Length", "5"}};
  5207. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5208. "text/plain");
  5209. ASSERT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, PostContentReceiver) {
  5213. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5214. ASSERT_TRUE(res);
  5215. ASSERT_EQ(StatusCode::OK_200, res->status);
  5216. ASSERT_EQ("content", res->body);
  5217. }
  5218. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5219. UploadFormDataItems items = {
  5220. {"text1", "text default", "", ""},
  5221. {"text2", "aωb", "", ""},
  5222. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5223. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5224. {"file3", "", "", "application/octet-stream"},
  5225. };
  5226. auto res = cli_.Post("/content_receiver", items);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. }
  5230. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5231. UploadFormDataItems items = {
  5232. {"text1", "text default", "", ""},
  5233. {"text2", "aωb", "", ""},
  5234. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5235. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5236. {"file3", "", "", "application/octet-stream"},
  5237. };
  5238. auto boundary = std::string("+++++");
  5239. std::string body;
  5240. for (const auto &item : items) {
  5241. body += "--" + boundary + "\r\n";
  5242. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5243. if (!item.filename.empty()) {
  5244. body += "; filename=\"" + item.filename + "\"";
  5245. }
  5246. body += "\r\n";
  5247. if (!item.content_type.empty()) {
  5248. body += "Content-Type: " + item.content_type + "\r\n";
  5249. }
  5250. body += "\r\n";
  5251. body += item.content + "\r\n";
  5252. }
  5253. body += "--" + boundary + "--\r\n";
  5254. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5255. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5256. ASSERT_TRUE(res);
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. }
  5259. TEST_F(ServerTest, PostContentReceiverGzip) {
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5262. ASSERT_TRUE(res);
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("content", res->body);
  5265. }
  5266. TEST_F(ServerTest, PutContentReceiver) {
  5267. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5268. ASSERT_TRUE(res);
  5269. ASSERT_EQ(StatusCode::OK_200, res->status);
  5270. ASSERT_EQ("content", res->body);
  5271. }
  5272. TEST_F(ServerTest, PatchContentReceiver) {
  5273. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5274. ASSERT_TRUE(res);
  5275. ASSERT_EQ(StatusCode::OK_200, res->status);
  5276. ASSERT_EQ("content", res->body);
  5277. }
  5278. template <typename ClientType>
  5279. void TestWithHeadersAndContentReceiver(
  5280. ClientType &cli,
  5281. std::function<Result(ClientType &, const std::string &, const Headers &,
  5282. const std::string &, const std::string &,
  5283. ContentReceiver, DownloadProgress)>
  5284. request_func) {
  5285. Headers headers;
  5286. headers.emplace("X-Custom-Header", "test-value");
  5287. std::string received_body;
  5288. auto res = request_func(
  5289. cli, "/content_receiver", headers, "content", "application/json",
  5290. [&](const char *data, size_t data_length) {
  5291. received_body.append(data, data_length);
  5292. return true;
  5293. },
  5294. nullptr);
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("content", received_body);
  5298. }
  5299. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5300. #ifdef CPPHTTPLIB_SSL_ENABLED
  5301. using ClientT = SSLClient;
  5302. #else
  5303. using ClientT = Client;
  5304. #endif
  5305. TestWithHeadersAndContentReceiver<ClientT>(
  5306. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5307. const std::string &body, const std::string &content_type,
  5308. ContentReceiver receiver, DownloadProgress progress) {
  5309. return cli.Post(path, headers, body, content_type, receiver, progress);
  5310. });
  5311. }
  5312. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5313. #ifdef CPPHTTPLIB_SSL_ENABLED
  5314. using ClientT = SSLClient;
  5315. #else
  5316. using ClientT = Client;
  5317. #endif
  5318. TestWithHeadersAndContentReceiver<ClientT>(
  5319. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5320. const std::string &body, const std::string &content_type,
  5321. ContentReceiver receiver, DownloadProgress progress) {
  5322. return cli.Put(path, headers, body, content_type, receiver, progress);
  5323. });
  5324. }
  5325. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5326. #ifdef CPPHTTPLIB_SSL_ENABLED
  5327. using ClientT = SSLClient;
  5328. #else
  5329. using ClientT = Client;
  5330. #endif
  5331. TestWithHeadersAndContentReceiver<ClientT>(
  5332. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5333. const std::string &body, const std::string &content_type,
  5334. ContentReceiver receiver, DownloadProgress progress) {
  5335. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5336. });
  5337. }
  5338. template <typename ClientType>
  5339. void TestWithHeadersAndContentReceiverWithProgress(
  5340. ClientType &cli,
  5341. std::function<Result(ClientType &, const std::string &, const Headers &,
  5342. const std::string &, const std::string &,
  5343. ContentReceiver, DownloadProgress)>
  5344. request_func) {
  5345. Headers headers;
  5346. headers.emplace("X-Test-Header", "progress-test");
  5347. std::string received_body;
  5348. auto progress_called = false;
  5349. auto res = request_func(
  5350. cli, "/content_receiver", headers, "content", "text/plain",
  5351. [&](const char *data, size_t data_length) {
  5352. received_body.append(data, data_length);
  5353. return true;
  5354. },
  5355. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5356. progress_called = true;
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ("content", received_body);
  5362. EXPECT_TRUE(progress_called);
  5363. }
  5364. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5365. #ifdef CPPHTTPLIB_SSL_ENABLED
  5366. using ClientT = SSLClient;
  5367. #else
  5368. using ClientT = Client;
  5369. #endif
  5370. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5371. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5372. const std::string &body, const std::string &content_type,
  5373. ContentReceiver receiver, DownloadProgress progress) {
  5374. return cli.Post(path, headers, body, content_type, receiver, progress);
  5375. });
  5376. }
  5377. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5378. #ifdef CPPHTTPLIB_SSL_ENABLED
  5379. using ClientT = SSLClient;
  5380. #else
  5381. using ClientT = Client;
  5382. #endif
  5383. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5384. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5385. const std::string &body, const std::string &content_type,
  5386. ContentReceiver receiver, DownloadProgress progress) {
  5387. return cli.Put(path, headers, body, content_type, receiver, progress);
  5388. });
  5389. }
  5390. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5391. #ifdef CPPHTTPLIB_SSL_ENABLED
  5392. using ClientT = SSLClient;
  5393. #else
  5394. using ClientT = Client;
  5395. #endif
  5396. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5398. const std::string &body, const std::string &content_type,
  5399. ContentReceiver receiver, DownloadProgress progress) {
  5400. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5401. });
  5402. }
  5403. template <typename ClientType>
  5404. void TestWithHeadersAndContentReceiverError(
  5405. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5406. const Headers &, const std::string &,
  5407. const std::string &, ContentReceiver)>
  5408. request_func) {
  5409. Headers headers;
  5410. headers.emplace("X-Error-Test", "true");
  5411. std::string received_body;
  5412. auto receiver_failed = false;
  5413. auto res =
  5414. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5415. [&](const char *data, size_t data_length) {
  5416. received_body.append(data, data_length);
  5417. receiver_failed = true;
  5418. return false;
  5419. });
  5420. ASSERT_FALSE(res);
  5421. EXPECT_TRUE(receiver_failed);
  5422. }
  5423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5424. #ifdef CPPHTTPLIB_SSL_ENABLED
  5425. using ClientT = SSLClient;
  5426. #else
  5427. using ClientT = Client;
  5428. #endif
  5429. TestWithHeadersAndContentReceiverError<ClientT>(
  5430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5431. const std::string &body, const std::string &content_type,
  5432. ContentReceiver receiver) {
  5433. return cli.Post(path, headers, body, content_type, receiver);
  5434. });
  5435. }
  5436. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5437. #ifdef CPPHTTPLIB_SSL_ENABLED
  5438. using ClientT = SSLClient;
  5439. #else
  5440. using ClientT = Client;
  5441. #endif
  5442. TestWithHeadersAndContentReceiverError<ClientT>(
  5443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5444. const std::string &body, const std::string &content_type,
  5445. ContentReceiver receiver) {
  5446. return cli.Put(path, headers, body, content_type, receiver);
  5447. });
  5448. }
  5449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5450. #ifdef CPPHTTPLIB_SSL_ENABLED
  5451. using ClientT = SSLClient;
  5452. #else
  5453. using ClientT = Client;
  5454. #endif
  5455. TestWithHeadersAndContentReceiverError<ClientT>(
  5456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5457. const std::string &body, const std::string &content_type,
  5458. ContentReceiver receiver) {
  5459. return cli.Patch(path, headers, body, content_type, receiver);
  5460. });
  5461. }
  5462. TEST_F(ServerTest, PostQueryStringAndBody) {
  5463. auto res =
  5464. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5465. ASSERT_TRUE(res);
  5466. ASSERT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, HTTP2Magic) {
  5469. Request req;
  5470. req.method = "PRI";
  5471. req.path = "*";
  5472. req.body = "SM";
  5473. auto res = std::make_shared<Response>();
  5474. auto error = Error::Success;
  5475. auto ret = cli_.send(req, *res, error);
  5476. ASSERT_TRUE(ret);
  5477. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5478. }
  5479. TEST_F(ServerTest, KeepAlive) {
  5480. auto res = cli_.Get("/hi");
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. EXPECT_EQ("Hello World!", res->body);
  5485. res = cli_.Get("/hi");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("Hello World!", res->body);
  5490. res = cli_.Get("/hi");
  5491. ASSERT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("Hello World!", res->body);
  5495. res = cli_.Get("/not-exist");
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5498. res = cli_.Post("/empty", "", "text/plain");
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ(StatusCode::OK_200, res->status);
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("empty", res->body);
  5503. EXPECT_EQ("close", res->get_header_value("Connection"));
  5504. res = cli_.Post(
  5505. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("empty", res->body);
  5511. cli_.set_keep_alive(false);
  5512. res = cli_.Get("/last-request");
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("close", res->get_header_value("Connection"));
  5516. }
  5517. TEST_F(ServerTest, TooManyRedirect) {
  5518. cli_.set_follow_location(true);
  5519. auto res = cli_.Get("/redirect/0");
  5520. ASSERT_TRUE(!res);
  5521. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5522. }
  5523. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5524. Request req;
  5525. req.method = "FOOBAR";
  5526. req.path = "/hi";
  5527. cli_.set_keep_alive(true);
  5528. auto res = cli_.send(req);
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5531. EXPECT_EQ("close", res->get_header_value("Connection"));
  5532. EXPECT_FALSE(cli_.is_socket_open());
  5533. }
  5534. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5536. TEST_F(ServerTest, Gzip) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "gzip, deflate");
  5539. auto res = cli_.Get("/compress", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5545. "7890123456789012345678901234567890",
  5546. res->body);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. }
  5549. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "gzip, deflate");
  5552. auto res = cli_.Get("/compress-with-charset", headers);
  5553. ASSERT_TRUE(res);
  5554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5555. EXPECT_EQ("application/json; charset=utf-8",
  5556. res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. res->body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "");
  5565. auto res = cli_.Get("/compress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, GzipWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "gzip, deflate");
  5578. std::string body;
  5579. auto res = cli_.Get("/compress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5595. Headers headers;
  5596. headers.emplace("Accept-Encoding", "gzip, deflate");
  5597. cli_.set_decompress(false);
  5598. auto res = cli_.Get("/compress", headers);
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(33U, res->body.size());
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. }
  5606. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "");
  5609. std::string body;
  5610. auto res = cli_.Get("/compress", headers,
  5611. [&](const char *data, uint64_t data_length) {
  5612. EXPECT_EQ(100U, data_length);
  5613. body.append(data, data_length);
  5614. return true;
  5615. });
  5616. ASSERT_TRUE(res);
  5617. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5621. "7890123456789012345678901234567890",
  5622. body);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. }
  5625. TEST_F(ServerTest, NoGzip) {
  5626. Headers headers;
  5627. headers.emplace("Accept-Encoding", "gzip, deflate");
  5628. auto res = cli_.Get("/nocompress", headers);
  5629. ASSERT_TRUE(res);
  5630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5634. "7890123456789012345678901234567890",
  5635. res->body);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. }
  5638. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5639. Headers headers;
  5640. headers.emplace("Accept-Encoding", "gzip, deflate");
  5641. std::string body;
  5642. auto res = cli_.Get("/nocompress", headers,
  5643. [&](const char *data, uint64_t data_length) {
  5644. EXPECT_EQ(100U, data_length);
  5645. body.append(data, data_length);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5653. "7890123456789012345678901234567890",
  5654. body);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. }
  5657. TEST_F(ServerTest, MultipartFormDataGzip) {
  5658. UploadFormDataItems items = {
  5659. {"key1", "test", "", ""},
  5660. {"key2", "--abcdefg123", "", ""},
  5661. };
  5662. cli_.set_compress(true);
  5663. auto res = cli_.Post("/compress-multipart", items);
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. }
  5667. #endif
  5668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5669. TEST_F(ServerTest, Brotli) {
  5670. Headers headers;
  5671. headers.emplace("Accept-Encoding", "br");
  5672. auto res = cli_.Get("/compress", headers);
  5673. ASSERT_TRUE(res);
  5674. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5676. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5677. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5678. "7890123456789012345678901234567890",
  5679. res->body);
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. }
  5682. #endif
  5683. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5684. TEST_F(ServerTest, Zstd) {
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "zstd");
  5687. auto res = cli_.Get("/compress", headers);
  5688. ASSERT_TRUE(res);
  5689. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5693. "7890123456789012345678901234567890",
  5694. res->body);
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. }
  5697. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5706. "7890123456789012345678901234567890",
  5707. res->body);
  5708. EXPECT_EQ(StatusCode::OK_200, res->status);
  5709. }
  5710. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "zstd");
  5713. std::string body;
  5714. auto res = cli_.Get("/compress", headers,
  5715. [&](const char *data, uint64_t data_length) {
  5716. EXPECT_EQ(100U, data_length);
  5717. body.append(data, data_length);
  5718. return true;
  5719. });
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5724. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5725. "7890123456789012345678901234567890",
  5726. body);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. }
  5729. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5730. Headers headers;
  5731. headers.emplace("Accept-Encoding", "zstd");
  5732. cli_.set_decompress(false);
  5733. auto res = cli_.Get("/compress", headers);
  5734. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5735. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5736. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5737. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5738. ASSERT_TRUE(res);
  5739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ(26U, res->body.size());
  5744. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5745. 0);
  5746. }
  5747. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "");
  5750. std::string body;
  5751. auto res = cli_.Get("/compress", headers,
  5752. [&](const char *data, uint64_t data_length) {
  5753. EXPECT_EQ(100U, data_length);
  5754. body.append(data, data_length);
  5755. return true;
  5756. });
  5757. ASSERT_TRUE(res);
  5758. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5762. "7890123456789012345678901234567890",
  5763. body);
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST_F(ServerTest, NoZstd) {
  5767. Headers headers;
  5768. headers.emplace("Accept-Encoding", "zstd");
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5772. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5773. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5775. "7890123456789012345678901234567890",
  5776. res->body);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5780. Headers headers;
  5781. headers.emplace("Accept-Encoding", "zstd");
  5782. std::string body;
  5783. auto res = cli_.Get("/nocompress", headers,
  5784. [&](const char *data, uint64_t data_length) {
  5785. EXPECT_EQ(100U, data_length);
  5786. body.append(data, data_length);
  5787. return true;
  5788. });
  5789. ASSERT_TRUE(res);
  5790. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5791. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5793. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5794. "7890123456789012345678901234567890",
  5795. body);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. // TODO: How to enable zstd ??
  5799. TEST_F(ServerTest, MultipartFormDataZstd) {
  5800. UploadFormDataItems items = {
  5801. {"key1", "test", "", ""},
  5802. {"key2", "--abcdefg123", "", ""},
  5803. };
  5804. Headers headers;
  5805. headers.emplace("Accept-Encoding", "zstd");
  5806. cli_.set_compress(true);
  5807. auto res = cli_.Post("/compress-multipart", headers, items);
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5812. Headers headers;
  5813. headers.emplace("Accept-Encoding", "zstd");
  5814. cli_.set_compress(true);
  5815. auto res = cli_.Put(
  5816. "/put", headers, 3,
  5817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5818. sink.os << "PUT";
  5819. return true;
  5820. },
  5821. "text/plain");
  5822. ASSERT_TRUE(res);
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("PUT", res->body);
  5825. }
  5826. // Pre-compression logging tests
  5827. TEST_F(ServerTest, PreCompressionLogging) {
  5828. // Test data for compression (matches the actual /compress endpoint content)
  5829. const std::string test_content =
  5830. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5831. "3456789012345678901234567890";
  5832. // Variables to capture logging data
  5833. std::string pre_compression_body;
  5834. std::string pre_compression_content_type;
  5835. std::string pre_compression_content_encoding;
  5836. std::string post_compression_body;
  5837. std::string post_compression_content_type;
  5838. std::string post_compression_content_encoding;
  5839. // Set up pre-compression logger
  5840. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5841. const Response &res) {
  5842. pre_compression_body = res.body;
  5843. pre_compression_content_type = res.get_header_value("Content-Type");
  5844. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5845. });
  5846. // Set up post-compression logger
  5847. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5848. post_compression_body = res.body;
  5849. post_compression_content_type = res.get_header_value("Content-Type");
  5850. post_compression_content_encoding =
  5851. res.get_header_value("Content-Encoding");
  5852. });
  5853. // Test with gzip compression
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "gzip");
  5856. auto res = cli_.Get("/compress", headers);
  5857. // Verify response was compressed
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5861. // Verify pre-compression logger captured uncompressed content
  5862. EXPECT_EQ(test_content, pre_compression_body);
  5863. EXPECT_EQ("text/plain", pre_compression_content_type);
  5864. EXPECT_TRUE(pre_compression_content_encoding
  5865. .empty()); // No encoding header before compression
  5866. // Verify post-compression logger captured compressed content
  5867. EXPECT_NE(test_content,
  5868. post_compression_body); // Should be different after compression
  5869. EXPECT_EQ("text/plain", post_compression_content_type);
  5870. EXPECT_EQ("gzip", post_compression_content_encoding);
  5871. // Verify compressed content is smaller
  5872. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5873. }
  5874. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5875. const std::string test_content =
  5876. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5877. "3456789012345678901234567890";
  5878. std::string pre_compression_body;
  5879. std::string post_compression_body;
  5880. svr_.set_pre_compression_logger(
  5881. [&](const Request & /*req*/, const Response &res) {
  5882. pre_compression_body = res.body;
  5883. });
  5884. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5885. post_compression_body = res.body;
  5886. });
  5887. Headers headers;
  5888. headers.emplace("Accept-Encoding", "br");
  5889. auto res = cli_.Get("/compress", headers);
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5893. // Verify pre-compression content is uncompressed
  5894. EXPECT_EQ(test_content, pre_compression_body);
  5895. // Verify post-compression content is compressed
  5896. EXPECT_NE(test_content, post_compression_body);
  5897. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5898. }
  5899. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5900. const std::string test_content =
  5901. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5902. "3456789012345678901234567890";
  5903. std::string pre_compression_body;
  5904. std::string post_compression_body;
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. });
  5909. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5910. post_compression_body = res.body;
  5911. });
  5912. // Request without compression (use /nocompress endpoint)
  5913. Headers headers;
  5914. auto res = cli_.Get("/nocompress", headers);
  5915. ASSERT_TRUE(res);
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5918. // Pre-compression logger should not be called when no compression is applied
  5919. EXPECT_TRUE(
  5920. pre_compression_body.empty()); // Pre-compression logger not called
  5921. EXPECT_EQ(
  5922. test_content,
  5923. post_compression_body); // Post-compression logger captures final content
  5924. }
  5925. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5926. const std::string test_content =
  5927. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5928. "3456789012345678901234567890";
  5929. std::string pre_compression_body;
  5930. bool pre_logger_called = false;
  5931. // Set only pre-compression logger
  5932. svr_.set_pre_compression_logger(
  5933. [&](const Request & /*req*/, const Response &res) {
  5934. pre_compression_body = res.body;
  5935. pre_logger_called = true;
  5936. });
  5937. Headers headers;
  5938. headers.emplace("Accept-Encoding", "gzip");
  5939. auto res = cli_.Get("/compress", headers);
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5943. // Verify pre-compression logger was called
  5944. EXPECT_TRUE(pre_logger_called);
  5945. EXPECT_EQ(test_content, pre_compression_body);
  5946. }
  5947. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5948. {
  5949. // Test with Expect: 100-continue header - success case
  5950. // Server returns 100 Continue, client sends body, server returns 200 OK
  5951. Request req;
  5952. req.method = "POST";
  5953. req.path = "/post-large";
  5954. req.set_header("Expect", "100-continue");
  5955. req.body = LARGE_DATA;
  5956. Response res;
  5957. auto error = Error::Success;
  5958. cli_.set_keep_alive(true);
  5959. auto ret = cli_.send(req, res, error);
  5960. EXPECT_TRUE(ret);
  5961. EXPECT_EQ(StatusCode::OK_200, res.status);
  5962. EXPECT_EQ(LARGE_DATA, res.body);
  5963. }
  5964. {
  5965. // Test with Expect: 100-continue header - error case
  5966. // Client should not send the body when server returns an error
  5967. Request req;
  5968. req.method = "POST";
  5969. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5970. req.set_header("Expect", "100-continue");
  5971. req.body = LARGE_DATA;
  5972. Response res;
  5973. auto error = Error::Success;
  5974. auto start = std::chrono::high_resolution_clock::now();
  5975. cli_.set_keep_alive(true);
  5976. auto ret = cli_.send(req, res, error);
  5977. auto end = std::chrono::high_resolution_clock::now();
  5978. auto elapsed =
  5979. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5980. .count();
  5981. // With Expect: 100-continue, request completes successfully but with error
  5982. EXPECT_TRUE(ret);
  5983. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5984. EXPECT_EQ("close", res.get_header_value("Connection"));
  5985. EXPECT_FALSE(cli_.is_socket_open());
  5986. EXPECT_LE(elapsed, 2000);
  5987. }
  5988. {
  5989. // Send an extra GET request to ensure error recovery without hanging
  5990. Request req;
  5991. req.method = "GET";
  5992. req.path = "/hi";
  5993. auto start = std::chrono::high_resolution_clock::now();
  5994. auto res = cli_.send(req);
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("Hello World!", res->body);
  6002. EXPECT_LE(elapsed, 500);
  6003. }
  6004. }
  6005. TEST(ZstdDecompressor, ChunkedDecompression) {
  6006. std::string data;
  6007. for (size_t i = 0; i < 32 * 1024; ++i) {
  6008. data.push_back(static_cast<char>('a' + i % 26));
  6009. }
  6010. std::string compressed_data;
  6011. {
  6012. httplib::detail::zstd_compressor compressor;
  6013. bool result = compressor.compress(
  6014. data.data(), data.size(),
  6015. /*last=*/true,
  6016. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6017. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6018. compressed_data_size);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(result);
  6022. }
  6023. std::string decompressed_data;
  6024. {
  6025. httplib::detail::zstd_decompressor decompressor;
  6026. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6027. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6028. size_t chunk_size = 130;
  6029. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6030. chunk_begin += chunk_size) {
  6031. size_t current_chunk_size =
  6032. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6033. bool result = decompressor.decompress(
  6034. compressed_data.data() + chunk_begin, current_chunk_size,
  6035. [&](const char *decompressed_data_chunk,
  6036. size_t decompressed_data_chunk_size) {
  6037. decompressed_data.insert(decompressed_data.size(),
  6038. decompressed_data_chunk,
  6039. decompressed_data_chunk_size);
  6040. return true;
  6041. });
  6042. ASSERT_TRUE(result);
  6043. }
  6044. }
  6045. ASSERT_EQ(data, decompressed_data);
  6046. }
  6047. TEST(ZstdDecompressor, Decompress) {
  6048. std::string original_text = "Compressed with ZSTD";
  6049. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6050. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6051. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6052. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6053. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6054. std::string decompressed_data;
  6055. {
  6056. httplib::detail::zstd_decompressor decompressor;
  6057. bool result = decompressor.decompress(
  6058. compressed_data.data(), compressed_data.size(),
  6059. [&](const char *decompressed_data_chunk,
  6060. size_t decompressed_data_chunk_size) {
  6061. decompressed_data.insert(decompressed_data.size(),
  6062. decompressed_data_chunk,
  6063. decompressed_data_chunk_size);
  6064. return true;
  6065. });
  6066. ASSERT_TRUE(result);
  6067. }
  6068. ASSERT_EQ(original_text, decompressed_data);
  6069. }
  6070. #endif
  6071. // Sends a raw request to a server listening at HOST:PORT.
  6072. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6073. std::string *resp = nullptr) {
  6074. auto error = Error::Success;
  6075. auto client_sock = detail::create_client_socket(
  6076. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6077. /*connection_timeout_sec=*/5, 0,
  6078. /*read_timeout_sec=*/5, 0,
  6079. /*write_timeout_sec=*/5, 0, std::string(), error);
  6080. if (client_sock == INVALID_SOCKET) { return false; }
  6081. auto ret = detail::process_client_socket(
  6082. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6083. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6084. if (req.size() !=
  6085. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6086. return false;
  6087. }
  6088. char buf[512];
  6089. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6090. while (line_reader.getline()) {
  6091. if (resp) { *resp += line_reader.ptr(); }
  6092. }
  6093. return true;
  6094. });
  6095. detail::close_socket(client_sock);
  6096. return ret;
  6097. }
  6098. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6099. Server svr;
  6100. std::string header_value;
  6101. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6102. header_value = req.get_header_value("foo");
  6103. res.set_content("ok", "text/plain");
  6104. });
  6105. thread t = thread([&] { svr.listen(HOST, PORT); });
  6106. auto se = detail::scope_exit([&] {
  6107. svr.stop();
  6108. t.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6113. // like characters are not treated the same - use vertical tab and escape.
  6114. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6115. "foo: \t \v bar \x1B\t \r\n"
  6116. "Connection: close\r\n"
  6117. "\r\n";
  6118. std::string res;
  6119. ASSERT_TRUE(send_request(5, req, &res));
  6120. EXPECT_EQ(header_value, "");
  6121. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6122. }
  6123. // Sends a raw request and verifies that there isn't a crash or exception.
  6124. static void test_raw_request(const std::string &req,
  6125. std::string *out = nullptr) {
  6126. Server svr;
  6127. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6128. res.set_content("ok", "text/plain");
  6129. });
  6130. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6131. res.set_content("ok", "text/plain");
  6132. });
  6133. svr.Get("/header_field_value_check",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("ok", "text/plain");
  6136. });
  6137. // Server read timeout must be longer than the client read timeout for the
  6138. // bug to reproduce, probably to force the server to process a request
  6139. // without a trailing blank line.
  6140. const time_t client_read_timeout_sec = 1;
  6141. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6142. bool listen_thread_ok = false;
  6143. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6144. auto se = detail::scope_exit([&] {
  6145. svr.stop();
  6146. t.join();
  6147. ASSERT_FALSE(svr.is_running());
  6148. EXPECT_TRUE(listen_thread_ok);
  6149. });
  6150. svr.wait_until_ready();
  6151. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6152. }
  6153. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6154. // A certain header line causes an exception if the header property is parsed
  6155. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6156. test_raw_request(
  6157. "GET /hi HTTP/1.1\r\n"
  6158. " : "
  6159. " "
  6160. " ");
  6161. }
  6162. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6163. // A certain header line causes an exception if the header property *name* is
  6164. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6165. // greedy matcher and requires backtracking when there are a lot of ":"
  6166. // characters.
  6167. // This occurs with libc++ but not libstdc++.
  6168. test_raw_request(
  6169. "GET /hi HTTP/1.1\r\n"
  6170. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6171. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6172. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6173. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6174. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6175. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6176. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6177. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6178. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6179. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6180. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6181. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6182. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6185. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6186. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6187. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6188. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6189. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6190. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6191. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6192. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6193. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6194. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6195. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6196. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6197. "&&&%%%");
  6198. }
  6199. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6200. // Make sure this doesn't crash the server.
  6201. // In a previous version of the header line regex, the "\r" rendered the line
  6202. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6203. // a new position where the leading white space ended and the field value
  6204. // began.
  6205. // The crash occurs with libc++ but not libstdc++.
  6206. test_raw_request("GET /hi HTTP/1.1\r\n"
  6207. "a:" +
  6208. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6209. "\r\n"
  6210. "\r\n");
  6211. }
  6212. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6213. std::string out;
  6214. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6215. "Content-Type: text/plain\r\n"
  6216. "Transfer-Encoding: chunked\r\n"
  6217. "\r\n"
  6218. "nothex\r\n",
  6219. &out);
  6220. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6221. }
  6222. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6223. std::string out;
  6224. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6225. "Content-Type: text/plain\r\n"
  6226. "Transfer-Encoding: chunked\r\n"
  6227. "\r\n"
  6228. "3\r\n"
  6229. "xyz\r\n"
  6230. "NaN\r\n",
  6231. &out);
  6232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6233. }
  6234. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6235. std::string out;
  6236. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6237. "Content-Type: text/plain\r\n"
  6238. "Transfer-Encoding: chunked\r\n"
  6239. "\r\n"
  6240. // Length is too large for 64 bits.
  6241. "1ffffffffffffffff\r\n"
  6242. "xyz\r\n",
  6243. &out);
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6247. test_raw_request("GET /hi HTTP/1.1\r\n"
  6248. "Content-Type: text/plain\r\n\r");
  6249. }
  6250. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6251. std::string out;
  6252. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6254. }
  6255. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6256. Server svr;
  6257. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6258. EXPECT_TRUE(!req.remote_addr.empty());
  6259. });
  6260. thread t = thread([&] { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. // Send an invalid request line to trigger Bad Request
  6268. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6269. std::string out;
  6270. ASSERT_TRUE(send_request(5, bad_req, &out));
  6271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6272. }
  6273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6274. std::string out;
  6275. std::string request(
  6276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6277. test_raw_request(request, &out);
  6278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6279. }
  6280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6281. std::string out;
  6282. std::string request(
  6283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6284. test_raw_request(request, &out);
  6285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6286. }
  6287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6288. std::string out;
  6289. std::string request(
  6290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6291. test_raw_request(request, &out);
  6292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6293. }
  6294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6295. std::string out;
  6296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6297. "Test: \r\n\r\n",
  6298. &out);
  6299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6300. }
  6301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6302. Server svr;
  6303. std::string x_custom;
  6304. std::string cookie;
  6305. std::string xff;
  6306. std::string x_unicode;
  6307. std::string x_iis;
  6308. svr.Get("/check", [&](const Request &req, Response &res) {
  6309. x_custom = req.get_header_value("X-Custom");
  6310. cookie = req.get_header_value("Cookie");
  6311. xff = req.get_header_value("X-Forwarded-For");
  6312. x_unicode = req.get_header_value("X-Unicode");
  6313. x_iis = req.get_header_value("X-IIS");
  6314. res.set_content("ok", "text/plain");
  6315. });
  6316. thread t = thread([&] { svr.listen(HOST, PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. t.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. const std::string req = "GET /check HTTP/1.1\r\n"
  6324. "Host: localhost\r\n"
  6325. "X-Custom: a%0D%0AInjected: b\r\n"
  6326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6328. "X-Unicode: %E3%81%82\r\n"
  6329. "X-IIS: %u00E9\r\n"
  6330. "Connection: close\r\n"
  6331. "\r\n";
  6332. std::string res;
  6333. ASSERT_TRUE(send_request(5, req, &res));
  6334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6335. // Every value must be returned verbatim (wire form), with no decoding.
  6336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6339. EXPECT_EQ("%E3%81%82", x_unicode);
  6340. EXPECT_EQ("%u00E9", x_iis);
  6341. }
  6342. // Applications that previously relied on automatic percent-decoding can
  6343. // reproduce the old behavior by explicitly calling decode_path_component()
  6344. // or, for RFC 3986 conformance, decode_uri_component().
  6345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6346. Server svr;
  6347. std::string decoded;
  6348. svr.Get("/check", [&](const Request &req, Response &res) {
  6349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6350. res.set_content("ok", "text/plain");
  6351. });
  6352. thread t = thread([&] { svr.listen(HOST, PORT); });
  6353. auto se = detail::scope_exit([&] {
  6354. svr.stop();
  6355. t.join();
  6356. ASSERT_FALSE(svr.is_running());
  6357. });
  6358. svr.wait_until_ready();
  6359. const std::string req = "GET /check HTTP/1.1\r\n"
  6360. "Host: localhost\r\n"
  6361. "X-Custom: hello%20world\r\n"
  6362. "Connection: close\r\n"
  6363. "\r\n";
  6364. std::string res;
  6365. ASSERT_TRUE(send_request(5, req, &res));
  6366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6367. EXPECT_EQ("hello world", decoded);
  6368. }
  6369. // Regression test for #2033. Browsers send Referer values that include
  6370. // percent-encoded characters such as %0A inside the URL. Decoding the
  6371. // header value would either trip the post-decode CR/LF/NUL guard (the
  6372. // original bug, returning 400) or, after that guard was relaxed, silently
  6373. // store a literal LF — both unacceptable. The wire form must round-trip.
  6374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6375. Server svr;
  6376. std::string referer;
  6377. svr.Get("/check", [&](const Request &req, Response &res) {
  6378. referer = req.get_header_value("Referer");
  6379. res.set_content("ok", "text/plain");
  6380. });
  6381. thread t = thread([&] { svr.listen(HOST, PORT); });
  6382. auto se = detail::scope_exit([&] {
  6383. svr.stop();
  6384. t.join();
  6385. ASSERT_FALSE(svr.is_running());
  6386. });
  6387. svr.wait_until_ready();
  6388. const std::string req = "GET /check HTTP/1.1\r\n"
  6389. "Host: localhost\r\n"
  6390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6391. "Connection: close\r\n"
  6392. "\r\n";
  6393. std::string res;
  6394. ASSERT_TRUE(send_request(5, req, &res));
  6395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6397. }
  6398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6399. Server svr;
  6400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6401. res.set_header("Cache-Control", "no-cache");
  6402. res.set_chunked_content_provider(
  6403. "text/event-stream", [](size_t offset, DataSink &sink) {
  6404. std::string s = "data:";
  6405. s += std::to_string(offset);
  6406. s += "\n\n";
  6407. auto ret = sink.write(s.data(), s.size());
  6408. EXPECT_TRUE(ret);
  6409. std::this_thread::sleep_for(std::chrono::seconds(1));
  6410. return true;
  6411. });
  6412. });
  6413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6414. svr.wait_until_ready();
  6415. Client client(HOST, PORT);
  6416. const Headers headers = {{"Accept", "text/event-stream"}};
  6417. auto get_thread = std::thread([&client, &headers]() {
  6418. auto res = client.Get(
  6419. "/events", headers,
  6420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6421. });
  6422. auto se = detail::scope_exit([&] {
  6423. svr.stop();
  6424. get_thread.join();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. // Give GET time to get a few messages.
  6429. std::this_thread::sleep_for(std::chrono::seconds(2));
  6430. }
  6431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6432. httplib::Server svr;
  6433. svr.Post("/hi",
  6434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6435. res.status = StatusCode::OK_200;
  6436. });
  6437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6438. svr.wait_until_ready();
  6439. Client cli(HOST, PORT);
  6440. auto res = cli.Post("/hi", "data", "text/plain");
  6441. ASSERT_TRUE(res);
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. svr.stop();
  6444. thread.join();
  6445. ASSERT_FALSE(svr.is_running());
  6446. res = cli.Post("/hi", "data", "text/plain");
  6447. ASSERT_FALSE(res);
  6448. }
  6449. TEST(ServerStopTest, ListenFailure) {
  6450. Server svr;
  6451. auto t = thread([&]() {
  6452. auto ret = svr.listen("????", PORT);
  6453. EXPECT_FALSE(ret);
  6454. });
  6455. svr.wait_until_ready();
  6456. svr.stop();
  6457. t.join();
  6458. }
  6459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6460. TEST(ServerStopTest, Decommision) {
  6461. Server svr;
  6462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6463. for (int i = 0; i < 4; i++) {
  6464. auto is_even = !(i % 2);
  6465. std::thread t{[&] {
  6466. try {
  6467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6468. if (is_even) {
  6469. throw std::runtime_error("Some thing that happens to go wrong.");
  6470. }
  6471. svr.listen(HOST, PORT);
  6472. } catch (...) { svr.decommission(); }
  6473. }};
  6474. svr.wait_until_ready();
  6475. // Server is up
  6476. {
  6477. Client cli(HOST, PORT);
  6478. auto res = cli.Get("/hi");
  6479. if (is_even) {
  6480. EXPECT_FALSE(res);
  6481. } else {
  6482. EXPECT_TRUE(res);
  6483. EXPECT_EQ("hi...", res->body);
  6484. }
  6485. }
  6486. svr.stop();
  6487. t.join();
  6488. // Server is down...
  6489. {
  6490. Client cli(HOST, PORT);
  6491. auto res = cli.Get("/hi");
  6492. EXPECT_FALSE(res);
  6493. }
  6494. }
  6495. }
  6496. #endif
  6497. // Helper function for string body upload progress tests
  6498. template <typename SetupHandler, typename ClientCall>
  6499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6500. ClientCall &&client_call,
  6501. const string &body) {
  6502. Server svr;
  6503. setup_handler(svr);
  6504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6505. auto se = detail::scope_exit([&] {
  6506. svr.stop();
  6507. t.join();
  6508. });
  6509. svr.wait_until_ready();
  6510. Client cli(HOST, PORT);
  6511. vector<uint64_t> progress_values;
  6512. bool progress_called = false;
  6513. auto res =
  6514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6515. progress_values.push_back(current);
  6516. progress_called = true;
  6517. return true;
  6518. });
  6519. ASSERT_TRUE(res);
  6520. EXPECT_EQ(200, res->status);
  6521. EXPECT_TRUE(progress_called);
  6522. }
  6523. TEST(UploadProgressTest, PostStringBodyBasic) {
  6524. TestStringBodyUploadProgress(
  6525. [](Server &svr) {
  6526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6527. res.set_content("received", "text/plain");
  6528. });
  6529. },
  6530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6531. return cli.Post("/test", body, "text/plain", progress_callback);
  6532. },
  6533. "test data for upload progress");
  6534. }
  6535. TEST(UploadProgressTest, PutStringBodyBasic) {
  6536. TestStringBodyUploadProgress(
  6537. [](Server &svr) {
  6538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6539. res.set_content("put received", "text/plain");
  6540. });
  6541. },
  6542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6543. return cli.Put("/test", body, "text/plain", progress_callback);
  6544. },
  6545. "put test data for upload progress");
  6546. }
  6547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6548. TestStringBodyUploadProgress(
  6549. [](Server &svr) {
  6550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6551. res.set_content("patch received", "text/plain");
  6552. });
  6553. },
  6554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6555. return cli.Patch("/test", body, "text/plain", progress_callback);
  6556. },
  6557. "patch test data for upload progress");
  6558. }
  6559. // Helper function for content provider upload progress tests
  6560. template <typename SetupHandler, typename ClientCall>
  6561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6562. ClientCall &&client_call) {
  6563. Server svr;
  6564. setup_handler(svr);
  6565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. });
  6570. svr.wait_until_ready();
  6571. Client cli(HOST, PORT);
  6572. vector<uint64_t> progress_values;
  6573. auto res =
  6574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6575. progress_values.push_back(current);
  6576. return true;
  6577. });
  6578. ASSERT_TRUE(res);
  6579. EXPECT_EQ(200, res->status);
  6580. EXPECT_FALSE(progress_values.empty());
  6581. }
  6582. TEST(UploadProgressTest, PostContentProviderProgress) {
  6583. TestContentProviderUploadProgress(
  6584. [](Server &svr) {
  6585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6586. res.set_content("provider received", "text/plain");
  6587. });
  6588. },
  6589. [](Client &cli, UploadProgress progress_callback) {
  6590. return cli.Post(
  6591. "/test", 10,
  6592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6593. sink.os << "test data";
  6594. return true;
  6595. },
  6596. "text/plain", progress_callback);
  6597. });
  6598. }
  6599. // Helper function for multipart upload progress tests
  6600. template <typename SetupHandler, typename ClientCall>
  6601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6602. ClientCall &&client_call,
  6603. const string &endpoint) {
  6604. Server svr;
  6605. setup_handler(svr);
  6606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. t.join();
  6610. });
  6611. svr.wait_until_ready();
  6612. Client cli(HOST, PORT);
  6613. vector<uint64_t> progress_values;
  6614. UploadFormDataItems items = {
  6615. {"field1", "value1", "", ""},
  6616. {"field2", "longer value for progress tracking test", "", ""},
  6617. {"file1", "file content data for upload progress", "test.txt",
  6618. "text/plain"}};
  6619. auto res = client_call(cli, endpoint, items,
  6620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6621. progress_values.push_back(current);
  6622. return true;
  6623. });
  6624. ASSERT_TRUE(res);
  6625. EXPECT_EQ(200, res->status);
  6626. EXPECT_FALSE(progress_values.empty());
  6627. }
  6628. TEST(UploadProgressTest, PostMultipartProgress) {
  6629. TestMultipartUploadProgress(
  6630. [](Server &svr) {
  6631. svr.Post("/multipart", [](const Request &req, Response &res) {
  6632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6633. res.set_content("multipart received", "text/plain");
  6634. });
  6635. },
  6636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6637. UploadProgress progress_callback) {
  6638. return cli.Post(endpoint, items, progress_callback);
  6639. },
  6640. "/multipart");
  6641. }
  6642. // Helper function for basic download progress tests
  6643. template <typename SetupHandler, typename ClientCall>
  6644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6645. ClientCall &&client_call, const string &endpoint,
  6646. size_t expected_content_size) {
  6647. Server svr;
  6648. setup_handler(svr);
  6649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6650. auto se = detail::scope_exit([&] {
  6651. svr.stop();
  6652. t.join();
  6653. });
  6654. svr.wait_until_ready();
  6655. Client cli(HOST, PORT);
  6656. vector<uint64_t> progress_values;
  6657. auto res = client_call(cli, endpoint,
  6658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6659. progress_values.push_back(current);
  6660. return true;
  6661. });
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ(200, res->status);
  6664. EXPECT_FALSE(progress_values.empty());
  6665. EXPECT_EQ(expected_content_size, res->body.size());
  6666. }
  6667. TEST(DownloadProgressTest, GetBasic) {
  6668. TestBasicDownloadProgress(
  6669. [](Server &svr) {
  6670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6671. string content(1000, 'D');
  6672. res.set_content(content, "text/plain");
  6673. });
  6674. },
  6675. [](Client &cli, const string &endpoint,
  6676. DownloadProgress progress_callback) {
  6677. return cli.Get(endpoint, progress_callback);
  6678. },
  6679. "/download", 1000u);
  6680. }
  6681. // Helper function for content receiver download progress tests
  6682. template <typename SetupHandler, typename ClientCall>
  6683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6684. ClientCall &&client_call,
  6685. const string &endpoint,
  6686. size_t expected_content_size) {
  6687. Server svr;
  6688. setup_handler(svr);
  6689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. t.join();
  6693. });
  6694. svr.wait_until_ready();
  6695. Client cli(HOST, PORT);
  6696. vector<uint64_t> progress_values;
  6697. string received_body;
  6698. auto res = client_call(
  6699. cli, endpoint,
  6700. [&](const char *data, size_t data_length) -> bool {
  6701. received_body.append(data, data_length);
  6702. return true;
  6703. },
  6704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6705. progress_values.push_back(current);
  6706. return true;
  6707. });
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ(200, res->status);
  6710. EXPECT_FALSE(progress_values.empty());
  6711. EXPECT_EQ(expected_content_size, received_body.size());
  6712. EXPECT_TRUE(res->body.empty());
  6713. }
  6714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6715. TestContentReceiverDownloadProgress(
  6716. [](Server &svr) {
  6717. svr.Get("/download-receiver",
  6718. [](const Request & /*req*/, Response &res) {
  6719. string content(2000, 'R');
  6720. res.set_content(content, "text/plain");
  6721. });
  6722. },
  6723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6724. DownloadProgress progress_callback) {
  6725. return cli.Get(endpoint, content_receiver, progress_callback);
  6726. },
  6727. "/download-receiver", 2000u);
  6728. }
  6729. TEST(StreamingTest, NoContentLengthStreaming) {
  6730. Server svr;
  6731. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6732. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6733. if (offset < 6) {
  6734. sink.os << (offset < 3 ? "a" : "b");
  6735. } else {
  6736. sink.done();
  6737. }
  6738. return true;
  6739. });
  6740. });
  6741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6742. auto listen_se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. listen_thread.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. });
  6747. svr.wait_until_ready();
  6748. Client client(HOST, PORT);
  6749. auto get_thread = std::thread([&client]() {
  6750. std::string s;
  6751. auto res =
  6752. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6753. s += std::string(data, len);
  6754. return true;
  6755. });
  6756. ASSERT_TRUE(res);
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("aaabbb", s);
  6759. });
  6760. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6761. // Give GET time to get a few messages.
  6762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6763. }
  6764. TEST(MountTest, Unmount) {
  6765. Server svr;
  6766. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6767. auto se = detail::scope_exit([&] {
  6768. svr.stop();
  6769. listen_thread.join();
  6770. ASSERT_FALSE(svr.is_running());
  6771. });
  6772. svr.wait_until_ready();
  6773. Client cli("localhost", PORT);
  6774. svr.set_mount_point("/mount2", "./www2");
  6775. auto res = cli.Get("/");
  6776. ASSERT_TRUE(res);
  6777. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6778. res = cli.Get("/mount2/dir/test.html");
  6779. ASSERT_TRUE(res);
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. svr.set_mount_point("/", "./www");
  6782. res = cli.Get("/dir/");
  6783. ASSERT_TRUE(res);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. svr.remove_mount_point("/");
  6786. res = cli.Get("/dir/");
  6787. ASSERT_TRUE(res);
  6788. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6789. svr.remove_mount_point("/mount2");
  6790. res = cli.Get("/mount2/dir/test.html");
  6791. ASSERT_TRUE(res);
  6792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6793. }
  6794. TEST(MountTest, Redicect) {
  6795. Server svr;
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.set_mount_point("/", "./www");
  6803. svr.wait_until_ready();
  6804. Client cli("localhost", PORT);
  6805. auto res = cli.Get("/dir/");
  6806. ASSERT_TRUE(res);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. res = cli.Get("/dir");
  6809. ASSERT_TRUE(res);
  6810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6811. res = cli.Get("/file");
  6812. ASSERT_TRUE(res);
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. res = cli.Get("/file/");
  6815. ASSERT_TRUE(res);
  6816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6817. cli.set_follow_location(true);
  6818. res = cli.Get("/dir");
  6819. ASSERT_TRUE(res);
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. }
  6822. TEST(MountTest, MultibytesPathName) {
  6823. Server svr;
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.set_mount_point("/", "./www");
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", PORT);
  6833. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6834. ASSERT_TRUE(res);
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6837. }
  6838. #ifdef _WIN32
  6839. // Issue #2435: mmap::open() must succeed even when another handle holds
  6840. // the file open for writing (e.g. an active log file).
  6841. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6842. const char *path = "mmap_concurrent_writer_test.txt";
  6843. const char *content = "hello";
  6844. {
  6845. std::ofstream f(path, std::ios::binary);
  6846. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6847. }
  6848. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6849. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6850. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6851. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6852. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6853. detail::mmap m(path);
  6854. ASSERT_TRUE(m.is_open());
  6855. EXPECT_EQ(strlen(content), m.size());
  6856. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6857. }
  6858. #endif
  6859. TEST(KeepAliveTest, ReadTimeout) {
  6860. Server svr;
  6861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6862. std::this_thread::sleep_for(std::chrono::seconds(2));
  6863. res.set_content("a", "text/plain");
  6864. });
  6865. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6866. res.set_content("b", "text/plain");
  6867. });
  6868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6869. auto se = detail::scope_exit([&] {
  6870. svr.stop();
  6871. listen_thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli("localhost", PORT);
  6876. cli.set_keep_alive(true);
  6877. cli.set_read_timeout(std::chrono::seconds(1));
  6878. auto resa = cli.Get("/a");
  6879. ASSERT_FALSE(resa);
  6880. EXPECT_EQ(Error::Read, resa.error());
  6881. auto resb = cli.Get("/b");
  6882. ASSERT_TRUE(resb);
  6883. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6884. EXPECT_EQ("b", resb->body);
  6885. }
  6886. TEST(KeepAliveTest, MaxCount) {
  6887. size_t keep_alive_max_count = 3;
  6888. Server svr;
  6889. svr.set_keep_alive_max_count(keep_alive_max_count);
  6890. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6891. res.set_content("Hello World!", "text/plain");
  6892. });
  6893. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6894. auto se = detail::scope_exit([&] {
  6895. svr.stop();
  6896. listen_thread.join();
  6897. ASSERT_FALSE(svr.is_running());
  6898. });
  6899. svr.wait_until_ready();
  6900. Client cli(HOST, PORT);
  6901. cli.set_keep_alive(true);
  6902. for (size_t i = 0; i < 5; i++) {
  6903. auto result = cli.Get("/hi");
  6904. ASSERT_TRUE(result);
  6905. EXPECT_EQ(StatusCode::OK_200, result->status);
  6906. if (i == keep_alive_max_count - 1) {
  6907. EXPECT_EQ("close", result->get_header_value("Connection"));
  6908. } else {
  6909. EXPECT_FALSE(result->has_header("Connection"));
  6910. }
  6911. }
  6912. }
  6913. TEST(KeepAliveTest, Issue1041) {
  6914. Server svr;
  6915. svr.set_keep_alive_timeout(3);
  6916. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6917. res.set_content("Hello World!", "text/plain");
  6918. });
  6919. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6920. auto se = detail::scope_exit([&] {
  6921. svr.stop();
  6922. listen_thread.join();
  6923. ASSERT_FALSE(svr.is_running());
  6924. });
  6925. svr.wait_until_ready();
  6926. Client cli(HOST, PORT);
  6927. cli.set_keep_alive(true);
  6928. auto result = cli.Get("/hi");
  6929. ASSERT_TRUE(result);
  6930. EXPECT_EQ(StatusCode::OK_200, result->status);
  6931. std::this_thread::sleep_for(std::chrono::seconds(5));
  6932. result = cli.Get("/hi");
  6933. ASSERT_TRUE(result);
  6934. EXPECT_EQ(StatusCode::OK_200, result->status);
  6935. }
  6936. TEST(KeepAliveTest, Issue1959) {
  6937. Server svr;
  6938. svr.set_keep_alive_timeout(5);
  6939. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6940. res.set_content("a", "text/plain");
  6941. });
  6942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6943. auto se = detail::scope_exit([&] {
  6944. if (!svr.is_running()) return;
  6945. svr.stop();
  6946. listen_thread.join();
  6947. ASSERT_FALSE(svr.is_running());
  6948. });
  6949. svr.wait_until_ready();
  6950. Client cli("localhost", PORT);
  6951. cli.set_keep_alive(true);
  6952. using namespace std::chrono;
  6953. auto start = steady_clock::now();
  6954. cli.Get("/a");
  6955. svr.stop();
  6956. listen_thread.join();
  6957. auto end = steady_clock::now();
  6958. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6959. EXPECT_LT(elapsed, 5000);
  6960. }
  6961. #ifdef CPPHTTPLIB_SSL_ENABLED
  6962. TEST(KeepAliveTest, SSLClientReconnection) {
  6963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6964. ASSERT_TRUE(svr.is_valid());
  6965. svr.set_keep_alive_timeout(1);
  6966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6967. res.set_content("Hello World!", "text/plain");
  6968. });
  6969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6970. auto se = detail::scope_exit([&] {
  6971. svr.stop();
  6972. listen_thread.join();
  6973. ASSERT_FALSE(svr.is_running());
  6974. });
  6975. svr.wait_until_ready();
  6976. SSLClient cli(HOST, PORT);
  6977. cli.enable_server_certificate_verification(false);
  6978. cli.set_keep_alive(true);
  6979. auto result = cli.Get("/hi");
  6980. ASSERT_TRUE(result);
  6981. EXPECT_EQ(StatusCode::OK_200, result->status);
  6982. result = cli.Get("/hi");
  6983. ASSERT_TRUE(result);
  6984. EXPECT_EQ(StatusCode::OK_200, result->status);
  6985. std::this_thread::sleep_for(std::chrono::seconds(2));
  6986. // Recoonect
  6987. result = cli.Get("/hi");
  6988. ASSERT_TRUE(result);
  6989. EXPECT_EQ(StatusCode::OK_200, result->status);
  6990. result = cli.Get("/hi");
  6991. ASSERT_TRUE(result);
  6992. EXPECT_EQ(StatusCode::OK_200, result->status);
  6993. }
  6994. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6996. ASSERT_TRUE(svr.is_valid());
  6997. svr.set_keep_alive_timeout(1);
  6998. std::string content = "reconnect";
  6999. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7000. res.set_content("Hello World!", "text/plain");
  7001. });
  7002. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7003. auto se = detail::scope_exit([&] {
  7004. svr.stop();
  7005. listen_thread.join();
  7006. ASSERT_FALSE(svr.is_running());
  7007. });
  7008. svr.wait_until_ready();
  7009. SSLClient cli(HOST, PORT);
  7010. cli.enable_server_certificate_verification(false);
  7011. cli.set_keep_alive(true);
  7012. auto result = cli.Post(
  7013. "/hi", content.size(),
  7014. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7015. sink.write(content.c_str(), content.size());
  7016. return true;
  7017. },
  7018. "text/plain");
  7019. ASSERT_TRUE(result);
  7020. EXPECT_EQ(200, result->status);
  7021. std::this_thread::sleep_for(std::chrono::seconds(2));
  7022. // Recoonect
  7023. result = cli.Post(
  7024. "/hi", content.size(),
  7025. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7026. sink.write(content.c_str(), content.size());
  7027. return true;
  7028. },
  7029. "text/plain");
  7030. ASSERT_TRUE(result);
  7031. EXPECT_EQ(200, result->status);
  7032. result = cli.Post(
  7033. "/hi", content.size(),
  7034. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7035. sink.write(content.c_str(), content.size());
  7036. return true;
  7037. },
  7038. "text/plain");
  7039. ASSERT_TRUE(result);
  7040. EXPECT_EQ(200, result->status);
  7041. }
  7042. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7043. using namespace httplib::tls;
  7044. {
  7045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7046. ASSERT_TRUE(svr.is_valid());
  7047. svr.Get("/sni", [&](const Request &req, Response &res) {
  7048. std::string expected = req.sni();
  7049. EXPECT_EQ(expected, req.get_param_value("expected"));
  7050. res.set_content("ok", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. {
  7060. SSLClient cli("localhost", PORT);
  7061. cli.enable_server_certificate_verification(false);
  7062. auto res = cli.Get("/sni?expected=localhost");
  7063. ASSERT_TRUE(res);
  7064. }
  7065. {
  7066. SSLClient cli("::1", PORT);
  7067. cli.enable_server_certificate_verification(false);
  7068. auto res = cli.Get("/sni?expected=");
  7069. // NOTE: This may fail if the server is listening on IPv4 only
  7070. // (e.g., when localhost resolves to 127.0.0.1 only)
  7071. if (res) {
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. } else {
  7074. EXPECT_EQ(Error::Connection, res.error());
  7075. }
  7076. }
  7077. }
  7078. }
  7079. #endif
  7080. TEST(ClientProblemDetectionTest, ContentProvider) {
  7081. Server svr;
  7082. size_t content_length = 1024 * 1024;
  7083. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7084. res.set_content_provider(
  7085. content_length, "text/plain",
  7086. [&](size_t offset, size_t length, DataSink &sink) {
  7087. auto out_len = std::min(length, static_cast<size_t>(1024));
  7088. std::string out(out_len, '@');
  7089. sink.write(out.data(), out_len);
  7090. return offset < 4096;
  7091. },
  7092. [](bool success) { ASSERT_FALSE(success); });
  7093. });
  7094. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7095. res.set_content_provider(
  7096. 0, "text/plain",
  7097. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7098. EXPECT_TRUE(false);
  7099. return true;
  7100. },
  7101. [](bool success) { ASSERT_FALSE(success); });
  7102. });
  7103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7104. auto se = detail::scope_exit([&] {
  7105. svr.stop();
  7106. listen_thread.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. svr.wait_until_ready();
  7110. Client cli("localhost", PORT);
  7111. {
  7112. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7113. size_t /*data_length*/) { return false; });
  7114. ASSERT_FALSE(res);
  7115. }
  7116. {
  7117. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7118. size_t /*data_length*/) { return false; });
  7119. ASSERT_TRUE(res);
  7120. }
  7121. }
  7122. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7123. Server svr;
  7124. svr.set_error_handler([](Request const &, Response &res) -> void {
  7125. res.set_chunked_content_provider(
  7126. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7127. sink.os << "hello";
  7128. sink.os << "world";
  7129. sink.done();
  7130. return true;
  7131. });
  7132. });
  7133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. listen_thread.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli("localhost", PORT);
  7141. auto res = cli.Get("/");
  7142. ASSERT_TRUE(res);
  7143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7144. EXPECT_EQ("helloworld", res->body);
  7145. }
  7146. TEST(LongPollingTest, ClientCloseDetection) {
  7147. Server svr;
  7148. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7149. res.set_chunked_content_provider(
  7150. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7151. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7152. sink.os << "hello";
  7153. auto count = 10;
  7154. while (count > 0 && sink.is_writable()) {
  7155. this_thread::sleep_for(chrono::milliseconds(10));
  7156. count--;
  7157. }
  7158. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7159. return true;
  7160. });
  7161. });
  7162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. listen_thread.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. Client cli("localhost", PORT);
  7170. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7171. EXPECT_EQ("hello", string(data, data_length));
  7172. return false; // close the socket immediately.
  7173. });
  7174. ASSERT_FALSE(res);
  7175. }
  7176. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7177. Server svr;
  7178. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7179. res.set_chunked_content_provider(
  7180. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7181. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7182. sink.os << "hello";
  7183. EXPECT_TRUE(sink.os.good());
  7184. // Wait for the client to close the connection
  7185. auto count = 10;
  7186. while (count > 0 && sink.is_writable()) {
  7187. this_thread::sleep_for(chrono::milliseconds(10));
  7188. count--;
  7189. }
  7190. // After client disconnect, write repeatedly until the socket
  7191. // write actually fails (small writes may be absorbed by the
  7192. // kernel buffer)
  7193. std::string chunk(1024, 'x');
  7194. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7195. sink.os << chunk;
  7196. }
  7197. EXPECT_TRUE(sink.os.fail());
  7198. return true;
  7199. });
  7200. });
  7201. auto port = svr.bind_to_any_port("localhost");
  7202. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7203. auto se = detail::scope_exit([&] {
  7204. svr.stop();
  7205. listen_thread.join();
  7206. ASSERT_FALSE(svr.is_running());
  7207. });
  7208. svr.wait_until_ready();
  7209. Client cli("localhost", port);
  7210. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7211. EXPECT_EQ("hello", string(data, data_length));
  7212. return false; // close the socket immediately.
  7213. });
  7214. ASSERT_FALSE(res);
  7215. }
  7216. TEST(GetWithParametersTest, GetWithParameters) {
  7217. Server svr;
  7218. svr.Get("/", [&](const Request &req, Response &) {
  7219. EXPECT_EQ("world", req.get_param_value("hello"));
  7220. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7221. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7222. });
  7223. svr.Get("/params", [&](const Request &req, Response &) {
  7224. EXPECT_EQ("world", req.get_param_value("hello"));
  7225. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7226. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7227. });
  7228. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7229. EXPECT_EQ("resource-id", req.matches[1]);
  7230. EXPECT_EQ("foo", req.get_param_value("param1"));
  7231. EXPECT_EQ("bar", req.get_param_value("param2"));
  7232. });
  7233. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7234. EXPECT_EQ("user-id", req.path_params.at("id"));
  7235. EXPECT_EQ("foo", req.get_param_value("param1"));
  7236. EXPECT_EQ("bar", req.get_param_value("param2"));
  7237. });
  7238. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7239. auto se = detail::scope_exit([&] {
  7240. svr.stop();
  7241. listen_thread.join();
  7242. ASSERT_FALSE(svr.is_running());
  7243. });
  7244. svr.wait_until_ready();
  7245. {
  7246. Client cli(HOST, PORT);
  7247. Params params;
  7248. params.emplace("hello", "world");
  7249. params.emplace("hello2", "world2");
  7250. params.emplace("hello3", "world3");
  7251. auto res = cli.Get("/", params, Headers{});
  7252. ASSERT_TRUE(res);
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. }
  7255. {
  7256. Client cli(HOST, PORT);
  7257. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7258. ASSERT_TRUE(res);
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. }
  7261. {
  7262. Client cli(HOST, PORT);
  7263. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7264. ASSERT_TRUE(res);
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. {
  7268. Client cli(HOST, PORT);
  7269. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7270. ASSERT_TRUE(res);
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. }
  7274. TEST(GetWithParametersTest, GetWithParameters2) {
  7275. Server svr;
  7276. svr.Get("/", [&](const Request &req, Response &res) {
  7277. auto text = req.get_param_value("hello");
  7278. res.set_content(text, "text/plain");
  7279. });
  7280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. listen_thread.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. Client cli("localhost", PORT);
  7288. Params params;
  7289. params.emplace("hello", "world");
  7290. std::string body;
  7291. auto res = cli.Get("/", params, Headers{},
  7292. [&](const char *data, size_t data_length) {
  7293. body.append(data, data_length);
  7294. return true;
  7295. });
  7296. ASSERT_TRUE(res);
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ("world", body);
  7299. }
  7300. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7301. auto host = "httpbingo.org";
  7302. auto path = std::string{"/range/32"};
  7303. #ifdef CPPHTTPLIB_SSL_ENABLED
  7304. SSLClient cli(host);
  7305. #else
  7306. Client cli(host);
  7307. #endif
  7308. cli.set_default_headers({make_range_header({{1, 10}})});
  7309. cli.set_connection_timeout(5);
  7310. {
  7311. auto res = cli.Get(path);
  7312. ASSERT_TRUE(res);
  7313. EXPECT_EQ("bcdefghijk", res->body);
  7314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7315. }
  7316. {
  7317. auto res = cli.Get(path);
  7318. ASSERT_TRUE(res);
  7319. EXPECT_EQ("bcdefghijk", res->body);
  7320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7321. }
  7322. }
  7323. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7324. Server svr;
  7325. svr.set_default_headers({{"Hello", "World"}});
  7326. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7327. res.set_content("ok", "text/plain");
  7328. });
  7329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7330. auto se = detail::scope_exit([&] {
  7331. svr.stop();
  7332. listen_thread.join();
  7333. ASSERT_FALSE(svr.is_running());
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli("localhost", PORT);
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. EXPECT_EQ("ok", res->body);
  7341. EXPECT_EQ("World", res->get_header_value("Hello"));
  7342. }
  7343. #ifdef CPPHTTPLIB_SSL_ENABLED
  7344. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7346. ASSERT_TRUE(svr.is_valid());
  7347. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7348. std::this_thread::sleep_for(std::chrono::seconds(2));
  7349. res.set_content("a", "text/plain");
  7350. });
  7351. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7352. res.set_content("b", "text/plain");
  7353. });
  7354. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. listen_thread.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. });
  7360. svr.wait_until_ready();
  7361. SSLClient cli("localhost", PORT);
  7362. cli.enable_server_certificate_verification(false);
  7363. cli.set_keep_alive(true);
  7364. cli.set_read_timeout(std::chrono::seconds(1));
  7365. auto resa = cli.Get("/a");
  7366. ASSERT_TRUE(!resa);
  7367. EXPECT_EQ(Error::Read, resa.error());
  7368. auto resb = cli.Get("/b");
  7369. ASSERT_TRUE(resb);
  7370. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7371. EXPECT_EQ("b", resb->body);
  7372. }
  7373. #endif
  7374. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7375. protected:
  7376. ServerTestWithAI_PASSIVE()
  7377. : cli_(HOST, PORT)
  7378. #ifdef CPPHTTPLIB_SSL_ENABLED
  7379. ,
  7380. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7381. #endif
  7382. {
  7383. #ifdef CPPHTTPLIB_SSL_ENABLED
  7384. cli_.enable_server_certificate_verification(false);
  7385. #endif
  7386. }
  7387. virtual void SetUp() {
  7388. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7389. res.set_content("Hello World!", "text/plain");
  7390. });
  7391. t_ = thread(
  7392. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7393. svr_.wait_until_ready();
  7394. }
  7395. virtual void TearDown() {
  7396. svr_.stop();
  7397. t_.join();
  7398. }
  7399. #ifdef CPPHTTPLIB_SSL_ENABLED
  7400. SSLClient cli_;
  7401. SSLServer svr_;
  7402. #else
  7403. Client cli_;
  7404. Server svr_;
  7405. #endif
  7406. thread t_;
  7407. };
  7408. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7409. auto res = cli_.Get("/hi");
  7410. ASSERT_TRUE(res);
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7413. EXPECT_EQ("Hello World!", res->body);
  7414. }
  7415. class ServerUpDownTest : public ::testing::Test {
  7416. protected:
  7417. ServerUpDownTest() : cli_(HOST, PORT) {}
  7418. virtual void SetUp() {
  7419. t_ = thread([&]() {
  7420. svr_.bind_to_any_port(HOST);
  7421. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7422. ASSERT_TRUE(svr_.listen_after_bind());
  7423. });
  7424. svr_.wait_until_ready();
  7425. }
  7426. virtual void TearDown() {
  7427. svr_.stop();
  7428. t_.join();
  7429. }
  7430. Client cli_;
  7431. Server svr_;
  7432. thread t_;
  7433. };
  7434. TEST_F(ServerUpDownTest, QuickStartStop) {
  7435. // Should not crash, especially when run with
  7436. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7437. }
  7438. class PayloadMaxLengthTest : public ::testing::Test {
  7439. protected:
  7440. PayloadMaxLengthTest()
  7441. : cli_(HOST, PORT)
  7442. #ifdef CPPHTTPLIB_SSL_ENABLED
  7443. ,
  7444. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7445. #endif
  7446. {
  7447. #ifdef CPPHTTPLIB_SSL_ENABLED
  7448. cli_.enable_server_certificate_verification(false);
  7449. #endif
  7450. }
  7451. virtual void SetUp() {
  7452. svr_.set_payload_max_length(8);
  7453. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7454. res.set_content("test", "text/plain");
  7455. });
  7456. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7457. svr_.wait_until_ready();
  7458. }
  7459. virtual void TearDown() {
  7460. svr_.stop();
  7461. t_.join();
  7462. }
  7463. #ifdef CPPHTTPLIB_SSL_ENABLED
  7464. SSLClient cli_;
  7465. SSLServer svr_;
  7466. #else
  7467. Client cli_;
  7468. Server svr_;
  7469. #endif
  7470. thread t_;
  7471. };
  7472. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7473. auto res = cli_.Post("/test", "123456789", "text/plain");
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7476. res = cli_.Post("/test", "12345678", "text/plain");
  7477. ASSERT_TRUE(res);
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. }
  7480. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7481. // Test chunked encoding with payload exceeding the 8-byte limit
  7482. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7483. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7484. ASSERT_TRUE(res);
  7485. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7486. }
  7487. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7488. // Test chunked encoding with payload within the 8-byte limit
  7489. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7490. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7491. ASSERT_TRUE(res);
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. }
  7494. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7495. // Test using send_request to send chunked data exceeding payload limit
  7496. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7497. "Host: " +
  7498. std::string(HOST) + ":" + std::to_string(PORT) +
  7499. "\r\n"
  7500. "Transfer-Encoding: chunked\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n"
  7503. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7504. "0123456789\r\n"
  7505. "0\r\n" // End chunk
  7506. "\r\n";
  7507. std::string response;
  7508. bool result = send_request(1, chunked_request, &response);
  7509. if (!result) {
  7510. // If send_request fails, it might be because the server closed the
  7511. // connection due to payload limit enforcement, which is acceptable
  7512. SUCCEED()
  7513. << "Server rejected oversized chunked request (connection closed)";
  7514. } else {
  7515. // If we got a response, check if it's an error response or connection was
  7516. // closed early Short response length indicates connection was closed due to
  7517. // payload limit
  7518. if (response.length() <= 10) {
  7519. SUCCEED() << "Server closed connection for oversized chunked request";
  7520. } else {
  7521. // Check for error status codes
  7522. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7523. response.find("Payload Too Large") != std::string::npos ||
  7524. response.find("400") != std::string::npos);
  7525. }
  7526. }
  7527. }
  7528. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7529. // Test request without Content-Length header exceeding payload limit
  7530. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7531. "Host: " +
  7532. std::string(HOST) + ":" +
  7533. std::to_string(PORT) +
  7534. "\r\n"
  7535. "Connection: close\r\n"
  7536. "\r\n";
  7537. // Add payload exceeding the 8-byte limit
  7538. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7539. request_without_content_length += large_payload;
  7540. std::string response;
  7541. bool result = send_request(1, request_without_content_length, &response);
  7542. if (!result) {
  7543. // If send_request fails, server likely closed connection due to payload
  7544. // limit
  7545. SUCCEED() << "Server rejected oversized request without Content-Length "
  7546. "(connection closed)";
  7547. } else {
  7548. // Check if server responded with error or closed connection early
  7549. if (response.length() <= 10) {
  7550. SUCCEED() << "Server closed connection for oversized request without "
  7551. "Content-Length";
  7552. } else {
  7553. // Check for error status codes
  7554. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7555. response.find("Payload Too Large") != std::string::npos ||
  7556. response.find("400") != std::string::npos);
  7557. }
  7558. }
  7559. }
  7560. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7561. // Test request without Content-Length header within payload limit
  7562. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7563. "Host: " +
  7564. std::string(HOST) + ":" +
  7565. std::to_string(PORT) +
  7566. "\r\n"
  7567. "Connection: close\r\n"
  7568. "\r\n";
  7569. // Add payload within the 8-byte limit
  7570. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7571. request_without_content_length += small_payload;
  7572. std::string response;
  7573. bool result = send_request(1, request_without_content_length, &response);
  7574. // For requests without Content-Length, the server may have different behavior
  7575. // The key is that it should not reject due to payload limit for small
  7576. // payloads
  7577. if (result) {
  7578. // Check for any HTTP response (success or error, but not connection closed)
  7579. if (response.length() > 10) {
  7580. SUCCEED()
  7581. << "Server processed request without Content-Length within limit";
  7582. } else {
  7583. // Short response might indicate connection closed, which is acceptable
  7584. SUCCEED() << "Server closed connection for request without "
  7585. "Content-Length (acceptable behavior)";
  7586. }
  7587. } else {
  7588. // Connection failure might be due to protocol requirements
  7589. SUCCEED() << "Connection issue with request without Content-Length "
  7590. "(environment-specific)";
  7591. }
  7592. }
  7593. class LargePayloadMaxLengthTest : public ::testing::Test {
  7594. protected:
  7595. LargePayloadMaxLengthTest()
  7596. : cli_(HOST, PORT)
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. ,
  7599. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7600. #endif
  7601. {
  7602. #ifdef CPPHTTPLIB_SSL_ENABLED
  7603. cli_.enable_server_certificate_verification(false);
  7604. #endif
  7605. }
  7606. virtual void SetUp() {
  7607. // Set 10MB payload limit
  7608. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7609. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7610. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7611. res.set_content("Large payload test", "text/plain");
  7612. });
  7613. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7614. svr_.wait_until_ready();
  7615. }
  7616. virtual void TearDown() {
  7617. svr_.stop();
  7618. t_.join();
  7619. }
  7620. #ifdef CPPHTTPLIB_SSL_ENABLED
  7621. SSLClient cli_;
  7622. SSLServer svr_;
  7623. #else
  7624. Client cli_;
  7625. Server svr_;
  7626. #endif
  7627. thread t_;
  7628. };
  7629. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7630. // Test chunked encoding with payload within 10MB limit
  7631. std::string medium_payload(5 * 1024 * 1024,
  7632. 'A'); // 5MB payload, within 10MB limit
  7633. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7634. ASSERT_TRUE(res);
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. }
  7637. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7638. // Test chunked encoding with payload exceeding 10MB limit
  7639. std::string large_payload(12 * 1024 * 1024,
  7640. 'B'); // 12MB payload, exceeds 10MB limit
  7641. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7642. // Server may either return 413 or close the connection
  7643. if (res) {
  7644. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7645. } else {
  7646. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7647. }
  7648. }
  7649. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7650. // Test request without Content-Length header within 10MB limit
  7651. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7652. "Host: " +
  7653. std::string(HOST) + ":" +
  7654. std::to_string(PORT) +
  7655. "\r\n"
  7656. "Connection: close\r\n"
  7657. "\r\n";
  7658. // Add 1MB payload (within 10MB limit)
  7659. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7660. request_without_content_length += medium_payload;
  7661. std::string response;
  7662. bool result = send_request(5, request_without_content_length, &response);
  7663. if (result) {
  7664. // Should get a proper HTTP response for payloads within limit
  7665. if (response.length() > 10) {
  7666. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7667. "10MB limit";
  7668. } else {
  7669. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7670. "Content-Length)";
  7671. }
  7672. } else {
  7673. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7674. }
  7675. }
  7676. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7677. // Test request without Content-Length header exceeding 10MB limit
  7678. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7679. "Host: " +
  7680. std::string(HOST) + ":" +
  7681. std::to_string(PORT) +
  7682. "\r\n"
  7683. "Connection: close\r\n"
  7684. "\r\n";
  7685. // Add 12MB payload (exceeds 10MB limit)
  7686. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7687. request_without_content_length += large_payload;
  7688. std::string response;
  7689. bool result = send_request(10, request_without_content_length, &response);
  7690. if (!result) {
  7691. // Server should close connection due to payload limit
  7692. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7693. "(connection closed)";
  7694. } else {
  7695. // Check for error response
  7696. if (response.length() <= 10) {
  7697. SUCCEED()
  7698. << "Server closed connection for 12MB request exceeding 10MB limit";
  7699. } else {
  7700. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7701. response.find("Payload Too Large") != std::string::npos ||
  7702. response.find("400") != std::string::npos);
  7703. }
  7704. }
  7705. }
  7706. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7707. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7708. // path.
  7709. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7710. Server svr;
  7711. const size_t LIMIT = 64 * 1024; // 64KB
  7712. svr.set_payload_max_length(LIMIT);
  7713. size_t total = 0;
  7714. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7715. const ContentReader &content_reader) {
  7716. content_reader([&](const char * /*data*/, size_t len) {
  7717. total += len;
  7718. return true;
  7719. });
  7720. res.status = 200;
  7721. res.set_content("stream_ok", "text/plain");
  7722. });
  7723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7724. auto se = detail::scope_exit([&] {
  7725. svr.stop();
  7726. thread.join();
  7727. ASSERT_FALSE(svr.is_running());
  7728. });
  7729. svr.wait_until_ready();
  7730. // Prepare 256KB raw data and gzip-compress it
  7731. std::string raw(256 * 1024, 'A');
  7732. std::string gz;
  7733. {
  7734. z_stream zs{};
  7735. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7736. Z_DEFAULT_STRATEGY);
  7737. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7738. zs.avail_in = static_cast<uInt>(raw.size());
  7739. char outbuf[4096];
  7740. int ret;
  7741. do {
  7742. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7743. zs.avail_out = sizeof(outbuf);
  7744. ret = deflate(&zs, Z_FINISH);
  7745. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7746. } while (ret != Z_STREAM_END);
  7747. deflateEnd(&zs);
  7748. }
  7749. Client cli(HOST, PORT);
  7750. cli.set_connection_timeout(std::chrono::seconds(5));
  7751. Headers headers = {{"Content-Encoding", "gzip"}};
  7752. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7753. "application/octet-stream");
  7754. ASSERT_TRUE(res);
  7755. // Server must reject oversized decompressed payloads with 413.
  7756. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7757. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7758. EXPECT_LE(total, LIMIT);
  7759. }
  7760. #endif
  7761. // Regression test for DoS vulnerability: a malicious server sending a response
  7762. // without Content-Length header must not cause unbounded memory consumption on
  7763. // the client side. The client should stop reading after a reasonable limit,
  7764. // similar to the server-side set_payload_max_length protection.
  7765. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7766. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7767. #ifndef _WIN32
  7768. signal(SIGPIPE, SIG_IGN);
  7769. #endif
  7770. auto server_thread = std::thread([] {
  7771. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7772. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7773. default_socket_options(srv);
  7774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7776. sockaddr_in addr{};
  7777. addr.sin_family = AF_INET;
  7778. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7779. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7780. int opt = 1;
  7781. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7782. #ifdef _WIN32
  7783. reinterpret_cast<const char *>(&opt),
  7784. #else
  7785. &opt,
  7786. #endif
  7787. sizeof(opt));
  7788. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7789. ::listen(srv, 1);
  7790. sockaddr_in cli_addr{};
  7791. socklen_t cli_len = sizeof(cli_addr);
  7792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7793. if (cli != INVALID_SOCKET) {
  7794. char buf[4096];
  7795. ::recv(cli, buf, sizeof(buf), 0);
  7796. // Malicious response: no Content-Length, no chunked encoding
  7797. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7798. "Connection: close\r\n"
  7799. "\r\n";
  7800. ::send(cli,
  7801. #ifdef _WIN32
  7802. static_cast<const char *>(response_header.c_str()),
  7803. static_cast<int>(response_header.size()),
  7804. #else
  7805. response_header.c_str(), response_header.size(),
  7806. #endif
  7807. 0);
  7808. // Send 10MB of data
  7809. std::string chunk(64 * 1024, 'A');
  7810. size_t total_sent = 0;
  7811. while (total_sent < MALICIOUS_DATA_SIZE) {
  7812. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7813. auto sent = ::send(cli,
  7814. #ifdef _WIN32
  7815. static_cast<const char *>(chunk.c_str()),
  7816. static_cast<int>(to_send),
  7817. #else
  7818. chunk.c_str(), to_send,
  7819. #endif
  7820. 0);
  7821. if (sent <= 0) break;
  7822. total_sent += static_cast<size_t>(sent);
  7823. }
  7824. detail::close_socket(cli);
  7825. }
  7826. detail::close_socket(srv);
  7827. });
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7829. size_t total_read = 0;
  7830. {
  7831. Client cli("127.0.0.1", PORT + 2);
  7832. cli.set_read_timeout(5, 0);
  7833. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7834. auto stream = cli.open_stream("GET", "/malicious");
  7835. ASSERT_TRUE(stream.is_valid());
  7836. char buffer[64 * 1024];
  7837. ssize_t n;
  7838. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7839. total_read += static_cast<size_t>(n);
  7840. }
  7841. } // StreamHandle and Client destroyed here, closing the socket
  7842. server_thread.join();
  7843. // With set_payload_max_length, the client must stop reading before consuming
  7844. // all 10MB. The read loop should be cut off at or near the configured limit.
  7845. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7846. << "Client read " << total_read << " bytes, exceeding the configured "
  7847. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7848. }
  7849. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7850. // the entire response body without truncation.
  7851. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7852. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7853. #ifndef _WIN32
  7854. signal(SIGPIPE, SIG_IGN);
  7855. #endif
  7856. auto server_thread = std::thread([] {
  7857. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7858. default_socket_options(srv);
  7859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7861. sockaddr_in addr{};
  7862. addr.sin_family = AF_INET;
  7863. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7864. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7865. int opt = 1;
  7866. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7867. #ifdef _WIN32
  7868. reinterpret_cast<const char *>(&opt),
  7869. #else
  7870. &opt,
  7871. #endif
  7872. sizeof(opt));
  7873. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7874. ::listen(srv, 1);
  7875. sockaddr_in cli_addr{};
  7876. socklen_t cli_len = sizeof(cli_addr);
  7877. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7878. if (cli != INVALID_SOCKET) {
  7879. char buf[4096];
  7880. ::recv(cli, buf, sizeof(buf), 0);
  7881. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7882. "Connection: close\r\n"
  7883. "\r\n";
  7884. ::send(cli,
  7885. #ifdef _WIN32
  7886. static_cast<const char *>(response_header.c_str()),
  7887. static_cast<int>(response_header.size()),
  7888. #else
  7889. response_header.c_str(), response_header.size(),
  7890. #endif
  7891. 0);
  7892. std::string chunk(64 * 1024, 'A');
  7893. size_t total_sent = 0;
  7894. while (total_sent < DATA_SIZE) {
  7895. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7896. auto sent = ::send(cli,
  7897. #ifdef _WIN32
  7898. static_cast<const char *>(chunk.c_str()),
  7899. static_cast<int>(to_send),
  7900. #else
  7901. chunk.c_str(), to_send,
  7902. #endif
  7903. 0);
  7904. if (sent <= 0) break;
  7905. total_sent += static_cast<size_t>(sent);
  7906. }
  7907. #ifdef _WIN32
  7908. ::shutdown(cli, SD_SEND);
  7909. #else
  7910. ::shutdown(cli, SHUT_WR);
  7911. #endif
  7912. // Drain until the client closes its end, ensuring all data is delivered
  7913. char drain[1024];
  7914. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7915. detail::close_socket(cli);
  7916. }
  7917. detail::close_socket(srv);
  7918. });
  7919. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7920. size_t total_read = 0;
  7921. {
  7922. Client cli("127.0.0.1", PORT + 2);
  7923. cli.set_read_timeout(5, 0);
  7924. cli.set_payload_max_length(0); // 0 means no limit
  7925. auto stream = cli.open_stream("GET", "/data");
  7926. ASSERT_TRUE(stream.is_valid());
  7927. char buffer[64 * 1024];
  7928. ssize_t n;
  7929. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7930. total_read += static_cast<size_t>(n);
  7931. }
  7932. }
  7933. server_thread.join();
  7934. EXPECT_EQ(total_read, DATA_SIZE)
  7935. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7936. << " bytes without truncation, but only read " << total_read << " bytes.";
  7937. }
  7938. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7939. // enormous Content-Length must not cause the client to pre-allocate a huge
  7940. // response body buffer. The reservation is capped at payload_max_length_, and
  7941. // the read itself fails when the body exceeds the limit.
  7942. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7943. #ifndef _WIN32
  7944. signal(SIGPIPE, SIG_IGN);
  7945. #endif
  7946. auto server_thread = std::thread([] {
  7947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7948. default_socket_options(srv);
  7949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7951. sockaddr_in addr{};
  7952. addr.sin_family = AF_INET;
  7953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7955. int opt = 1;
  7956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7957. #ifdef _WIN32
  7958. reinterpret_cast<const char *>(&opt),
  7959. #else
  7960. &opt,
  7961. #endif
  7962. sizeof(opt));
  7963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7964. ::listen(srv, 1);
  7965. sockaddr_in cli_addr{};
  7966. socklen_t cli_len = sizeof(cli_addr);
  7967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7968. if (cli != INVALID_SOCKET) {
  7969. char buf[4096];
  7970. ::recv(cli, buf, sizeof(buf), 0);
  7971. // Malicious response: claim a 20GB body but send only a tiny payload.
  7972. std::string response = "HTTP/1.1 200 OK\r\n"
  7973. "Content-Length: 20000000000\r\n"
  7974. "\r\n"
  7975. "abc";
  7976. ::send(cli,
  7977. #ifdef _WIN32
  7978. static_cast<const char *>(response.c_str()),
  7979. static_cast<int>(response.size()),
  7980. #else
  7981. response.c_str(), response.size(),
  7982. #endif
  7983. 0);
  7984. detail::close_socket(cli);
  7985. }
  7986. detail::close_socket(srv);
  7987. });
  7988. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7989. {
  7990. Client cli("127.0.0.1", PORT + 2);
  7991. cli.set_read_timeout(5, 0);
  7992. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  7993. // result in a 20GB pre-allocation. The Get() call is expected to fail
  7994. // (server claims more bytes than payload_max_length permits), but it must
  7995. // not exhaust memory before getting there.
  7996. auto res = cli.Get("/malicious");
  7997. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  7998. }
  7999. server_thread.join();
  8000. }
  8001. // Verify that content_receiver bypasses the default payload_max_length,
  8002. // allowing streaming downloads larger than 100MB without requiring an explicit
  8003. // set_payload_max_length call.
  8004. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8005. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8006. #ifndef _WIN32
  8007. signal(SIGPIPE, SIG_IGN);
  8008. #endif
  8009. auto server_thread = std::thread([] {
  8010. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8011. default_socket_options(srv);
  8012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8014. sockaddr_in addr{};
  8015. addr.sin_family = AF_INET;
  8016. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8017. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8018. int opt = 1;
  8019. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8020. #ifdef _WIN32
  8021. reinterpret_cast<const char *>(&opt),
  8022. #else
  8023. &opt,
  8024. #endif
  8025. sizeof(opt));
  8026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8027. ::listen(srv, 1);
  8028. sockaddr_in cli_addr{};
  8029. socklen_t cli_len = sizeof(cli_addr);
  8030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8031. if (cli != INVALID_SOCKET) {
  8032. char buf[4096];
  8033. ::recv(cli, buf, sizeof(buf), 0);
  8034. // Response with Content-Length larger than default 100MB limit
  8035. auto content_length = std::to_string(DATA_SIZE);
  8036. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8037. "Content-Length: " +
  8038. content_length +
  8039. "\r\n"
  8040. "Connection: close\r\n"
  8041. "\r\n";
  8042. ::send(cli,
  8043. #ifdef _WIN32
  8044. static_cast<const char *>(response_header.c_str()),
  8045. static_cast<int>(response_header.size()),
  8046. #else
  8047. response_header.c_str(), response_header.size(),
  8048. #endif
  8049. 0);
  8050. std::string chunk(64 * 1024, 'A');
  8051. size_t total_sent = 0;
  8052. while (total_sent < DATA_SIZE) {
  8053. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8054. auto sent = ::send(cli,
  8055. #ifdef _WIN32
  8056. static_cast<const char *>(chunk.c_str()),
  8057. static_cast<int>(to_send),
  8058. #else
  8059. chunk.c_str(), to_send,
  8060. #endif
  8061. 0);
  8062. if (sent <= 0) break;
  8063. total_sent += static_cast<size_t>(sent);
  8064. }
  8065. detail::close_socket(cli);
  8066. }
  8067. detail::close_socket(srv);
  8068. });
  8069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8070. size_t total_received = 0;
  8071. {
  8072. Client cli("127.0.0.1", PORT + 2);
  8073. cli.set_read_timeout(10, 0);
  8074. // Do NOT call set_payload_max_length — use the default 100MB limit
  8075. auto res =
  8076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8077. total_received += data_length;
  8078. return true;
  8079. });
  8080. ASSERT_TRUE(res);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. server_thread.join();
  8084. EXPECT_EQ(total_received, DATA_SIZE)
  8085. << "With content_receiver, the client should read all " << DATA_SIZE
  8086. << " bytes despite the default 100MB payload_max_length, but only read "
  8087. << total_received << " bytes.";
  8088. }
  8089. // Verify that an explicit set_payload_max_length smaller than the response is
  8090. // enforced even when a content_receiver is used.
  8091. TEST(ClientVulnerabilityTest,
  8092. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8093. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8094. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8095. #ifndef _WIN32
  8096. signal(SIGPIPE, SIG_IGN);
  8097. #endif
  8098. auto server_thread = std::thread([] {
  8099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8100. default_socket_options(srv);
  8101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8103. sockaddr_in addr{};
  8104. addr.sin_family = AF_INET;
  8105. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8107. int opt = 1;
  8108. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8109. #ifdef _WIN32
  8110. reinterpret_cast<const char *>(&opt),
  8111. #else
  8112. &opt,
  8113. #endif
  8114. sizeof(opt));
  8115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8116. ::listen(srv, 1);
  8117. sockaddr_in cli_addr{};
  8118. socklen_t cli_len = sizeof(cli_addr);
  8119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8120. if (cli != INVALID_SOCKET) {
  8121. char buf[4096];
  8122. ::recv(cli, buf, sizeof(buf), 0);
  8123. auto content_length = std::to_string(DATA_SIZE);
  8124. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8125. "Content-Length: " +
  8126. content_length +
  8127. "\r\n"
  8128. "Connection: close\r\n"
  8129. "\r\n";
  8130. ::send(cli,
  8131. #ifdef _WIN32
  8132. static_cast<const char *>(response_header.c_str()),
  8133. static_cast<int>(response_header.size()),
  8134. #else
  8135. response_header.c_str(), response_header.size(),
  8136. #endif
  8137. 0);
  8138. std::string chunk(64 * 1024, 'A');
  8139. size_t total_sent = 0;
  8140. while (total_sent < DATA_SIZE) {
  8141. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8142. auto sent = ::send(cli,
  8143. #ifdef _WIN32
  8144. static_cast<const char *>(chunk.c_str()),
  8145. static_cast<int>(to_send),
  8146. #else
  8147. chunk.c_str(), to_send,
  8148. #endif
  8149. 0);
  8150. if (sent <= 0) break;
  8151. total_sent += static_cast<size_t>(sent);
  8152. }
  8153. detail::close_socket(cli);
  8154. }
  8155. detail::close_socket(srv);
  8156. });
  8157. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8158. size_t total_received = 0;
  8159. {
  8160. Client cli("127.0.0.1", PORT + 2);
  8161. cli.set_read_timeout(10, 0);
  8162. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8163. auto res =
  8164. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8165. total_received += data_length;
  8166. return true;
  8167. });
  8168. // Should fail because 200MB exceeds the explicit 150MB limit
  8169. EXPECT_FALSE(res);
  8170. }
  8171. server_thread.join();
  8172. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8173. << "Client with content_receiver should respect the explicit "
  8174. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8175. << total_received << " bytes.";
  8176. }
  8177. // Verify that an explicit set_payload_max_length larger than the response
  8178. // allows the content_receiver to read all data successfully.
  8179. TEST(ClientVulnerabilityTest,
  8180. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8181. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8182. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8183. #ifndef _WIN32
  8184. signal(SIGPIPE, SIG_IGN);
  8185. #endif
  8186. auto server_thread = std::thread([] {
  8187. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8188. default_socket_options(srv);
  8189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8191. sockaddr_in addr{};
  8192. addr.sin_family = AF_INET;
  8193. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8194. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8195. int opt = 1;
  8196. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8197. #ifdef _WIN32
  8198. reinterpret_cast<const char *>(&opt),
  8199. #else
  8200. &opt,
  8201. #endif
  8202. sizeof(opt));
  8203. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8204. ::listen(srv, 1);
  8205. sockaddr_in cli_addr{};
  8206. socklen_t cli_len = sizeof(cli_addr);
  8207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8208. if (cli != INVALID_SOCKET) {
  8209. char buf[4096];
  8210. ::recv(cli, buf, sizeof(buf), 0);
  8211. auto content_length = std::to_string(DATA_SIZE);
  8212. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8213. "Content-Length: " +
  8214. content_length +
  8215. "\r\n"
  8216. "Connection: close\r\n"
  8217. "\r\n";
  8218. ::send(cli,
  8219. #ifdef _WIN32
  8220. static_cast<const char *>(response_header.c_str()),
  8221. static_cast<int>(response_header.size()),
  8222. #else
  8223. response_header.c_str(), response_header.size(),
  8224. #endif
  8225. 0);
  8226. std::string chunk(64 * 1024, 'A');
  8227. size_t total_sent = 0;
  8228. while (total_sent < DATA_SIZE) {
  8229. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8230. auto sent = ::send(cli,
  8231. #ifdef _WIN32
  8232. static_cast<const char *>(chunk.c_str()),
  8233. static_cast<int>(to_send),
  8234. #else
  8235. chunk.c_str(), to_send,
  8236. #endif
  8237. 0);
  8238. if (sent <= 0) break;
  8239. total_sent += static_cast<size_t>(sent);
  8240. }
  8241. #ifdef _WIN32
  8242. ::shutdown(cli, SD_SEND);
  8243. #else
  8244. ::shutdown(cli, SHUT_WR);
  8245. #endif
  8246. char drain[1024];
  8247. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8248. detail::close_socket(cli);
  8249. }
  8250. detail::close_socket(srv);
  8251. });
  8252. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8253. size_t total_received = 0;
  8254. {
  8255. Client cli("127.0.0.1", PORT + 2);
  8256. cli.set_read_timeout(10, 0);
  8257. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8258. auto res =
  8259. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8260. total_received += data_length;
  8261. return true;
  8262. });
  8263. ASSERT_TRUE(res);
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. }
  8266. server_thread.join();
  8267. EXPECT_EQ(total_received, DATA_SIZE)
  8268. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8269. << " bytes (larger than " << DATA_SIZE
  8270. << " bytes response), content_receiver should read all data, but only "
  8271. "read "
  8272. << total_received << " bytes.";
  8273. }
  8274. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8275. // Regression test for "zip bomb" attack on the client side: a malicious server
  8276. // sends a small gzip-compressed response that decompresses to a huge payload.
  8277. // The client must enforce payload_max_length on the decompressed size.
  8278. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8279. constexpr size_t DECOMPRESSED_SIZE =
  8280. 10 * 1024 * 1024; // 10MB after decompression
  8281. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8282. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8283. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8284. std::string compressed;
  8285. {
  8286. httplib::detail::gzip_compressor compressor;
  8287. bool ok =
  8288. compressor.compress(uncompressed.data(), uncompressed.size(),
  8289. /*last=*/true, [&](const char *buf, size_t len) {
  8290. compressed.append(buf, len);
  8291. return true;
  8292. });
  8293. ASSERT_TRUE(ok);
  8294. }
  8295. // Sanity: compressed data should be much smaller than the decompressed size
  8296. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8297. #ifndef _WIN32
  8298. signal(SIGPIPE, SIG_IGN);
  8299. #endif
  8300. // Set up the listening socket in the main thread so the server is guaranteed
  8301. // to be ready before the client connects (eliminates race condition).
  8302. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8303. default_socket_options(srv);
  8304. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8305. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8306. sockaddr_in addr{};
  8307. addr.sin_family = AF_INET;
  8308. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8309. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8310. int opt = 1;
  8311. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8312. #ifdef _WIN32
  8313. reinterpret_cast<const char *>(&opt),
  8314. #else
  8315. &opt,
  8316. #endif
  8317. sizeof(opt));
  8318. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8319. ASSERT_EQ(0, ::listen(srv, 1));
  8320. auto server_thread = std::thread([&compressed, srv] {
  8321. sockaddr_in cli_addr{};
  8322. socklen_t cli_len = sizeof(cli_addr);
  8323. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8324. if (cli != INVALID_SOCKET) {
  8325. // Read the full HTTP request (until \r\n\r\n)
  8326. char buf[4096];
  8327. size_t total = 0;
  8328. while (total < sizeof(buf)) {
  8329. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8330. if (n <= 0) break;
  8331. total += static_cast<size_t>(n);
  8332. // Check for end of headers
  8333. if (total >= 4) {
  8334. std::string req(buf, total);
  8335. if (req.find("\r\n\r\n") != std::string::npos) break;
  8336. }
  8337. }
  8338. // Malicious response: gzip-compressed body, no Content-Length
  8339. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8340. "Content-Encoding: gzip\r\n"
  8341. "Connection: close\r\n"
  8342. "\r\n";
  8343. ::send(cli,
  8344. #ifdef _WIN32
  8345. static_cast<const char *>(response_header.c_str()),
  8346. static_cast<int>(response_header.size()),
  8347. #else
  8348. response_header.c_str(), response_header.size(),
  8349. #endif
  8350. 0);
  8351. // Send the compressed payload (small on the wire, huge when decompressed)
  8352. size_t total_sent = 0;
  8353. while (total_sent < compressed.size()) {
  8354. auto to_send = std::min(compressed.size() - total_sent,
  8355. static_cast<size_t>(64 * 1024));
  8356. auto sent =
  8357. ::send(cli,
  8358. #ifdef _WIN32
  8359. static_cast<const char *>(compressed.c_str() + total_sent),
  8360. static_cast<int>(to_send),
  8361. #else
  8362. compressed.c_str() + total_sent, to_send,
  8363. #endif
  8364. 0);
  8365. if (sent <= 0) break;
  8366. total_sent += static_cast<size_t>(sent);
  8367. }
  8368. detail::close_socket(cli);
  8369. }
  8370. });
  8371. auto se = detail::scope_exit([&] {
  8372. detail::close_socket(srv);
  8373. server_thread.join();
  8374. });
  8375. size_t total_decompressed = 0;
  8376. {
  8377. Client cli("127.0.0.1", PORT + 3);
  8378. cli.set_read_timeout(5, 0);
  8379. cli.set_decompress(true);
  8380. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8381. auto stream = cli.open_stream("GET", "/zipbomb");
  8382. ASSERT_TRUE(stream.is_valid());
  8383. char buffer[64 * 1024];
  8384. ssize_t n;
  8385. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8386. total_decompressed += static_cast<size_t>(n);
  8387. }
  8388. }
  8389. // The decompressed size must be capped by payload_max_length. Without
  8390. // protection, the client would decompress the full 10MB from a tiny
  8391. // compressed payload, enabling a zip bomb DoS attack.
  8392. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8393. << "Client decompressed " << total_decompressed
  8394. << " bytes from a gzip response. The decompressed size should be "
  8395. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8396. }
  8397. #endif
  8398. TEST(HostAndPortPropertiesTest, NoSSL) {
  8399. httplib::Client cli("www.google.com", 1234);
  8400. ASSERT_EQ("www.google.com", cli.host());
  8401. ASSERT_EQ(1234, cli.port());
  8402. }
  8403. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8404. httplib::Client cli("www.google.com:1234");
  8405. ASSERT_EQ("www.google.com", cli.host());
  8406. ASSERT_EQ(1234, cli.port());
  8407. }
  8408. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8409. // Port number that overflows int — should not crash, client becomes invalid
  8410. httplib::Client cli("http://www.google.com:99999999999999999999");
  8411. ASSERT_FALSE(cli.is_valid());
  8412. }
  8413. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8414. // Port 99999 exceeds valid range (1-65535) — should not crash
  8415. httplib::Client cli("http://www.google.com:99999");
  8416. ASSERT_FALSE(cli.is_valid());
  8417. }
  8418. #ifdef CPPHTTPLIB_SSL_ENABLED
  8419. TEST(HostAndPortPropertiesTest, SSL) {
  8420. httplib::SSLClient cli("www.google.com");
  8421. ASSERT_EQ("www.google.com", cli.host());
  8422. ASSERT_EQ(443, cli.port());
  8423. }
  8424. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8425. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8426. std::string cert;
  8427. read_file(CA_CERT_FILE, cert);
  8428. httplib::SSLClient httplib_client("www.google.com");
  8429. // Load CA store first time
  8430. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8431. // Load CA store second time (update)
  8432. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8433. // Verify client is still valid and can make connections
  8434. httplib_client.enable_server_certificate_verification(true);
  8435. auto res = httplib_client.Get("/");
  8436. ASSERT_TRUE(res);
  8437. // Google may return 200 or 301 depending on various factors
  8438. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8439. res->status == StatusCode::MovedPermanently_301);
  8440. }
  8441. TEST(SSLClientTest, ServerNameIndication_Online) {
  8442. auto host = "httpbingo.org";
  8443. auto path = std::string{"/get"};
  8444. SSLClient cli(host, 443);
  8445. auto res = cli.Get(path);
  8446. ASSERT_TRUE(res);
  8447. ASSERT_EQ(StatusCode::OK_200, res->status);
  8448. }
  8449. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8450. // Use a site that will cause SSL verification failure due to self-signed cert
  8451. SSLClient cli("self-signed.badssl.com", 443);
  8452. cli.enable_server_certificate_verification(true);
  8453. auto res = cli.Get("/");
  8454. ASSERT_TRUE(!res);
  8455. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8456. // Verify backend error is captured for SSLServerVerification
  8457. // This occurs when certificate verification fails
  8458. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8459. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8460. EXPECT_NE(0UL, res.ssl_backend_error());
  8461. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8462. // For OpenSSL, ssl_error is 0 for verification errors
  8463. EXPECT_EQ(0, res.ssl_error());
  8464. #if !defined(_WIN32) || \
  8465. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8466. // On non-Windows or when Windows Schannel is disabled, the error comes
  8467. // from OpenSSL's verification
  8468. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8469. res.ssl_backend_error());
  8470. #endif
  8471. #endif
  8472. }
  8473. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8474. // Use a site where hostname doesn't match the certificate
  8475. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8476. SSLClient cli("wrong.host.badssl.com", 443);
  8477. cli.enable_server_certificate_verification(true);
  8478. cli.enable_server_hostname_verification(true);
  8479. auto res = cli.Get("/");
  8480. ASSERT_TRUE(!res);
  8481. // The error type depends on when hostname verification occurs:
  8482. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8483. // - Mbed TLS: SSLServerVerification (during handshake)
  8484. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8485. res.error() == Error::SSLServerVerification);
  8486. // Verify backend error is captured for hostname verification failure
  8487. EXPECT_NE(0UL, res.ssl_backend_error());
  8488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8489. // For OpenSSL, ssl_error is 0 for verification errors
  8490. EXPECT_EQ(0, res.ssl_error());
  8491. #if !defined(_WIN32) || \
  8492. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8493. // On non-Windows or when Windows Schannel is disabled, the error comes
  8494. // from OpenSSL's hostname verification
  8495. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8496. res.ssl_backend_error());
  8497. #endif
  8498. #endif
  8499. }
  8500. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8501. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8502. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8503. SSLClient cli("www.google.com", 443);
  8504. cli.enable_server_certificate_verification(true);
  8505. auto res = cli.Get("/");
  8506. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8507. }
  8508. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8509. SSLClient cli("www.google.com", 443);
  8510. cli.enable_server_certificate_verification(true);
  8511. cli.enable_windows_certificate_verification(false);
  8512. auto res = cli.Get("/");
  8513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8514. }
  8515. #endif
  8516. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8517. Client cli("https://google.com");
  8518. auto res = cli.Get("/");
  8519. ASSERT_TRUE(res);
  8520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8521. }
  8522. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8523. SSLClient cli("google.com");
  8524. cli.set_ca_cert_path(CA_CERT_FILE);
  8525. auto res = cli.Get("/");
  8526. ASSERT_TRUE(res);
  8527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8528. }
  8529. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8530. SSLClient cli("google.com");
  8531. cli.enable_server_certificate_verification(true);
  8532. cli.set_ca_cert_path("hello");
  8533. auto res = cli.Get("/");
  8534. ASSERT_TRUE(!res);
  8535. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8536. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8537. // should be set
  8538. EXPECT_EQ(0, res.ssl_error());
  8539. // Verify backend error is captured for SSLLoadingCerts
  8540. // This error occurs when loading CA certificates fails
  8541. EXPECT_NE(0UL, res.ssl_backend_error());
  8542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8543. // OpenSSL specific error codes:
  8544. // > openssl errstr 0x80000002
  8545. // error:80000002:system library::No such file or directory
  8546. // > openssl errstr 0xA000126
  8547. // error:0A000126:SSL routines::unexpected eof while reading
  8548. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8549. res.ssl_backend_error() == 0xA000126);
  8550. #endif
  8551. }
  8552. TEST(SSLClientTest, ServerCertificateVerification4) {
  8553. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8554. ASSERT_TRUE(svr.is_valid());
  8555. svr.Get("/test", [&](const Request &, Response &res) {
  8556. res.set_content("test", "text/plain");
  8557. svr.stop();
  8558. ASSERT_TRUE(true);
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. t.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. SSLClient cli("127.0.0.1", PORT);
  8567. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8568. cli.enable_server_certificate_verification(true);
  8569. cli.set_connection_timeout(30);
  8570. auto res = cli.Get("/test");
  8571. ASSERT_TRUE(res);
  8572. ASSERT_EQ(StatusCode::OK_200, res->status);
  8573. }
  8574. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8575. std::string cert;
  8576. read_file(CA_CERT_FILE, cert);
  8577. SSLClient cli("google.com");
  8578. cli.load_ca_cert_store(cert.data(), cert.size());
  8579. const auto res = cli.Get("/");
  8580. ASSERT_TRUE(res);
  8581. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8582. }
  8583. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8584. // clang-format off
  8585. static constexpr char cert[] =
  8586. "GlobalSign Root CA\n"
  8587. "==================\n"
  8588. "-----BEGIN CERTIFICATE-----\n"
  8589. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8590. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8591. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8592. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8593. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8594. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8595. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8596. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8597. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8598. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8599. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8600. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8601. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8602. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8603. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8604. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8605. "-----END CERTIFICATE-----\n";
  8606. // clang-format on
  8607. SSLClient cli("google.com");
  8608. cli.load_ca_cert_store(cert, sizeof(cert));
  8609. const auto res = cli.Get("/");
  8610. ASSERT_TRUE(res);
  8611. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8612. }
  8613. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8614. SSLClient cli("www.youtube.com");
  8615. cli.set_ca_cert_path(CA_CERT_FILE);
  8616. cli.enable_server_certificate_verification(true);
  8617. cli.set_follow_location(true);
  8618. auto res = cli.Get("/");
  8619. ASSERT_TRUE(res);
  8620. ASSERT_EQ(StatusCode::OK_200, res->status);
  8621. }
  8622. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8623. SSLClient cli("wWw.YouTube.Com");
  8624. cli.set_ca_cert_path(CA_CERT_FILE);
  8625. cli.enable_server_certificate_verification(true);
  8626. cli.enable_server_hostname_verification(true);
  8627. cli.set_follow_location(true);
  8628. auto res = cli.Get("/");
  8629. ASSERT_TRUE(res);
  8630. ASSERT_EQ(StatusCode::OK_200, res->status);
  8631. }
  8632. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8633. SSLClient cli("gOoGlE.COm");
  8634. cli.enable_server_certificate_verification(true);
  8635. cli.enable_server_hostname_verification(true);
  8636. cli.set_follow_location(true);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res);
  8639. ASSERT_EQ(StatusCode::OK_200, res->status);
  8640. }
  8641. TEST(SSLClientTest, Issue2004_Online) {
  8642. Client client("https://google.com");
  8643. client.set_follow_location(true);
  8644. auto res = client.Get("/");
  8645. ASSERT_TRUE(res);
  8646. ASSERT_EQ(StatusCode::OK_200, res->status);
  8647. auto body = res->body;
  8648. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8649. }
  8650. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8651. // Create SSLClient with invalid cert/key to make is_valid() return false
  8652. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8653. "nonexistent_key.pem");
  8654. // is_valid() should be false due to cert loading failure
  8655. ASSERT_FALSE(cli.is_valid());
  8656. auto res = cli.Get("/");
  8657. ASSERT_FALSE(res);
  8658. EXPECT_EQ(Error::SSLConnection, res.error());
  8659. }
  8660. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8661. // Test for Issue #2251: SSL error not properly reported when client cert
  8662. // and key paths are swapped or mismatched
  8663. // This simulates the scenario where user accidentally swaps the cert and key
  8664. // files
  8665. // Using client cert file as private key and vice versa (completely wrong)
  8666. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8667. // Should fail validation due to cert/key mismatch
  8668. ASSERT_FALSE(cli.is_valid());
  8669. // Attempt to make a request should fail with proper error
  8670. auto res = cli.Get("/");
  8671. ASSERT_FALSE(res);
  8672. EXPECT_EQ(Error::SSLConnection, res.error());
  8673. // SSL error should be recorded in the Result object (this is the key fix for
  8674. // Issue #2251)
  8675. auto backend_error = res.ssl_backend_error();
  8676. EXPECT_NE(0u, backend_error);
  8677. }
  8678. // Tests cert/key mismatch detection at the TLS context level
  8679. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8680. // Test that using mismatched cert/key causes connection failure.
  8681. // We verify this at the SSLClient level rather than through internal
  8682. // TLS API functions.
  8683. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8684. cli.enable_server_certificate_verification(false);
  8685. cli.set_connection_timeout(2);
  8686. // The mismatch should cause a connection or handshake error
  8687. auto res = cli.Get("/test");
  8688. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8689. // Either way, the request should fail
  8690. EXPECT_FALSE(res);
  8691. }
  8692. #endif
  8693. #if 0
  8694. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8695. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8696. ASSERT_TRUE(cli != nullptr);
  8697. cli->set_address_family(AF_INET6);
  8698. cli->set_interface("en0");
  8699. auto res = cli->Get("/get");
  8700. ASSERT_TRUE(res);
  8701. ASSERT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. #endif
  8704. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8705. #ifdef CPPHTTPLIB_SSL_ENABLED
  8706. void ClientCertPresent(
  8707. const std::string &client_cert_file,
  8708. const std::string &client_private_key_file,
  8709. const std::string &client_encrypted_private_key_pass = std::string()) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8712. CLIENT_CA_CERT_DIR);
  8713. ASSERT_TRUE(svr.is_valid());
  8714. svr.Get("/test", [&](const Request &req, Response &res) {
  8715. res.set_content("test", "text/plain");
  8716. auto cert = req.peer_cert();
  8717. ASSERT_TRUE(static_cast<bool>(cert));
  8718. std::string common_name = cert.subject_cn();
  8719. EXPECT_EQ("Common Name", common_name);
  8720. });
  8721. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8722. auto se = detail::scope_exit([&] {
  8723. svr.stop();
  8724. t.join();
  8725. ASSERT_FALSE(svr.is_running());
  8726. });
  8727. svr.wait_until_ready();
  8728. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8729. client_encrypted_private_key_pass);
  8730. cli.enable_server_certificate_verification(false);
  8731. cli.set_connection_timeout(30);
  8732. auto res = cli.Get("/test");
  8733. ASSERT_TRUE(res);
  8734. ASSERT_EQ(StatusCode::OK_200, res->status);
  8735. }
  8736. TEST(SSLClientServerTest, ClientCertPresent) {
  8737. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8738. }
  8739. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8740. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8741. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8742. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8743. }
  8744. // PEM memory-based constructor tests (works with all TLS backends)
  8745. void PemMemoryClientCertPresent(
  8746. const std::string &client_cert_file,
  8747. const std::string &client_private_key_file,
  8748. const std::string &client_encrypted_private_key_pass = std::string()) {
  8749. // Read PEM files into memory
  8750. std::string server_cert_pem, server_key_pem;
  8751. std::string client_ca_pem;
  8752. std::string client_cert_pem, client_key_pem;
  8753. read_file(SERVER_CERT_FILE, server_cert_pem);
  8754. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8755. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8756. read_file(client_cert_file, client_cert_pem);
  8757. read_file(client_private_key_file, client_key_pem);
  8758. // Create server with PEM memory
  8759. SSLServer::PemMemory server_pem = {
  8760. server_cert_pem.c_str(),
  8761. server_cert_pem.size(),
  8762. server_key_pem.c_str(),
  8763. server_key_pem.size(),
  8764. client_ca_pem.c_str(),
  8765. client_ca_pem.size(),
  8766. nullptr // no password for server key
  8767. };
  8768. SSLServer svr(server_pem);
  8769. ASSERT_TRUE(svr.is_valid());
  8770. svr.Get("/test", [&](const Request &, Response &res) {
  8771. res.set_content("test", "text/plain");
  8772. });
  8773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8774. auto se = detail::scope_exit([&] {
  8775. svr.stop();
  8776. t.join();
  8777. ASSERT_FALSE(svr.is_running());
  8778. });
  8779. svr.wait_until_ready();
  8780. // Create client with PEM memory
  8781. const char *password = client_encrypted_private_key_pass.empty()
  8782. ? nullptr
  8783. : client_encrypted_private_key_pass.c_str();
  8784. SSLClient::PemMemory client_pem = {
  8785. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8786. client_key_pem.size(), password};
  8787. SSLClient cli(HOST, PORT, client_pem);
  8788. cli.enable_server_certificate_verification(false);
  8789. cli.set_connection_timeout(30);
  8790. auto res = cli.Get("/test");
  8791. ASSERT_TRUE(res);
  8792. ASSERT_EQ(StatusCode::OK_200, res->status);
  8793. }
  8794. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8795. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8796. }
  8797. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8798. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8799. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8800. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8801. }
  8802. TEST(SSLClientServerTest, ClientCertMissing) {
  8803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8804. CLIENT_CA_CERT_DIR);
  8805. ASSERT_TRUE(svr.is_valid());
  8806. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8808. auto se = detail::scope_exit([&] {
  8809. svr.stop();
  8810. t.join();
  8811. ASSERT_FALSE(svr.is_running());
  8812. });
  8813. svr.wait_until_ready();
  8814. SSLClient cli(HOST, PORT);
  8815. cli.set_connection_timeout(30);
  8816. auto res = cli.Get("/test");
  8817. ASSERT_TRUE(!res);
  8818. // When client cert is missing and server requires it, connection fails
  8819. // Error type depends on backend implementation
  8820. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8821. res.error() == Error::SSLConnection);
  8822. // Verify backend error is captured
  8823. // Note: This test may have different error codes depending on the exact
  8824. // verification failure
  8825. EXPECT_NE(0UL, res.ssl_backend_error());
  8826. }
  8827. TEST(SSLClientServerTest, TrustDirOptional) {
  8828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8829. ASSERT_TRUE(svr.is_valid());
  8830. svr.Get("/test", [&](const Request &, Response &res) {
  8831. res.set_content("test", "text/plain");
  8832. });
  8833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. t.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8841. cli.enable_server_certificate_verification(false);
  8842. cli.set_connection_timeout(30);
  8843. auto res = cli.Get("/test");
  8844. ASSERT_TRUE(res);
  8845. ASSERT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8848. class NoListenSSLServer : public SSLServer {
  8849. public:
  8850. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8851. const char *client_ca_cert_file_path,
  8852. const char *client_ca_cert_dir_path = nullptr)
  8853. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8854. client_ca_cert_dir_path),
  8855. stop_(false) {}
  8856. std::atomic_bool stop_;
  8857. private:
  8858. bool process_and_close_socket(socket_t /*sock*/) override {
  8859. // Don't create SSL context
  8860. while (!stop_.load()) {
  8861. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8862. }
  8863. return true;
  8864. }
  8865. };
  8866. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8867. CLIENT_CA_CERT_FILE);
  8868. ASSERT_TRUE(svr.is_valid());
  8869. svr.Get("/test", [&](const Request &, Response &res) {
  8870. res.set_content("test", "text/plain");
  8871. });
  8872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8873. auto se = detail::scope_exit([&] {
  8874. svr.stop_ = true;
  8875. svr.stop();
  8876. t.join();
  8877. ASSERT_FALSE(svr.is_running());
  8878. });
  8879. svr.wait_until_ready();
  8880. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8881. cli.enable_server_certificate_verification(false);
  8882. cli.set_connection_timeout(1);
  8883. auto res = cli.Get("/test");
  8884. ASSERT_TRUE(!res);
  8885. EXPECT_EQ(Error::SSLConnection, res.error());
  8886. // Timeout results in WantRead error code (maps to backend-specific value)
  8887. EXPECT_NE(0, res.ssl_error());
  8888. }
  8889. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8890. // Test SSLServer with client certificate verification using the standard
  8891. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8893. CLIENT_CA_CERT_DIR);
  8894. ASSERT_TRUE(svr.is_valid());
  8895. svr.Get("/test", [&](const Request &req, Response &res) {
  8896. res.set_content("test", "text/plain");
  8897. auto cert = req.peer_cert();
  8898. ASSERT_TRUE(static_cast<bool>(cert));
  8899. auto common_name = cert.subject_cn();
  8900. EXPECT_EQ("Common Name", common_name);
  8901. });
  8902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8910. cli.enable_server_certificate_verification(false);
  8911. cli.set_connection_timeout(30);
  8912. auto res = cli.Get("/test");
  8913. ASSERT_TRUE(res);
  8914. ASSERT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8917. // Verifies that wildcard matching and exact matching work consistently
  8918. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8919. using namespace httplib::tls;
  8920. // We need a running server to test against
  8921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8922. ASSERT_TRUE(svr.is_valid());
  8923. svr.Get("/test", [](const Request &, Response &res) {
  8924. res.set_content("ok", "text/plain");
  8925. });
  8926. thread t([&]() { svr.listen(HOST, PORT); });
  8927. auto se = detail::scope_exit([&] {
  8928. svr.stop();
  8929. t.join();
  8930. });
  8931. svr.wait_until_ready();
  8932. bool verify_callback_called = false;
  8933. bool verify_result_wrong = false;
  8934. SSLClient cli(HOST, PORT);
  8935. cli.enable_server_certificate_verification(true);
  8936. cli.set_ca_cert_path(CA_CERT_FILE);
  8937. cli.set_connection_timeout(5);
  8938. // Note: Test certificate has CN="Common Name", not "localhost"
  8939. bool verify_result_cn = false;
  8940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8941. verify_callback_called = true;
  8942. if (!ctx.cert) return false;
  8943. // Test 1: "Common Name" should match (our test server cert CN)
  8944. verify_result_cn = ctx.check_hostname("Common Name");
  8945. // Test 2: wrong hostname should not match
  8946. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8947. return true; // Accept for the purpose of this test
  8948. });
  8949. auto res = cli.Get("/test");
  8950. // The request may succeed or fail depending on cert configuration
  8951. // but the callback should have been called
  8952. ASSERT_TRUE(verify_callback_called)
  8953. << "Verify callback should have been called";
  8954. // CN="Common Name" should match our test certificate
  8955. //
  8956. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  8957. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  8958. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  8959. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  8960. // <openssl/base.h>, which is included transitively when
  8961. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  8962. #if defined(OPENSSL_IS_BORINGSSL)
  8963. EXPECT_FALSE(verify_result_cn)
  8964. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  8965. #else
  8966. EXPECT_TRUE(verify_result_cn)
  8967. << "verify_hostname should match 'Common Name' (certificate CN)";
  8968. #endif
  8969. // Wrong hostname should not match
  8970. EXPECT_FALSE(verify_result_wrong)
  8971. << "verify_hostname should not match 'wronghost.example.com'";
  8972. }
  8973. #endif
  8974. // mbedTLS-specific callback constructor test
  8975. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8976. #ifdef CPPHTTPLIB_SSL_ENABLED
  8977. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8979. ASSERT_TRUE(svr.is_valid());
  8980. // Set up a handler to verify client certificate is present
  8981. bool client_cert_verified = false;
  8982. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8983. // Verify that client certificate was provided
  8984. client_cert_verified = true;
  8985. res.set_content("success", "text/plain");
  8986. });
  8987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. ASSERT_FALSE(svr.is_running());
  8992. });
  8993. svr.wait_until_ready();
  8994. // Client with certificate
  8995. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8996. cli.enable_server_certificate_verification(false);
  8997. cli.set_connection_timeout(30);
  8998. auto res = cli.Get("/test");
  8999. ASSERT_TRUE(res);
  9000. ASSERT_EQ(StatusCode::OK_200, res->status);
  9001. ASSERT_TRUE(client_cert_verified);
  9002. EXPECT_EQ("success", res->body);
  9003. }
  9004. #endif
  9005. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9006. // backends
  9007. #ifdef CPPHTTPLIB_SSL_ENABLED
  9008. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9009. using namespace httplib::tls;
  9010. // Test that when client CA cert file is provided,
  9011. // the server properly requests and validates client certificates
  9012. // Create a server with client authentication
  9013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9014. ASSERT_TRUE(svr.is_valid());
  9015. bool handler_called = false;
  9016. svr.Get("/test", [&](const Request &req, Response &res) {
  9017. handler_called = true;
  9018. // Verify that a client certificate was provided
  9019. auto cert = req.peer_cert();
  9020. ASSERT_TRUE(static_cast<bool>(cert));
  9021. // Get the issuer name
  9022. std::string issuer_str = cert.issuer_name();
  9023. ASSERT_FALSE(issuer_str.empty());
  9024. // The client certificate should be issued by our test CA
  9025. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9026. res.set_content("authenticated", "text/plain");
  9027. });
  9028. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9029. auto se = detail::scope_exit([&] {
  9030. svr.stop();
  9031. t.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. svr.wait_until_ready();
  9035. // Connect with a client certificate issued by the CA
  9036. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9037. cli.enable_server_certificate_verification(false);
  9038. cli.set_connection_timeout(30);
  9039. auto res = cli.Get("/test");
  9040. ASSERT_TRUE(res);
  9041. ASSERT_EQ(StatusCode::OK_200, res->status);
  9042. ASSERT_TRUE(handler_called);
  9043. EXPECT_EQ("authenticated", res->body);
  9044. }
  9045. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9046. using namespace httplib::tls;
  9047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9048. ASSERT_TRUE(svr.is_valid());
  9049. svr.Get("/test", [](const Request &, Response &res) {
  9050. res.set_content("ok", "text/plain");
  9051. });
  9052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9053. auto se = detail::scope_exit([&] {
  9054. svr.stop();
  9055. t.join();
  9056. });
  9057. svr.wait_until_ready();
  9058. SSLClient cli(HOST, PORT);
  9059. cli.enable_server_certificate_verification(false);
  9060. cli.set_connection_timeout(30);
  9061. bool cert_checked = false;
  9062. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9063. if (ctx.cert) {
  9064. auto sans = ctx.sans();
  9065. // Test certificate may or may not have SANs - just verify the API
  9066. // works If SANs exist, verify the types are valid
  9067. for (const auto &san : sans) {
  9068. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9069. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9070. san.type == SanType::OTHER);
  9071. EXPECT_FALSE(san.value.empty());
  9072. }
  9073. cert_checked = true;
  9074. }
  9075. return true;
  9076. });
  9077. auto res = cli.Get("/test");
  9078. ASSERT_TRUE(res);
  9079. EXPECT_TRUE(cert_checked);
  9080. }
  9081. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9082. using namespace httplib::tls;
  9083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9084. ASSERT_TRUE(svr.is_valid());
  9085. svr.Get("/test", [](const Request &, Response &res) {
  9086. res.set_content("ok", "text/plain");
  9087. });
  9088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9089. auto se = detail::scope_exit([&] {
  9090. svr.stop();
  9091. t.join();
  9092. });
  9093. svr.wait_until_ready();
  9094. SSLClient cli(HOST, PORT);
  9095. cli.enable_server_certificate_verification(false);
  9096. cli.set_connection_timeout(30);
  9097. bool validity_checked = false;
  9098. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9099. if (ctx.cert) {
  9100. time_t not_before = 0, not_after = 0;
  9101. bool result = ctx.validity(not_before, not_after);
  9102. EXPECT_TRUE(result);
  9103. // Verify that not_before < now < not_after for a valid cert
  9104. time_t now = time(nullptr);
  9105. EXPECT_LT(not_before, now);
  9106. EXPECT_GT(not_after, now);
  9107. validity_checked = true;
  9108. }
  9109. return true;
  9110. });
  9111. auto res = cli.Get("/test");
  9112. ASSERT_TRUE(res);
  9113. EXPECT_TRUE(validity_checked);
  9114. }
  9115. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9116. using namespace httplib::tls;
  9117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9118. ASSERT_TRUE(svr.is_valid());
  9119. svr.Get("/test", [](const Request &, Response &res) {
  9120. res.set_content("ok", "text/plain");
  9121. });
  9122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9123. auto se = detail::scope_exit([&] {
  9124. svr.stop();
  9125. t.join();
  9126. });
  9127. svr.wait_until_ready();
  9128. SSLClient cli(HOST, PORT);
  9129. cli.enable_server_certificate_verification(false);
  9130. cli.set_connection_timeout(30);
  9131. bool serial_checked = false;
  9132. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9133. if (ctx.cert) {
  9134. std::string serial = ctx.serial();
  9135. EXPECT_FALSE(serial.empty());
  9136. // Serial should be a hex string
  9137. for (char c : serial) {
  9138. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9139. (c >= 'a' && c <= 'f'));
  9140. }
  9141. serial_checked = true;
  9142. }
  9143. return true;
  9144. });
  9145. auto res = cli.Get("/test");
  9146. ASSERT_TRUE(res);
  9147. EXPECT_TRUE(serial_checked);
  9148. }
  9149. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9150. // Test 1: Valid CA file - no error should be recorded
  9151. {
  9152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9153. CLIENT_CA_CERT_FILE);
  9154. ASSERT_TRUE(svr.is_valid());
  9155. // With valid setup, last_ssl_error should be 0
  9156. EXPECT_EQ(0, svr.ssl_last_error());
  9157. }
  9158. // Test 2: Invalid CA file content
  9159. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9160. {
  9161. // Create a temporary file with completely invalid content
  9162. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9163. {
  9164. std::ofstream ofs(temp_invalid_ca);
  9165. ofs << "This is not a certificate file at all\n";
  9166. ofs << "Just plain text content\n";
  9167. }
  9168. // Create server with invalid CA file
  9169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9170. // Clean up temporary file
  9171. std::remove(temp_invalid_ca);
  9172. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9173. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9174. // Note: SSL_CTX_load_verify_locations typically fails first,
  9175. // but our error handling code path is still exercised
  9176. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9177. }
  9178. }
  9179. TEST(VerifyCallbackTest, VerifyContextFields) {
  9180. using namespace httplib::tls;
  9181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9182. ASSERT_TRUE(svr.is_valid());
  9183. svr.Get("/test", [](const Request &, Response &res) {
  9184. res.set_content("ok", "text/plain");
  9185. });
  9186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9187. auto se = detail::scope_exit([&] {
  9188. svr.stop();
  9189. t.join();
  9190. });
  9191. svr.wait_until_ready();
  9192. SSLClient cli(HOST, PORT);
  9193. cli.enable_server_certificate_verification(false);
  9194. cli.set_connection_timeout(30);
  9195. int callback_count = 0;
  9196. bool saw_leaf_cert = false;
  9197. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9198. if (ctx.cert) {
  9199. callback_count++;
  9200. // We should see at least one certificate (the leaf)
  9201. std::string cn = ctx.subject_cn();
  9202. if (!cn.empty()) { saw_leaf_cert = true; }
  9203. // Verify context fields are populated
  9204. EXPECT_NE(ctx.session, nullptr);
  9205. EXPECT_GE(ctx.depth, 0);
  9206. }
  9207. return true;
  9208. });
  9209. auto res = cli.Get("/test");
  9210. ASSERT_TRUE(res);
  9211. EXPECT_GT(callback_count, 0);
  9212. EXPECT_TRUE(saw_leaf_cert);
  9213. }
  9214. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9215. using httplib::tls::TlsError;
  9216. // Test that verify_error_to_string returns empty for success
  9217. std::string success_str = TlsError::verify_error_to_string(0);
  9218. EXPECT_TRUE(success_str.empty());
  9219. // Test that verify_error_to_string returns non-empty for error codes
  9220. // Using a common error code (certificate expired)
  9221. std::string error_str =
  9222. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9223. EXPECT_FALSE(error_str.empty());
  9224. }
  9225. TEST(SessionVerifierTest, CertificateAccepted) {
  9226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9227. ASSERT_TRUE(svr.is_valid());
  9228. svr.Get("/test", [](const Request &, Response &res) {
  9229. res.set_content("ok", "text/plain");
  9230. });
  9231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. t.join();
  9235. });
  9236. svr.wait_until_ready();
  9237. SSLClient cli(HOST, PORT);
  9238. cli.enable_server_certificate_verification(false);
  9239. cli.set_connection_timeout(30);
  9240. bool callback_called = false;
  9241. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9242. EXPECT_NE(session, nullptr);
  9243. callback_called = true;
  9244. return SSLVerifierResponse::CertificateAccepted;
  9245. });
  9246. auto res = cli.Get("/test");
  9247. ASSERT_TRUE(res);
  9248. EXPECT_EQ(200, res->status);
  9249. EXPECT_TRUE(callback_called);
  9250. }
  9251. TEST(SessionVerifierTest, CertificateRejected) {
  9252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9253. ASSERT_TRUE(svr.is_valid());
  9254. svr.Get("/test", [](const Request &, Response &res) {
  9255. res.set_content("ok", "text/plain");
  9256. });
  9257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9258. auto se = detail::scope_exit([&] {
  9259. svr.stop();
  9260. t.join();
  9261. });
  9262. svr.wait_until_ready();
  9263. SSLClient cli(HOST, PORT);
  9264. cli.enable_server_certificate_verification(false);
  9265. cli.set_connection_timeout(30);
  9266. bool callback_called = false;
  9267. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9268. EXPECT_NE(session, nullptr);
  9269. callback_called = true;
  9270. return SSLVerifierResponse::CertificateRejected;
  9271. });
  9272. auto res = cli.Get("/test");
  9273. EXPECT_FALSE(res);
  9274. EXPECT_TRUE(callback_called);
  9275. }
  9276. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9278. ASSERT_TRUE(svr.is_valid());
  9279. svr.Get("/test", [](const Request &, Response &res) {
  9280. res.set_content("ok", "text/plain");
  9281. });
  9282. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9283. auto se = detail::scope_exit([&] {
  9284. svr.stop();
  9285. t.join();
  9286. });
  9287. svr.wait_until_ready();
  9288. // NoDecisionMade with verification disabled should succeed (no default check)
  9289. SSLClient cli(HOST, PORT);
  9290. cli.enable_server_certificate_verification(false);
  9291. cli.set_connection_timeout(30);
  9292. bool callback_called = false;
  9293. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9294. EXPECT_NE(session, nullptr);
  9295. callback_called = true;
  9296. return SSLVerifierResponse::NoDecisionMade;
  9297. });
  9298. auto res = cli.Get("/test");
  9299. ASSERT_TRUE(res);
  9300. EXPECT_EQ(200, res->status);
  9301. EXPECT_TRUE(callback_called);
  9302. }
  9303. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9305. ASSERT_TRUE(svr.is_valid());
  9306. svr.Get("/test", [](const Request &, Response &res) {
  9307. res.set_content("ok", "text/plain");
  9308. });
  9309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9310. auto se = detail::scope_exit([&] {
  9311. svr.stop();
  9312. t.join();
  9313. });
  9314. svr.wait_until_ready();
  9315. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9316. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9317. // so we only check that the request fails, not whether the callback was
  9318. // called.
  9319. SSLClient cli(HOST, PORT);
  9320. cli.enable_server_certificate_verification(true);
  9321. cli.set_connection_timeout(30);
  9322. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9323. EXPECT_NE(session, nullptr);
  9324. return SSLVerifierResponse::NoDecisionMade;
  9325. });
  9326. auto res = cli.Get("/test");
  9327. EXPECT_FALSE(res);
  9328. }
  9329. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9330. // Test SSL server using PemMemory constructor with client CA certificates
  9331. // Read PEM files
  9332. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9333. read_file(SERVER_CERT_FILE, server_cert_pem);
  9334. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9335. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9336. // Create SSLServer with PemMemory constructor including client CA
  9337. SSLServer::PemMemory server_pem = {
  9338. server_cert_pem.c_str(),
  9339. server_cert_pem.size(),
  9340. server_key_pem.c_str(),
  9341. server_key_pem.size(),
  9342. client_ca_pem.c_str(),
  9343. client_ca_pem.size(),
  9344. nullptr // no password for server key
  9345. };
  9346. SSLServer svr(server_pem);
  9347. ASSERT_TRUE(svr.is_valid());
  9348. // No SSL error should be recorded for valid setup
  9349. EXPECT_EQ(0, svr.ssl_last_error());
  9350. // Set up server endpoints
  9351. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9352. res.set_content("ok", "text/plain");
  9353. });
  9354. // Start server in a thread
  9355. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9356. svr.wait_until_ready();
  9357. // Connect with client certificate (using constructor with paths)
  9358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9359. cli.enable_server_certificate_verification(false);
  9360. auto res = cli.Get("/test-pem-ca");
  9361. ASSERT_TRUE(res);
  9362. EXPECT_EQ(200, res->status);
  9363. EXPECT_EQ("ok", res->body);
  9364. svr.stop();
  9365. server_thread.join();
  9366. }
  9367. #endif
  9368. #ifdef _WIN32
  9369. TEST(CleanupTest, WSACleanup) {
  9370. int ret = WSACleanup();
  9371. ASSERT_EQ(0, ret);
  9372. }
  9373. #endif
  9374. #ifndef CPPHTTPLIB_SSL_ENABLED
  9375. TEST(NoSSLSupport, SimpleInterface) {
  9376. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9377. }
  9378. #endif
  9379. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9380. TEST(InvalidScheme, SimpleInterface) {
  9381. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9382. }
  9383. #endif
  9384. TEST(NoScheme, SimpleInterface) {
  9385. Client cli("yahoo.com:80");
  9386. ASSERT_TRUE(cli.is_valid());
  9387. }
  9388. TEST(SendAPI, SimpleInterface_Online) {
  9389. Client cli("http://yahoo.com");
  9390. Request req;
  9391. req.method = "GET";
  9392. req.path = "/";
  9393. auto res = cli.send(req);
  9394. ASSERT_TRUE(res);
  9395. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9396. }
  9397. TEST(SendAPI, WithParamsInRequest) {
  9398. Server svr;
  9399. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9400. EXPECT_TRUE(req.has_param("test"));
  9401. EXPECT_EQ("test_value", req.get_param_value("test"));
  9402. });
  9403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. t.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. Client cli(HOST, PORT);
  9411. {
  9412. Request req;
  9413. req.method = "GET";
  9414. req.path = "/";
  9415. req.params.emplace("test", "test_value");
  9416. auto res = cli.send(req);
  9417. ASSERT_TRUE(res);
  9418. }
  9419. {
  9420. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9421. ASSERT_TRUE(res);
  9422. }
  9423. }
  9424. TEST(ClientImplMethods, GetSocketTest) {
  9425. httplib::Server svr;
  9426. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9427. res.status = StatusCode::OK_200;
  9428. });
  9429. auto port = svr.bind_to_any_port("127.0.0.1");
  9430. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. thread.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. {
  9438. httplib::Client cli("127.0.0.1", port);
  9439. cli.set_keep_alive(true);
  9440. // Use the behavior of cpp-httplib of opening the connection
  9441. // only when the first request happens. If that changes,
  9442. // this test would be obsolete.
  9443. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9444. // This also implicitly tests the server. But other tests would fail much
  9445. // earlier than this one to be considered.
  9446. auto res = cli.Get("/");
  9447. ASSERT_TRUE(res);
  9448. EXPECT_EQ(StatusCode::OK_200, res->status);
  9449. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9450. }
  9451. }
  9452. #ifdef CPPHTTPLIB_SSL_ENABLED
  9453. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9454. Client cli("http://yahoo.com");
  9455. auto res = cli.Get("/");
  9456. ASSERT_TRUE(res);
  9457. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9458. cli.set_follow_location(true);
  9459. res = cli.Get("/");
  9460. ASSERT_TRUE(res);
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9463. }
  9464. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9465. Client cli("https://yahoo.com");
  9466. auto res = cli.Get("/");
  9467. ASSERT_TRUE(res);
  9468. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9469. cli.set_follow_location(true);
  9470. res = cli.Get("/");
  9471. ASSERT_TRUE(res);
  9472. EXPECT_EQ(StatusCode::OK_200, res->status);
  9473. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9474. }
  9475. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9476. Client cli("https://yahoo.com");
  9477. auto res = cli.Get("/");
  9478. ASSERT_TRUE(res);
  9479. ASSERT_FALSE(!res);
  9480. ASSERT_TRUE(res);
  9481. ASSERT_FALSE(res == nullptr);
  9482. ASSERT_TRUE(res != nullptr);
  9483. EXPECT_EQ(Error::Success, res.error());
  9484. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9485. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9487. cli.set_follow_location(true);
  9488. res = cli.Get("/");
  9489. ASSERT_TRUE(res);
  9490. EXPECT_EQ(Error::Success, res.error());
  9491. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9492. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9493. EXPECT_EQ(StatusCode::OK_200, res->status);
  9494. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9495. }
  9496. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9497. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9498. Client cli("https://cdnjs.cloudflare.com");
  9499. auto res =
  9500. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9501. ASSERT_TRUE(res);
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. EXPECT_EQ(287630U, res->body.size());
  9504. EXPECT_EQ("application/javascript; charset=utf-8",
  9505. res->get_header_value("Content-Type"));
  9506. }
  9507. #endif
  9508. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9509. #undef REDIR_HOST // Silence compiler warning
  9510. #define REDIR_HOST "https://httpbingo.org"
  9511. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9512. Client cli(REDIR_HOST);
  9513. cli.set_follow_location(true);
  9514. auto res =
  9515. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9516. ASSERT_TRUE(res);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. }
  9519. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9520. Client cli(REDIR_HOST);
  9521. cli.set_follow_location(true);
  9522. Params params;
  9523. params.emplace("url", "http://example.com");
  9524. params.emplace("status_code", "302");
  9525. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9526. ASSERT_TRUE(res);
  9527. EXPECT_EQ(StatusCode::OK_200, res->status);
  9528. }
  9529. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9530. Client cli(REDIR_HOST);
  9531. cli.set_follow_location(true);
  9532. Params params;
  9533. params.emplace("url", "http://example.com");
  9534. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9535. ASSERT_TRUE(res);
  9536. EXPECT_EQ(StatusCode::OK_200, res->status);
  9537. }
  9538. TEST(HttpToHttpsRedirectTest, CertFile) {
  9539. auto ssl_port = PORT + 1;
  9540. Server svr;
  9541. ASSERT_TRUE(svr.is_valid());
  9542. svr.Get("/index", [&](const Request &, Response &res) {
  9543. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9544. "/index");
  9545. svr.stop();
  9546. });
  9547. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9548. ASSERT_TRUE(ssl_svr.is_valid());
  9549. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9550. res.set_content("test", "text/plain");
  9551. ssl_svr.stop();
  9552. });
  9553. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9554. thread t2 =
  9555. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9556. auto se = detail::scope_exit([&] {
  9557. t2.join();
  9558. t.join();
  9559. ASSERT_FALSE(svr.is_running());
  9560. });
  9561. svr.wait_until_ready();
  9562. ssl_svr.wait_until_ready();
  9563. Client cli("127.0.0.1", PORT);
  9564. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9565. cli.enable_server_certificate_verification(true);
  9566. cli.set_follow_location(true);
  9567. cli.set_connection_timeout(30);
  9568. auto res = cli.Get("/index");
  9569. ASSERT_TRUE(res);
  9570. ASSERT_EQ(StatusCode::OK_200, res->status);
  9571. }
  9572. TEST(SSLClientRedirectTest, CertFile) {
  9573. auto ssl_port = PORT + 1;
  9574. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9575. ASSERT_TRUE(ssl_svr1.is_valid());
  9576. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9577. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9578. "/index");
  9579. ssl_svr1.stop();
  9580. });
  9581. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9582. ASSERT_TRUE(ssl_svr2.is_valid());
  9583. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9584. res.set_content("test", "text/plain");
  9585. ssl_svr2.stop();
  9586. });
  9587. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9588. thread t2 =
  9589. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9590. auto se = detail::scope_exit([&] {
  9591. t2.join();
  9592. t.join();
  9593. ASSERT_FALSE(ssl_svr1.is_running());
  9594. });
  9595. ssl_svr1.wait_until_ready();
  9596. ssl_svr2.wait_until_ready();
  9597. SSLClient cli("127.0.0.1", PORT);
  9598. std::string cert;
  9599. read_file(SERVER_CERT2_FILE, cert);
  9600. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9601. cli.enable_server_certificate_verification(true);
  9602. cli.set_follow_location(true);
  9603. cli.set_connection_timeout(30);
  9604. auto res = cli.Get("/index");
  9605. ASSERT_TRUE(res);
  9606. ASSERT_EQ(StatusCode::OK_200, res->status);
  9607. }
  9608. #endif
  9609. #ifdef CPPHTTPLIB_SSL_ENABLED
  9610. // Test that set_ca_cert_store() skips system certs (consistent with
  9611. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9612. // should be trusted - system certs should NOT be loaded.
  9613. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9614. // Load a specific cert that is NOT a system CA cert
  9615. std::string cert;
  9616. read_file(SERVER_CERT2_FILE, cert);
  9617. SSLClient cli("google.com");
  9618. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9619. cli.enable_server_certificate_verification(true);
  9620. // This should FAIL because:
  9621. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9622. // 2. System certs should NOT be loaded when custom store is set
  9623. // If system certs WERE loaded, this would succeed
  9624. auto res = cli.Get("/");
  9625. ASSERT_FALSE(res);
  9626. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9627. }
  9628. TEST(MultipartFormDataTest, LargeData) {
  9629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9630. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9631. const ContentReader &content_reader) {
  9632. if (req.is_multipart_form_data()) {
  9633. std::vector<FormData> items;
  9634. content_reader(
  9635. [&](const FormData &file) {
  9636. items.push_back(file);
  9637. return true;
  9638. },
  9639. [&](const char *data, size_t data_length) {
  9640. items.back().content.append(data, data_length);
  9641. return true;
  9642. });
  9643. EXPECT_TRUE(std::string(items[0].name) == "document");
  9644. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9645. EXPECT_TRUE(items[0].filename == "2MB_data");
  9646. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9647. EXPECT_TRUE(items[1].name == "hello");
  9648. EXPECT_TRUE(items[1].content == "world");
  9649. EXPECT_TRUE(items[1].filename == "");
  9650. EXPECT_TRUE(items[1].content_type == "");
  9651. } else {
  9652. std::string body;
  9653. content_reader([&](const char *data, size_t data_length) {
  9654. body.append(data, data_length);
  9655. return true;
  9656. });
  9657. }
  9658. });
  9659. auto port = svr.bind_to_any_port(HOST);
  9660. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9661. auto se = detail::scope_exit([&] {
  9662. svr.stop();
  9663. t.join();
  9664. ASSERT_FALSE(svr.is_running());
  9665. });
  9666. svr.wait_until_ready();
  9667. {
  9668. std::string data(1024 * 1024 * 2, '.');
  9669. std::stringstream buffer;
  9670. buffer << data;
  9671. SSLClient cli(HOST, port);
  9672. cli.enable_server_certificate_verification(false);
  9673. UploadFormDataItems items{
  9674. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9675. {"hello", "world", "", ""},
  9676. };
  9677. auto res = cli.Post("/post", items);
  9678. ASSERT_TRUE(res);
  9679. ASSERT_EQ(StatusCode::OK_200, res->status);
  9680. }
  9681. }
  9682. TEST(MultipartFormDataTest, DataProviderItems) {
  9683. std::random_device seed_gen;
  9684. std::mt19937 random(seed_gen());
  9685. std::string rand1;
  9686. rand1.resize(1000);
  9687. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9688. std::string rand2;
  9689. rand2.resize(3000);
  9690. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9692. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9693. const ContentReader &content_reader) {
  9694. ASSERT_FALSE(req.is_multipart_form_data());
  9695. std::string body;
  9696. content_reader([&](const char *data, size_t data_length) {
  9697. body.append(data, data_length);
  9698. return true;
  9699. });
  9700. EXPECT_EQ(body, "");
  9701. });
  9702. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9703. const ContentReader &content_reader) {
  9704. ASSERT_TRUE(req.is_multipart_form_data());
  9705. std::vector<FormData> items;
  9706. content_reader(
  9707. [&](const FormData &file) {
  9708. items.push_back(file);
  9709. return true;
  9710. },
  9711. [&](const char *data, size_t data_length) {
  9712. items.back().content.append(data, data_length);
  9713. return true;
  9714. });
  9715. ASSERT_TRUE(items.size() == 2);
  9716. EXPECT_EQ(std::string(items[0].name), "name1");
  9717. EXPECT_EQ(items[0].content, "Testing123");
  9718. EXPECT_EQ(items[0].filename, "filename1");
  9719. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9720. EXPECT_EQ(items[1].name, "name2");
  9721. EXPECT_EQ(items[1].content, "Testing456");
  9722. EXPECT_EQ(items[1].filename, "");
  9723. EXPECT_EQ(items[1].content_type, "");
  9724. });
  9725. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9726. const ContentReader &content_reader) {
  9727. ASSERT_TRUE(req.is_multipart_form_data());
  9728. std::vector<FormData> items;
  9729. content_reader(
  9730. [&](const FormData &file) {
  9731. items.push_back(file);
  9732. return true;
  9733. },
  9734. [&](const char *data, size_t data_length) {
  9735. items.back().content.append(data, data_length);
  9736. return true;
  9737. });
  9738. ASSERT_TRUE(items.size() == 2);
  9739. EXPECT_EQ(items[0].name, "name3");
  9740. EXPECT_EQ(items[0].content, rand1);
  9741. EXPECT_EQ(items[0].filename, "filename3");
  9742. EXPECT_EQ(items[0].content_type, "");
  9743. EXPECT_EQ(items[1].name, "name4");
  9744. EXPECT_EQ(items[1].content, rand2);
  9745. EXPECT_EQ(items[1].filename, "filename4");
  9746. EXPECT_EQ(items[1].content_type, "");
  9747. });
  9748. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9749. const ContentReader &content_reader) {
  9750. ASSERT_TRUE(req.is_multipart_form_data());
  9751. std::vector<FormData> items;
  9752. content_reader(
  9753. [&](const FormData &file) {
  9754. items.push_back(file);
  9755. return true;
  9756. },
  9757. [&](const char *data, size_t data_length) {
  9758. items.back().content.append(data, data_length);
  9759. return true;
  9760. });
  9761. ASSERT_TRUE(items.size() == 4);
  9762. EXPECT_EQ(std::string(items[0].name), "name1");
  9763. EXPECT_EQ(items[0].content, "Testing123");
  9764. EXPECT_EQ(items[0].filename, "filename1");
  9765. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9766. EXPECT_EQ(items[1].name, "name2");
  9767. EXPECT_EQ(items[1].content, "Testing456");
  9768. EXPECT_EQ(items[1].filename, "");
  9769. EXPECT_EQ(items[1].content_type, "");
  9770. EXPECT_EQ(items[2].name, "name3");
  9771. EXPECT_EQ(items[2].content, rand1);
  9772. EXPECT_EQ(items[2].filename, "filename3");
  9773. EXPECT_EQ(items[2].content_type, "");
  9774. EXPECT_EQ(items[3].name, "name4");
  9775. EXPECT_EQ(items[3].content, rand2);
  9776. EXPECT_EQ(items[3].filename, "filename4");
  9777. EXPECT_EQ(items[3].content_type, "");
  9778. });
  9779. auto port = svr.bind_to_any_port("localhost");
  9780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9781. auto se = detail::scope_exit([&] {
  9782. svr.stop();
  9783. t.join();
  9784. ASSERT_FALSE(svr.is_running());
  9785. });
  9786. svr.wait_until_ready();
  9787. {
  9788. SSLClient cli("localhost", port);
  9789. cli.enable_server_certificate_verification(false);
  9790. UploadFormDataItems items{
  9791. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9792. {"name2", "Testing456", "", ""}, // not a file
  9793. };
  9794. {
  9795. auto res = cli.Post("/post-none", {}, {}, {});
  9796. ASSERT_TRUE(res);
  9797. ASSERT_EQ(StatusCode::OK_200, res->status);
  9798. }
  9799. FormDataProviderItems providers;
  9800. {
  9801. auto res =
  9802. cli.Post("/post-items", {}, items, providers); // empty providers
  9803. ASSERT_TRUE(res);
  9804. ASSERT_EQ(StatusCode::OK_200, res->status);
  9805. }
  9806. providers.push_back({"name3",
  9807. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9808. // test the offset is given correctly at each step
  9809. if (!offset)
  9810. sink.os.write(rand1.data(), 30);
  9811. else if (offset == 30)
  9812. sink.os.write(rand1.data() + 30, 300);
  9813. else if (offset == 330)
  9814. sink.os.write(rand1.data() + 330, 670);
  9815. else if (offset == rand1.size())
  9816. sink.done();
  9817. return true;
  9818. },
  9819. "filename3",
  9820. {}});
  9821. providers.push_back({"name4",
  9822. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9823. // test the offset is given correctly at each step
  9824. if (!offset)
  9825. sink.os.write(rand2.data(), 2000);
  9826. else if (offset == 2000)
  9827. sink.os.write(rand2.data() + 2000, 1);
  9828. else if (offset == 2001)
  9829. sink.os.write(rand2.data() + 2001, 999);
  9830. else if (offset == rand2.size())
  9831. sink.done();
  9832. return true;
  9833. },
  9834. "filename4",
  9835. {}});
  9836. {
  9837. auto res = cli.Post("/post-providers", {}, {}, providers);
  9838. ASSERT_TRUE(res);
  9839. ASSERT_EQ(StatusCode::OK_200, res->status);
  9840. }
  9841. {
  9842. auto res = cli.Post("/post-both", {}, items, providers);
  9843. ASSERT_TRUE(res);
  9844. ASSERT_EQ(StatusCode::OK_200, res->status);
  9845. }
  9846. }
  9847. }
  9848. TEST(MultipartFormDataTest, BadHeader) {
  9849. Server svr;
  9850. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9851. res.set_content("ok", "text/plain");
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. });
  9859. svr.wait_until_ready();
  9860. const std::string body =
  9861. "This is the preamble. It is to be ignored, though it\r\n"
  9862. "is a handy place for composition agents to include an\r\n"
  9863. "explanatory note to non-MIME conformant readers.\r\n"
  9864. "\r\n"
  9865. "\r\n"
  9866. "--simple boundary\r\n"
  9867. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9868. ": BAD...\r\n"
  9869. "\r\n"
  9870. "value1\r\n"
  9871. "--simple boundary\r\n"
  9872. "Content-Disposition: form-data; name=\"field2\"; "
  9873. "filename=\"example.txt\"\r\n"
  9874. "\r\n"
  9875. "value2\r\n"
  9876. "--simple boundary--\r\n"
  9877. "This is the epilogue. It is also to be ignored.\r\n";
  9878. std::string content_type =
  9879. R"(multipart/form-data; boundary="simple boundary")";
  9880. Client cli(HOST, PORT);
  9881. auto res = cli.Post("/post", body, content_type.c_str());
  9882. ASSERT_TRUE(res);
  9883. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9884. }
  9885. TEST(MultipartFormDataTest, WithPreamble) {
  9886. Server svr;
  9887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9888. res.set_content("ok", "text/plain");
  9889. });
  9890. thread t = thread([&] { svr.listen(HOST, PORT); });
  9891. auto se = detail::scope_exit([&] {
  9892. svr.stop();
  9893. t.join();
  9894. ASSERT_FALSE(svr.is_running());
  9895. });
  9896. svr.wait_until_ready();
  9897. const std::string body =
  9898. "This is the preamble. It is to be ignored, though it\r\n"
  9899. "is a handy place for composition agents to include an\r\n"
  9900. "explanatory note to non-MIME conformant readers.\r\n"
  9901. "\r\n"
  9902. "\r\n"
  9903. "--simple boundary\r\n"
  9904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9905. "\r\n"
  9906. "value1\r\n"
  9907. "--simple boundary\r\n"
  9908. "Content-Disposition: form-data; name=\"field2\"; "
  9909. "filename=\"example.txt\"\r\n"
  9910. "\r\n"
  9911. "value2\r\n"
  9912. "--simple boundary--\r\n"
  9913. "This is the epilogue. It is also to be ignored.\r\n";
  9914. std::string content_type =
  9915. R"(multipart/form-data; boundary="simple boundary")";
  9916. Client cli(HOST, PORT);
  9917. auto res = cli.Post("/post", body, content_type.c_str());
  9918. ASSERT_TRUE(res);
  9919. EXPECT_EQ(StatusCode::OK_200, res->status);
  9920. }
  9921. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9923. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9924. const ContentReader &content_reader) {
  9925. if (req.is_multipart_form_data()) {
  9926. std::vector<FormData> items;
  9927. content_reader(
  9928. [&](const FormData &file) {
  9929. items.push_back(file);
  9930. return true;
  9931. },
  9932. [&](const char *data, size_t data_length) {
  9933. items.back().content.append(data, data_length);
  9934. return true;
  9935. });
  9936. EXPECT_TRUE(std::string(items[0].name) == "document");
  9937. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9938. EXPECT_TRUE(items[0].filename == "2MB_data");
  9939. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9940. EXPECT_TRUE(items[1].name == "hello");
  9941. EXPECT_TRUE(items[1].content == "world");
  9942. EXPECT_TRUE(items[1].filename == "");
  9943. EXPECT_TRUE(items[1].content_type == "");
  9944. } else {
  9945. std::string body;
  9946. content_reader([&](const char *data, size_t data_length) {
  9947. body.append(data, data_length);
  9948. return true;
  9949. });
  9950. }
  9951. });
  9952. auto port = svr.bind_to_any_port("localhost");
  9953. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9954. auto se = detail::scope_exit([&] {
  9955. svr.stop();
  9956. t.join();
  9957. ASSERT_FALSE(svr.is_running());
  9958. });
  9959. svr.wait_until_ready();
  9960. {
  9961. std::string data(1024 * 1024 * 2, '.');
  9962. std::stringstream buffer;
  9963. buffer << data;
  9964. SSLClient cli("localhost", port);
  9965. cli.enable_server_certificate_verification(false);
  9966. UploadFormDataItems items{
  9967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9968. {"hello", "world", "", ""},
  9969. };
  9970. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9971. ASSERT_TRUE(res);
  9972. ASSERT_EQ(StatusCode::OK_200, res->status);
  9973. }
  9974. }
  9975. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9976. std::string data(1024 * 1024 * 2, '&');
  9977. std::stringstream buffer;
  9978. buffer << data;
  9979. Client cli("https://localhost:8080");
  9980. UploadFormDataItems items{
  9981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9982. {"hello", "world", "", ""},
  9983. };
  9984. for (const char &c : " \t\r\n") {
  9985. auto res =
  9986. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9988. ASSERT_FALSE(res);
  9989. }
  9990. }
  9991. TEST(MultipartFormDataTest, PutFormData) {
  9992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9993. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9994. const ContentReader &content_reader) {
  9995. if (req.is_multipart_form_data()) {
  9996. std::vector<FormData> items;
  9997. content_reader(
  9998. [&](const FormData &file) {
  9999. items.push_back(file);
  10000. return true;
  10001. },
  10002. [&](const char *data, size_t data_length) {
  10003. items.back().content.append(data, data_length);
  10004. return true;
  10005. });
  10006. EXPECT_TRUE(std::string(items[0].name) == "document");
  10007. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10008. EXPECT_TRUE(items[0].filename == "2MB_data");
  10009. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10010. EXPECT_TRUE(items[1].name == "hello");
  10011. EXPECT_TRUE(items[1].content == "world");
  10012. EXPECT_TRUE(items[1].filename == "");
  10013. EXPECT_TRUE(items[1].content_type == "");
  10014. } else {
  10015. std::string body;
  10016. content_reader([&](const char *data, size_t data_length) {
  10017. body.append(data, data_length);
  10018. return true;
  10019. });
  10020. }
  10021. });
  10022. auto port = svr.bind_to_any_port("localhost");
  10023. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. t.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.wait_until_ready();
  10030. {
  10031. std::string data(1024 * 1024 * 2, '&');
  10032. std::stringstream buffer;
  10033. buffer << data;
  10034. SSLClient cli("localhost", port);
  10035. cli.enable_server_certificate_verification(false);
  10036. UploadFormDataItems items{
  10037. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10038. {"hello", "world", "", ""},
  10039. };
  10040. auto res = cli.Put("/put", items);
  10041. ASSERT_TRUE(res);
  10042. ASSERT_EQ(StatusCode::OK_200, res->status);
  10043. }
  10044. }
  10045. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10047. svr.Put("/put_customboundary",
  10048. [&](const Request &req, const Response & /*res*/,
  10049. const ContentReader &content_reader) {
  10050. if (req.is_multipart_form_data()) {
  10051. std::vector<FormData> items;
  10052. content_reader(
  10053. [&](const FormData &file) {
  10054. items.push_back(file);
  10055. return true;
  10056. },
  10057. [&](const char *data, size_t data_length) {
  10058. items.back().content.append(data, data_length);
  10059. return true;
  10060. });
  10061. EXPECT_TRUE(std::string(items[0].name) == "document");
  10062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10063. EXPECT_TRUE(items[0].filename == "2MB_data");
  10064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10065. EXPECT_TRUE(items[1].name == "hello");
  10066. EXPECT_TRUE(items[1].content == "world");
  10067. EXPECT_TRUE(items[1].filename == "");
  10068. EXPECT_TRUE(items[1].content_type == "");
  10069. } else {
  10070. std::string body;
  10071. content_reader([&](const char *data, size_t data_length) {
  10072. body.append(data, data_length);
  10073. return true;
  10074. });
  10075. }
  10076. });
  10077. auto port = svr.bind_to_any_port("localhost");
  10078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. t.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. {
  10086. std::string data(1024 * 1024 * 2, '&');
  10087. std::stringstream buffer;
  10088. buffer << data;
  10089. SSLClient cli("localhost", port);
  10090. cli.enable_server_certificate_verification(false);
  10091. UploadFormDataItems items{
  10092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10093. {"hello", "world", "", ""},
  10094. };
  10095. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10096. ASSERT_TRUE(res);
  10097. ASSERT_EQ(StatusCode::OK_200, res->status);
  10098. }
  10099. }
  10100. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10101. std::string data(1024 * 1024 * 2, '&');
  10102. std::stringstream buffer;
  10103. buffer << data;
  10104. Client cli("https://localhost:8080");
  10105. cli.enable_server_certificate_verification(false);
  10106. UploadFormDataItems items{
  10107. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10108. {"hello", "world", "", ""},
  10109. };
  10110. for (const char &c : " \t\r\n") {
  10111. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10112. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10113. ASSERT_FALSE(res);
  10114. }
  10115. }
  10116. TEST(MultipartFormDataTest, AlternateFilename) {
  10117. auto handled = false;
  10118. Server svr;
  10119. svr.Post("/test", [&](const Request &req, Response &res) {
  10120. ASSERT_EQ(2u, req.form.files.size());
  10121. ASSERT_EQ(1u, req.form.fields.size());
  10122. // Test files
  10123. const auto &file1 = req.form.get_file("file1");
  10124. ASSERT_EQ("file1", file1.name);
  10125. ASSERT_EQ("A.txt", file1.filename);
  10126. ASSERT_EQ("text/plain", file1.content_type);
  10127. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10128. const auto &file2 = req.form.get_file("file2");
  10129. ASSERT_EQ("file2", file2.name);
  10130. ASSERT_EQ("a.html", file2.filename);
  10131. ASSERT_EQ("text/html", file2.content_type);
  10132. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10133. file2.content);
  10134. // Test text field
  10135. const auto &text = req.form.get_field("text");
  10136. ASSERT_EQ("text default", text);
  10137. res.set_content("ok", "text/plain");
  10138. handled = true;
  10139. });
  10140. thread t = thread([&] { svr.listen(HOST, PORT); });
  10141. auto se = detail::scope_exit([&] {
  10142. svr.stop();
  10143. t.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. ASSERT_TRUE(handled);
  10146. });
  10147. svr.wait_until_ready();
  10148. auto req = "POST /test HTTP/1.1\r\n"
  10149. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10150. "Content-Length: 399\r\n"
  10151. "\r\n"
  10152. "----------\r\n"
  10153. "Content-Disposition: form-data; name=\"text\"\r\n"
  10154. "\r\n"
  10155. "text default\r\n"
  10156. "----------\r\n"
  10157. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10158. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10159. "Content-Type: text/plain\r\n"
  10160. "\r\n"
  10161. "Content of a.txt.\r\n"
  10162. "\r\n"
  10163. "----------\r\n"
  10164. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10165. "\"a.html\"\r\n"
  10166. "Content-Type: text/html\r\n"
  10167. "\r\n"
  10168. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10169. "\r\n"
  10170. "------------\r\n";
  10171. ASSERT_TRUE(send_request(1, req));
  10172. }
  10173. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10174. auto handled = false;
  10175. Server svr;
  10176. svr.Post("/test", [&](const Request &req, Response &res) {
  10177. // Case-insensitive "utf-8''" prefix with a long value
  10178. const auto &file = req.form.get_file("file1");
  10179. ASSERT_EQ("file1", file.name);
  10180. // 8000 chars exercises both the Content-Disposition parser and the
  10181. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10182. // Prior to the fix, std::regex_match on this header would cause O(N)
  10183. // stack recursion in libstdc++, leading to SIGSEGV.
  10184. std::string expected_filename(8000, 'A');
  10185. ASSERT_EQ(expected_filename, file.filename);
  10186. res.set_content("ok", "text/plain");
  10187. handled = true;
  10188. });
  10189. thread t = thread([&] { svr.listen(HOST, PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. ASSERT_TRUE(handled);
  10195. });
  10196. svr.wait_until_ready();
  10197. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10198. // Regression test for GHSA-qq6v-r583-3h69
  10199. std::string long_filename(8000, 'A');
  10200. std::string body = "----------\r\n"
  10201. "Content-Disposition: form-data; name=\"file1\"; "
  10202. "filename*=\"Utf-8''" +
  10203. long_filename +
  10204. "\"\r\n"
  10205. "\r\n"
  10206. "hello\r\n"
  10207. "------------\r\n";
  10208. auto req = "POST /test HTTP/1.1\r\n"
  10209. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10210. "Content-Length: " +
  10211. std::to_string(body.size()) + "\r\n\r\n" + body;
  10212. ASSERT_TRUE(send_request(1, req));
  10213. }
  10214. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10215. auto handled = false;
  10216. Server svr;
  10217. svr.Post("/test", [&](const Request &req, Response &) {
  10218. ASSERT_EQ(2u, req.form.fields.size());
  10219. const auto &text1 = req.form.get_field("text1");
  10220. ASSERT_EQ("text1", text1);
  10221. const auto &text2 = req.form.get_field("text2");
  10222. ASSERT_EQ("text2", text2);
  10223. handled = true;
  10224. });
  10225. thread t = thread([&] { svr.listen(HOST, PORT); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. ASSERT_TRUE(handled);
  10231. });
  10232. svr.wait_until_ready();
  10233. auto req = "POST /test HTTP/1.1\r\n"
  10234. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10235. "Content-Length: 146\r\n"
  10236. "\r\n----------\r\n"
  10237. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10238. "\r\n"
  10239. "text1"
  10240. "\r\n----------\r\n"
  10241. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10242. "\r\n"
  10243. "text2"
  10244. "\r\n------------";
  10245. std::string response;
  10246. ASSERT_TRUE(send_request(1, req, &response));
  10247. ASSERT_EQ("200", response.substr(9, 3));
  10248. }
  10249. TEST(MultipartFormDataTest, ContentLength) {
  10250. auto handled = false;
  10251. Server svr;
  10252. svr.Post("/test", [&](const Request &req, Response &) {
  10253. ASSERT_EQ(2u, req.form.fields.size());
  10254. const auto &text1 = req.form.get_field("text1");
  10255. ASSERT_EQ("text1", text1);
  10256. const auto &text2 = req.form.get_field("text2");
  10257. ASSERT_EQ("text2", text2);
  10258. handled = true;
  10259. });
  10260. thread t = thread([&] { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. t.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. ASSERT_TRUE(handled);
  10266. });
  10267. svr.wait_until_ready();
  10268. auto req = "POST /test HTTP/1.1\r\n"
  10269. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10270. "Content-Length: 167\r\n"
  10271. "\r\n----------\r\n"
  10272. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10273. "Content-Length: 5\r\n"
  10274. "\r\n"
  10275. "text1"
  10276. "\r\n----------\r\n"
  10277. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10278. "\r\n"
  10279. "text2"
  10280. "\r\n------------\r\n";
  10281. std::string response;
  10282. ASSERT_TRUE(send_request(1, req, &response));
  10283. ASSERT_EQ("200", response.substr(9, 3));
  10284. }
  10285. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10286. auto handled = false;
  10287. Server svr;
  10288. svr.Post("/test", [&](const Request &req, Response &) {
  10289. ASSERT_EQ(2u, req.form.fields.size());
  10290. const auto &text1 = req.form.get_field("text1");
  10291. ASSERT_EQ("text1", text1);
  10292. // TODO: Add header access for text fields if needed
  10293. const auto &text2 = req.form.get_field("text2");
  10294. ASSERT_EQ("text2", text2);
  10295. // TODO: Header access for text fields needs to be implemented
  10296. // auto &headers = it->second.headers;
  10297. // ASSERT_EQ(3U, headers.size());
  10298. // auto custom_header = headers.find("x-whatever");
  10299. // ASSERT_TRUE(custom_header != headers.end());
  10300. // ASSERT_NE("customvalue", custom_header->second);
  10301. // ASSERT_EQ("CustomValue", custom_header->second);
  10302. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10303. handled = true;
  10304. });
  10305. thread t = thread([&] { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. ASSERT_FALSE(svr.is_running());
  10310. ASSERT_TRUE(handled);
  10311. });
  10312. svr.wait_until_ready();
  10313. auto req = "POST /test HTTP/1.1\r\n"
  10314. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10315. "Content-Length: 232\r\n"
  10316. "\r\n----------\r\n"
  10317. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10318. "Content-Length: 5\r\n"
  10319. "X-Test: 1\r\n"
  10320. "\r\n"
  10321. "text1"
  10322. "\r\n----------\r\n"
  10323. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10324. "Content-Type: text/plain\r\n"
  10325. "X-Whatever: CustomValue\r\n"
  10326. "\r\n"
  10327. "text2"
  10328. "\r\n------------\r\n"
  10329. "That should be disregarded. Not even read";
  10330. std::string response;
  10331. ASSERT_TRUE(send_request(1, req, &response));
  10332. ASSERT_EQ("200", response.substr(9, 3));
  10333. }
  10334. TEST(MultipartFormDataTest, LargeHeader) {
  10335. auto handled = false;
  10336. Server svr;
  10337. svr.Post("/test", [&](const Request &req, Response &) {
  10338. ASSERT_EQ(1u, req.form.fields.size());
  10339. const auto &text = req.form.get_field("name1");
  10340. ASSERT_EQ("text1", text);
  10341. handled = true;
  10342. });
  10343. thread t = thread([&] { svr.listen(HOST, PORT); });
  10344. auto se = detail::scope_exit([&] {
  10345. svr.stop();
  10346. t.join();
  10347. ASSERT_FALSE(svr.is_running());
  10348. ASSERT_TRUE(handled);
  10349. });
  10350. svr.wait_until_ready();
  10351. auto boundary = std::string("cpp-httplib-multipart-data");
  10352. std::string content = "--" + boundary +
  10353. "\r\n"
  10354. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10355. "\r\n"
  10356. "text1\r\n"
  10357. "--" +
  10358. boundary + "--\r\n";
  10359. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10360. "Content-Type: multipart/form-data;boundary=" +
  10361. boundary +
  10362. "\r\n"
  10363. "Content-Length: " +
  10364. std::to_string(content.size()) +
  10365. "\r\n"
  10366. "Dummy-Header: ";
  10367. std::string header_suffix = "\r\n"
  10368. "\r\n";
  10369. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10370. size_t header_dummy_size =
  10371. read_buff_size -
  10372. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10373. auto header_dummy = std::string(header_dummy_size, '@');
  10374. auto req = header_prefix + header_dummy + header_suffix + content;
  10375. std::string response;
  10376. ASSERT_TRUE(send_request(1, req, &response));
  10377. ASSERT_EQ("200", response.substr(9, 3));
  10378. }
  10379. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10380. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10381. // (not chunked Transfer-Encoding) after the streaming refactor.
  10382. auto handled = false;
  10383. Server svr;
  10384. svr.Post("/upload", [&](const Request &req, Response &res) {
  10385. auto cl_it = req.headers.find("Content-Length");
  10386. EXPECT_TRUE(cl_it != req.headers.end());
  10387. auto te_it = req.headers.find("Transfer-Encoding");
  10388. EXPECT_TRUE(te_it == req.headers.end());
  10389. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10390. res.set_content("ok", "text/plain");
  10391. handled = true;
  10392. });
  10393. auto port = svr.bind_to_any_port(HOST);
  10394. auto t = thread([&] { svr.listen_after_bind(); });
  10395. auto se = detail::scope_exit([&] {
  10396. svr.stop();
  10397. t.join();
  10398. ASSERT_FALSE(svr.is_running());
  10399. ASSERT_TRUE(handled);
  10400. });
  10401. svr.wait_until_ready();
  10402. UploadFormDataItems items = {
  10403. {"field1", "hello", "", "text/plain"},
  10404. {"file1", "world", "test.txt", "application/octet-stream"},
  10405. };
  10406. Client cli(HOST, port);
  10407. auto res = cli.Post("/upload", {}, items);
  10408. ASSERT_TRUE(res);
  10409. EXPECT_EQ(StatusCode::OK_200, res->status);
  10410. }
  10411. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10412. // Verify that make_multipart_content_provider coalesces many small segments
  10413. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10414. constexpr size_t kItemCount = 1000;
  10415. UploadFormDataItems items;
  10416. items.reserve(kItemCount);
  10417. for (size_t i = 0; i < kItemCount; i++) {
  10418. items.push_back(
  10419. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10420. }
  10421. const std::string boundary = "----test-boundary";
  10422. auto content_length = detail::get_multipart_content_length(items, boundary);
  10423. auto provider = detail::make_multipart_content_provider(items, boundary);
  10424. // Drive the provider the same way write_content_with_progress does
  10425. size_t write_count = 0;
  10426. size_t total_bytes = 0;
  10427. DataSink sink;
  10428. size_t offset = 0;
  10429. sink.write = [&](const char *d, size_t l) -> bool {
  10430. (void)d;
  10431. write_count++;
  10432. total_bytes += l;
  10433. offset += l;
  10434. return true;
  10435. };
  10436. sink.is_writable = []() -> bool { return true; };
  10437. while (offset < content_length) {
  10438. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10439. }
  10440. EXPECT_EQ(content_length, total_bytes);
  10441. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10442. // With buffering into 64KB blocks, write_count should be much smaller.
  10443. auto segment_count = 3 * kItemCount + 1;
  10444. EXPECT_LT(write_count, segment_count / 10);
  10445. }
  10446. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10447. // Integration test: send many UploadFormDataItems and verify the server
  10448. // receives all of them correctly (#2410).
  10449. constexpr size_t kItemCount = 500;
  10450. auto handled = false;
  10451. Server svr;
  10452. svr.Post("/upload", [&](const Request &req, Response &res) {
  10453. EXPECT_EQ(kItemCount, req.form.fields.size());
  10454. for (size_t i = 0; i < kItemCount; i++) {
  10455. auto key = "field" + std::to_string(i);
  10456. auto val = "value" + std::to_string(i);
  10457. auto it = req.form.fields.find(key);
  10458. if (it != req.form.fields.end()) {
  10459. EXPECT_EQ(val, it->second.content);
  10460. } else {
  10461. ADD_FAILURE() << "Missing field: " << key;
  10462. }
  10463. }
  10464. res.set_content("ok", "text/plain");
  10465. handled = true;
  10466. });
  10467. auto port = svr.bind_to_any_port(HOST);
  10468. auto t = thread([&] { svr.listen_after_bind(); });
  10469. auto se = detail::scope_exit([&] {
  10470. svr.stop();
  10471. t.join();
  10472. ASSERT_FALSE(svr.is_running());
  10473. ASSERT_TRUE(handled);
  10474. });
  10475. svr.wait_until_ready();
  10476. UploadFormDataItems items;
  10477. items.reserve(kItemCount);
  10478. for (size_t i = 0; i < kItemCount; i++) {
  10479. items.push_back(
  10480. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10481. }
  10482. Client cli(HOST, port);
  10483. auto res = cli.Post("/upload", items);
  10484. ASSERT_TRUE(res);
  10485. EXPECT_EQ(StatusCode::OK_200, res->status);
  10486. }
  10487. TEST(MultipartFormDataTest, MakeFileProvider) {
  10488. // Verify make_file_provider sends a file's contents correctly.
  10489. const std::string file_content(4096, 'Z');
  10490. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10491. {
  10492. std::ofstream ofs(tmp_path, std::ios::binary);
  10493. ofs.write(file_content.data(),
  10494. static_cast<std::streamsize>(file_content.size()));
  10495. }
  10496. auto handled = false;
  10497. Server svr;
  10498. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10499. const ContentReader &content_reader) {
  10500. ASSERT_TRUE(req.is_multipart_form_data());
  10501. std::vector<FormData> items;
  10502. content_reader(
  10503. [&](const FormData &file) {
  10504. items.push_back(file);
  10505. return true;
  10506. },
  10507. [&](const char *data, size_t data_length) {
  10508. items.back().content.append(data, data_length);
  10509. return true;
  10510. });
  10511. ASSERT_EQ(1u, items.size());
  10512. EXPECT_EQ("myfile", items[0].name);
  10513. EXPECT_EQ("data.bin", items[0].filename);
  10514. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10515. EXPECT_EQ(file_content, items[0].content);
  10516. handled = true;
  10517. });
  10518. auto port = svr.bind_to_any_port(HOST);
  10519. auto t = thread([&] { svr.listen_after_bind(); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. t.join();
  10523. ASSERT_FALSE(svr.is_running());
  10524. ASSERT_TRUE(handled);
  10525. std::remove(tmp_path.c_str());
  10526. });
  10527. svr.wait_until_ready();
  10528. FormDataProviderItems providers;
  10529. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10530. "application/octet-stream"));
  10531. Client cli(HOST, port);
  10532. auto res = cli.Post("/upload", {}, {}, providers);
  10533. ASSERT_TRUE(res);
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. }
  10536. TEST(MakeFileBodyTest, Basic) {
  10537. const std::string file_content(4096, 'Z');
  10538. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10539. {
  10540. std::ofstream ofs(tmp_path, std::ios::binary);
  10541. ofs.write(file_content.data(),
  10542. static_cast<std::streamsize>(file_content.size()));
  10543. }
  10544. auto handled = false;
  10545. Server svr;
  10546. svr.Post("/upload", [&](const Request &req, Response &res) {
  10547. EXPECT_EQ(file_content, req.body);
  10548. handled = true;
  10549. res.status = StatusCode::OK_200;
  10550. });
  10551. auto port = svr.bind_to_any_port(HOST);
  10552. auto t = thread([&] { svr.listen_after_bind(); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. t.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. ASSERT_TRUE(handled);
  10558. std::remove(tmp_path.c_str());
  10559. });
  10560. svr.wait_until_ready();
  10561. auto fb = make_file_body(tmp_path);
  10562. ASSERT_GT(fb.first, 0u);
  10563. Client cli(HOST, port);
  10564. auto res =
  10565. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10566. ASSERT_TRUE(res);
  10567. EXPECT_EQ(StatusCode::OK_200, res->status);
  10568. }
  10569. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10570. static constexpr unsigned int number_of_tasks{1000000};
  10571. std::atomic_uint count{0};
  10572. std::unique_ptr<TaskQueue> task_queue{
  10573. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10574. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10575. auto queued = task_queue->enqueue(
  10576. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10577. EXPECT_TRUE(queued);
  10578. }
  10579. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10580. task_queue->shutdown();
  10581. #else
  10582. EXPECT_NO_THROW(task_queue->shutdown());
  10583. #endif
  10584. EXPECT_EQ(number_of_tasks, count.load());
  10585. }
  10586. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10587. static constexpr unsigned int number_of_tasks{1000000};
  10588. static constexpr unsigned int qlimit{2};
  10589. unsigned int queued_count{0};
  10590. std::atomic_uint count{0};
  10591. std::unique_ptr<TaskQueue> task_queue{
  10592. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10593. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10594. if (task_queue->enqueue(
  10595. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10596. queued_count++;
  10597. }
  10598. }
  10599. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10600. task_queue->shutdown();
  10601. #else
  10602. EXPECT_NO_THROW(task_queue->shutdown());
  10603. #endif
  10604. EXPECT_EQ(queued_count, count.load());
  10605. EXPECT_TRUE(queued_count <= number_of_tasks);
  10606. EXPECT_TRUE(queued_count >= qlimit);
  10607. }
  10608. TEST(TaskQueueTest, MaxQueuedRequests) {
  10609. static constexpr unsigned int qlimit{3};
  10610. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10611. std::condition_variable sem_cv;
  10612. std::mutex sem_mtx;
  10613. int credits = 0;
  10614. bool queued;
  10615. /* Fill up the queue with tasks that will block until we give them credits to
  10616. * complete. */
  10617. for (unsigned int n = 0; n <= qlimit;) {
  10618. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10619. std::unique_lock<std::mutex> lock(sem_mtx);
  10620. while (credits <= 0) {
  10621. sem_cv.wait(lock);
  10622. }
  10623. /* Consume the credit and signal the test code if they are all gone. */
  10624. if (--credits == 0) { sem_cv.notify_one(); }
  10625. });
  10626. if (n < qlimit) {
  10627. /* The first qlimit enqueues must succeed. */
  10628. EXPECT_TRUE(queued);
  10629. } else {
  10630. /* The last one will succeed only when the worker thread
  10631. * starts and dequeues the first blocking task. Although
  10632. * not necessary for the correctness of this test, we sleep for
  10633. * a short while to avoid busy waiting. */
  10634. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10635. }
  10636. if (queued) { n++; }
  10637. }
  10638. /* Further enqueues must fail since the queue is full. */
  10639. for (auto i = 0; i < 4; i++) {
  10640. queued = task_queue->enqueue([] {});
  10641. EXPECT_FALSE(queued);
  10642. }
  10643. /* Give the credits to allow the previous tasks to complete. */
  10644. {
  10645. std::unique_lock<std::mutex> lock(sem_mtx);
  10646. credits += qlimit + 1;
  10647. }
  10648. sem_cv.notify_all();
  10649. /* Wait for all the credits to be consumed. */
  10650. {
  10651. std::unique_lock<std::mutex> lock(sem_mtx);
  10652. while (credits > 0) {
  10653. sem_cv.wait(lock);
  10654. }
  10655. }
  10656. /* Check that we are able again to enqueue at least qlimit tasks. */
  10657. for (unsigned int i = 0; i < qlimit; i++) {
  10658. queued = task_queue->enqueue([] {});
  10659. EXPECT_TRUE(queued);
  10660. }
  10661. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10662. task_queue->shutdown();
  10663. #else
  10664. EXPECT_NO_THROW(task_queue->shutdown());
  10665. #endif
  10666. }
  10667. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10668. Server svr;
  10669. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10670. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10671. });
  10672. svr.Get("/hello", [](const Request &req, Response &res) {
  10673. res.set_content(req.get_param_value("key"), "text/plain");
  10674. });
  10675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. {
  10683. Client cli(HOST, PORT);
  10684. cli.set_follow_location(true);
  10685. auto res = cli.Get("/");
  10686. ASSERT_TRUE(res);
  10687. EXPECT_EQ(StatusCode::OK_200, res->status);
  10688. EXPECT_EQ("val&key2=val2", res->body);
  10689. }
  10690. }
  10691. #endif
  10692. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10693. Server svr;
  10694. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10695. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10696. });
  10697. svr.Get("/hello", [](const Request &req, Response &res) {
  10698. res.set_content(req.get_param_value("key"), "text/plain");
  10699. });
  10700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10701. auto se = detail::scope_exit([&] {
  10702. svr.stop();
  10703. thread.join();
  10704. ASSERT_FALSE(svr.is_running());
  10705. });
  10706. svr.wait_until_ready();
  10707. {
  10708. Client cli(HOST, PORT);
  10709. cli.set_follow_location(true);
  10710. auto res = cli.Get("/");
  10711. ASSERT_TRUE(res);
  10712. EXPECT_EQ(StatusCode::OK_200, res->status);
  10713. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10714. }
  10715. }
  10716. TEST(RedirectTest, RedirectWithPlusInPath) {
  10717. Server svr;
  10718. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10719. res.set_redirect("/a+b");
  10720. });
  10721. // Route pattern uses regex; escape + as \\+
  10722. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10723. res.set_content(req.path, "text/plain");
  10724. });
  10725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10726. auto se = detail::scope_exit([&] {
  10727. svr.stop();
  10728. thread.join();
  10729. ASSERT_FALSE(svr.is_running());
  10730. });
  10731. svr.wait_until_ready();
  10732. {
  10733. Client cli(HOST, PORT);
  10734. cli.set_follow_location(true);
  10735. auto res = cli.Get("/");
  10736. ASSERT_TRUE(res);
  10737. EXPECT_EQ(StatusCode::OK_200, res->status);
  10738. EXPECT_EQ("/a+b", res->body);
  10739. }
  10740. }
  10741. #ifdef CPPHTTPLIB_SSL_ENABLED
  10742. TEST(RedirectTest, Issue2185_Online) {
  10743. SSLClient client("github.com");
  10744. client.set_follow_location(true);
  10745. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10746. "Coollab-Windows.zip");
  10747. ASSERT_TRUE(res);
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. EXPECT_EQ(9920427U, res->body.size());
  10750. }
  10751. #endif
  10752. TEST(VulnerabilityTest, CRLFInjection) {
  10753. Server svr;
  10754. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10755. res.set_content("Hello 1", "text/plain");
  10756. });
  10757. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10758. res.set_content("Hello 2", "text/plain");
  10759. });
  10760. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10761. res.set_content("Hello 3", "text/plain");
  10762. });
  10763. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10764. res.set_content("Hello 4", "text/plain");
  10765. });
  10766. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10767. for (const auto &x : req.headers) {
  10768. auto key = x.first;
  10769. EXPECT_STRNE("evil", key.c_str());
  10770. }
  10771. });
  10772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. {
  10780. Client cli(HOST, PORT);
  10781. cli.Post("/test1", "A=B",
  10782. "application/x-www-form-urlencoded\r\nevil: hello1");
  10783. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10784. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10785. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10786. }
  10787. }
  10788. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10789. auto server_thread = std::thread([] {
  10790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10791. default_socket_options(srv);
  10792. sockaddr_in addr{};
  10793. addr.sin_family = AF_INET;
  10794. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10795. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10796. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10797. ::listen(srv, 1);
  10798. sockaddr_in cli_addr{};
  10799. socklen_t cli_len = sizeof(cli_addr);
  10800. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10801. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10802. std::string buf_all;
  10803. char buf[2048];
  10804. ssize_t n;
  10805. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10806. buf_all.append(buf, static_cast<size_t>(n));
  10807. size_t pos;
  10808. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10809. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10810. auto e = request_block.find("\r\n");
  10811. if (e != std::string::npos) {
  10812. auto request_line = request_block.substr(0, e);
  10813. std::string msg =
  10814. "CRLF injection detected in request line: '" + request_line + "'";
  10815. EXPECT_FALSE(true) << msg;
  10816. }
  10817. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10818. ::send(cli,
  10819. #ifdef _WIN32
  10820. static_cast<const char *>(resp.c_str()),
  10821. static_cast<int>(resp.size()),
  10822. #else
  10823. resp.c_str(), resp.size(),
  10824. #endif
  10825. 0);
  10826. buf_all.erase(0, pos + 4);
  10827. }
  10828. }
  10829. detail::close_socket(cli);
  10830. detail::close_socket(srv);
  10831. });
  10832. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10833. auto cli = Client("127.0.0.1", PORT + 1);
  10834. auto headers = Headers{
  10835. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10836. {"Connection", "keep-alive"}};
  10837. auto res = cli.Get("/hi", headers);
  10838. EXPECT_FALSE(res);
  10839. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10840. server_thread.join();
  10841. }
  10842. TEST(PathParamsTest, StaticMatch) {
  10843. const auto pattern = "/users/all";
  10844. detail::PathParamsMatcher matcher(pattern);
  10845. Request request;
  10846. request.path = "/users/all";
  10847. ASSERT_TRUE(matcher.match(request));
  10848. std::unordered_map<std::string, std::string> expected_params = {};
  10849. EXPECT_EQ(request.path_params, expected_params);
  10850. }
  10851. TEST(PathParamsTest, StaticMismatch) {
  10852. const auto pattern = "/users/all";
  10853. detail::PathParamsMatcher matcher(pattern);
  10854. Request request;
  10855. request.path = "/users/1";
  10856. ASSERT_FALSE(matcher.match(request));
  10857. }
  10858. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10859. const auto pattern = "/users/:id/subscriptions";
  10860. detail::PathParamsMatcher matcher(pattern);
  10861. Request request;
  10862. request.path = "/users/42/subscriptions";
  10863. ASSERT_TRUE(matcher.match(request));
  10864. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10865. EXPECT_EQ(request.path_params, expected_params);
  10866. }
  10867. TEST(PathParamsTest, SingleParamInTheEnd) {
  10868. const auto pattern = "/users/:id";
  10869. detail::PathParamsMatcher matcher(pattern);
  10870. Request request;
  10871. request.path = "/users/24";
  10872. ASSERT_TRUE(matcher.match(request));
  10873. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10874. EXPECT_EQ(request.path_params, expected_params);
  10875. }
  10876. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10877. const auto pattern = "/users/:id/";
  10878. detail::PathParamsMatcher matcher(pattern);
  10879. Request request;
  10880. request.path = "/users/42/";
  10881. ASSERT_TRUE(matcher.match(request));
  10882. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10883. EXPECT_EQ(request.path_params, expected_params);
  10884. }
  10885. TEST(PathParamsTest, EmptyParam) {
  10886. const auto pattern = "/users/:id/";
  10887. detail::PathParamsMatcher matcher(pattern);
  10888. Request request;
  10889. request.path = "/users//";
  10890. ASSERT_TRUE(matcher.match(request));
  10891. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10892. EXPECT_EQ(request.path_params, expected_params);
  10893. }
  10894. TEST(PathParamsTest, FragmentMismatch) {
  10895. const auto pattern = "/users/:id/";
  10896. detail::PathParamsMatcher matcher(pattern);
  10897. Request request;
  10898. request.path = "/admins/24/";
  10899. ASSERT_FALSE(matcher.match(request));
  10900. }
  10901. TEST(PathParamsTest, ExtraFragments) {
  10902. const auto pattern = "/users/:id";
  10903. detail::PathParamsMatcher matcher(pattern);
  10904. Request request;
  10905. request.path = "/users/42/subscriptions";
  10906. ASSERT_FALSE(matcher.match(request));
  10907. }
  10908. TEST(PathParamsTest, MissingTrailingParam) {
  10909. const auto pattern = "/users/:id";
  10910. detail::PathParamsMatcher matcher(pattern);
  10911. Request request;
  10912. request.path = "/users";
  10913. ASSERT_FALSE(matcher.match(request));
  10914. }
  10915. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10916. const auto pattern = "/users/:id/subscriptions";
  10917. detail::PathParamsMatcher matcher(pattern);
  10918. Request request;
  10919. request.path = "/users/subscriptions";
  10920. ASSERT_FALSE(matcher.match(request));
  10921. }
  10922. TEST(PathParamsTest, MultipleParams) {
  10923. const auto pattern = "/users/:userid/subscriptions/:subid";
  10924. detail::PathParamsMatcher matcher(pattern);
  10925. Request request;
  10926. request.path = "/users/42/subscriptions/2";
  10927. ASSERT_TRUE(matcher.match(request));
  10928. std::unordered_map<std::string, std::string> expected_params = {
  10929. {"userid", "42"}, {"subid", "2"}};
  10930. EXPECT_EQ(request.path_params, expected_params);
  10931. }
  10932. TEST(PathParamsTest, SequenceOfParams) {
  10933. const auto pattern = "/values/:x/:y/:z";
  10934. detail::PathParamsMatcher matcher(pattern);
  10935. Request request;
  10936. request.path = "/values/1/2/3";
  10937. ASSERT_TRUE(matcher.match(request));
  10938. std::unordered_map<std::string, std::string> expected_params = {
  10939. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10940. EXPECT_EQ(request.path_params, expected_params);
  10941. }
  10942. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10943. const auto pattern = "/prefix:suffix";
  10944. detail::PathParamsMatcher matcher(pattern);
  10945. Request request;
  10946. request.path = "/prefix:suffix";
  10947. ASSERT_TRUE(matcher.match(request));
  10948. const std::unordered_map<std::string, std::string> expected_params = {};
  10949. EXPECT_EQ(request.path_params, expected_params);
  10950. }
  10951. TEST(ParseUrlTest, VariousPatterns) {
  10952. {
  10953. detail::UrlComponents uc;
  10954. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10955. EXPECT_EQ("http", uc.scheme);
  10956. EXPECT_EQ("example.com", uc.host);
  10957. EXPECT_EQ("8080", uc.port);
  10958. EXPECT_EQ("/path", uc.path);
  10959. EXPECT_EQ("?q=1", uc.query);
  10960. }
  10961. {
  10962. detail::UrlComponents uc;
  10963. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10964. EXPECT_EQ("https", uc.scheme);
  10965. EXPECT_EQ("example.com", uc.host);
  10966. EXPECT_TRUE(uc.port.empty());
  10967. EXPECT_EQ("/path", uc.path);
  10968. }
  10969. {
  10970. detail::UrlComponents uc;
  10971. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10972. EXPECT_EQ("::1", uc.host);
  10973. EXPECT_EQ("8080", uc.port);
  10974. EXPECT_EQ("/path", uc.path);
  10975. }
  10976. {
  10977. detail::UrlComponents uc;
  10978. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10979. }
  10980. {
  10981. detail::UrlComponents uc;
  10982. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10983. EXPECT_TRUE(uc.scheme.empty());
  10984. EXPECT_EQ("example.com", uc.host);
  10985. EXPECT_EQ("/path", uc.path);
  10986. EXPECT_EQ("?q=1", uc.query);
  10987. }
  10988. {
  10989. detail::UrlComponents uc;
  10990. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10991. EXPECT_TRUE(uc.host.empty());
  10992. EXPECT_EQ("/path", uc.path);
  10993. EXPECT_EQ("?q=1", uc.query);
  10994. }
  10995. {
  10996. detail::UrlComponents uc;
  10997. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10998. EXPECT_EQ("example.com", uc.host);
  10999. EXPECT_EQ("8080", uc.port);
  11000. }
  11001. {
  11002. // Unix socket path — must not be parsed as host
  11003. detail::UrlComponents uc;
  11004. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11005. EXPECT_TRUE(uc.host.empty());
  11006. }
  11007. {
  11008. detail::UrlComponents uc;
  11009. ASSERT_TRUE(detail::parse_url("", uc));
  11010. EXPECT_TRUE(uc.host.empty());
  11011. EXPECT_TRUE(uc.path.empty());
  11012. }
  11013. {
  11014. detail::UrlComponents uc;
  11015. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11016. }
  11017. {
  11018. detail::UrlComponents uc;
  11019. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11020. }
  11021. {
  11022. // Accepted by parse_url; callers restrict to http/https
  11023. detail::UrlComponents uc;
  11024. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11025. EXPECT_EQ("ftp", uc.scheme);
  11026. }
  11027. {
  11028. detail::UrlComponents uc;
  11029. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11030. }
  11031. {
  11032. detail::UrlComponents uc;
  11033. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11034. }
  11035. }
  11036. TEST(ParseUrlTest, FragmentHandling) {
  11037. {
  11038. detail::UrlComponents uc;
  11039. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11040. EXPECT_EQ("/path", uc.path);
  11041. EXPECT_TRUE(uc.query.empty());
  11042. }
  11043. {
  11044. detail::UrlComponents uc;
  11045. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11046. EXPECT_TRUE(uc.path.empty());
  11047. EXPECT_TRUE(uc.query.empty());
  11048. }
  11049. }
  11050. TEST(ParseUrlTest, UserinfoHandling) {
  11051. // Userinfo with @ but no colon — host includes @
  11052. detail::UrlComponents uc;
  11053. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11054. EXPECT_EQ("user@host.com", uc.host);
  11055. EXPECT_EQ("/path", uc.path);
  11056. }
  11057. TEST(ParseUrlTest, IPv6EdgeCases) {
  11058. {
  11059. detail::UrlComponents uc;
  11060. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11061. EXPECT_TRUE(uc.scheme.empty());
  11062. EXPECT_EQ("::1", uc.host);
  11063. EXPECT_EQ("8080", uc.port);
  11064. }
  11065. {
  11066. // Zone ID '%25' is not in [a-fA-F0-9:]
  11067. detail::UrlComponents uc;
  11068. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11069. }
  11070. }
  11071. TEST(ParseUrlTest, SchemeEdgeCases) {
  11072. {
  11073. detail::UrlComponents uc;
  11074. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11075. }
  11076. {
  11077. detail::UrlComponents uc;
  11078. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11079. }
  11080. {
  11081. detail::UrlComponents uc;
  11082. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11083. }
  11084. }
  11085. TEST(ParseUrlTest, PortEdgeCases) {
  11086. {
  11087. detail::UrlComponents uc;
  11088. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11089. EXPECT_TRUE(uc.port.empty());
  11090. EXPECT_EQ("/path", uc.path);
  11091. }
  11092. {
  11093. // parse_url accepts any port string; validation is done by parse_port
  11094. detail::UrlComponents uc;
  11095. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11096. EXPECT_EQ("abc", uc.port);
  11097. }
  11098. }
  11099. TEST(ParseUrlTest, WebSocketPatterns) {
  11100. {
  11101. detail::UrlComponents uc;
  11102. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11103. EXPECT_EQ("ws", uc.scheme);
  11104. EXPECT_EQ("echo.example.com", uc.host);
  11105. EXPECT_EQ("8080", uc.port);
  11106. EXPECT_EQ("/ws", uc.path);
  11107. }
  11108. {
  11109. detail::UrlComponents uc;
  11110. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11111. EXPECT_EQ("wss", uc.scheme);
  11112. EXPECT_EQ("echo.example.com", uc.host);
  11113. EXPECT_TRUE(uc.port.empty());
  11114. EXPECT_EQ("/ws", uc.path);
  11115. }
  11116. }
  11117. TEST(ParseUrlTest, QueryOnly) {
  11118. detail::UrlComponents uc;
  11119. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11120. EXPECT_TRUE(uc.host.empty());
  11121. EXPECT_TRUE(uc.path.empty());
  11122. EXPECT_EQ("?q=1&r=2", uc.query);
  11123. }
  11124. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11125. detail::UrlComponents uc;
  11126. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11127. EXPECT_TRUE(uc.scheme.empty());
  11128. EXPECT_EQ("example.com", uc.host);
  11129. EXPECT_EQ("443", uc.port);
  11130. EXPECT_EQ("/path", uc.path);
  11131. }
  11132. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11133. // If ipv6 regex working, regex match codepath is taken.
  11134. // else port will default to 80 in Client impl
  11135. int clientImplMagicPort = 80;
  11136. int port = 4321;
  11137. // above ports must be different to avoid false negative
  11138. EXPECT_NE(clientImplMagicPort, port);
  11139. std::string ipV6TestURL = "http://[ff06::c3]";
  11140. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11141. CLIENT_PRIVATE_KEY_FILE);
  11142. EXPECT_EQ(cli.port(), port);
  11143. }
  11144. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11145. auto file_path = "./www/dir/index.html";
  11146. auto dir_path = "./www/dir";
  11147. detail::FileStat stat_file(file_path);
  11148. EXPECT_TRUE(stat_file.is_file());
  11149. EXPECT_FALSE(stat_file.is_dir());
  11150. detail::FileStat stat_dir(dir_path);
  11151. EXPECT_FALSE(stat_dir.is_file());
  11152. EXPECT_TRUE(stat_dir.is_dir());
  11153. }
  11154. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11155. // IPv4 with default HTTP port (80)
  11156. EXPECT_EQ("example.com",
  11157. detail::make_host_and_port_string("example.com", 80, false));
  11158. // IPv4 with default HTTPS port (443)
  11159. EXPECT_EQ("example.com",
  11160. detail::make_host_and_port_string("example.com", 443, true));
  11161. // IPv4 with non-default HTTP port
  11162. EXPECT_EQ("example.com:8080",
  11163. detail::make_host_and_port_string("example.com", 8080, false));
  11164. // IPv4 with non-default HTTPS port
  11165. EXPECT_EQ("example.com:8443",
  11166. detail::make_host_and_port_string("example.com", 8443, true));
  11167. // IPv6 with default HTTP port (80)
  11168. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11169. // IPv6 with default HTTPS port (443)
  11170. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11171. // IPv6 with non-default HTTP port
  11172. EXPECT_EQ("[::1]:8080",
  11173. detail::make_host_and_port_string("::1", 8080, false));
  11174. // IPv6 with non-default HTTPS port
  11175. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11176. // IPv6 full address with default port
  11177. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11178. detail::make_host_and_port_string(
  11179. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11180. // IPv6 full address with non-default port
  11181. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11182. detail::make_host_and_port_string(
  11183. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11184. // IPv6 localhost with non-default port
  11185. EXPECT_EQ("[::1]:3000",
  11186. detail::make_host_and_port_string("::1", 3000, false));
  11187. // IPv6 with zone ID (link-local address) with default port
  11188. EXPECT_EQ("[fe80::1%eth0]",
  11189. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11190. // IPv6 with zone ID (link-local address) with non-default port
  11191. EXPECT_EQ("[fe80::1%eth0]:8080",
  11192. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11193. // Edge case: Port 443 with is_ssl=false (should add port)
  11194. EXPECT_EQ("example.com:443",
  11195. detail::make_host_and_port_string("example.com", 443, false));
  11196. // Edge case: Port 80 with is_ssl=true (should add port)
  11197. EXPECT_EQ("example.com:80",
  11198. detail::make_host_and_port_string("example.com", 80, true));
  11199. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11200. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11201. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11202. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11203. // Security fix: Already bracketed IPv6 should not get double brackets
  11204. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11205. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11206. EXPECT_EQ("[::1]:8080",
  11207. detail::make_host_and_port_string("[::1]", 8080, false));
  11208. EXPECT_EQ("[2001:db8::1]:8080",
  11209. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11210. EXPECT_EQ("[fe80::1%eth0]",
  11211. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11212. EXPECT_EQ("[fe80::1%eth0]:8080",
  11213. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11214. // Edge case: Empty host (should return as-is)
  11215. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11216. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11217. // This is a known limitation but shouldn't crash
  11218. EXPECT_EQ("[host:name]",
  11219. detail::make_host_and_port_string("host:name", 80, false));
  11220. // Port number edge cases (no validation, but should not crash)
  11221. EXPECT_EQ("example.com:0",
  11222. detail::make_host_and_port_string("example.com", 0, false));
  11223. EXPECT_EQ("example.com:-1",
  11224. detail::make_host_and_port_string("example.com", -1, false));
  11225. EXPECT_EQ("example.com:65535",
  11226. detail::make_host_and_port_string("example.com", 65535, false));
  11227. EXPECT_EQ("example.com:65536",
  11228. detail::make_host_and_port_string("example.com", 65536, false));
  11229. }
  11230. #ifdef CPPHTTPLIB_SSL_ENABLED
  11231. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11232. httplib::SSLClient cli("roblox.com", 443);
  11233. cli.set_follow_location(true);
  11234. auto res = cli.Get("/");
  11235. ASSERT_TRUE(res);
  11236. EXPECT_EQ(StatusCode::OK_200, res->status);
  11237. }
  11238. #endif
  11239. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11240. Server svr;
  11241. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11242. EXPECT_EQ(res.status, 400);
  11243. });
  11244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. thread.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, PORT);
  11252. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11253. }
  11254. TEST(InvalidHeaderCharsTest, is_field_name) {
  11255. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11256. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11257. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11258. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11259. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11260. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11261. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11262. EXPECT_FALSE(detail::fields::is_field_name(""));
  11263. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11264. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11265. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11266. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11267. }
  11268. TEST(InvalidHeaderCharsTest, is_field_value) {
  11269. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11270. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11271. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11272. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11273. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11274. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11275. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11276. EXPECT_TRUE(detail::fields::is_field_value(""));
  11277. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11278. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11279. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11280. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11281. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11282. }
  11283. TEST(InvalidHeaderCharsTest, OnServer) {
  11284. Server svr;
  11285. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11286. std::string header = "Not Set";
  11287. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11288. res.set_header(header, "value");
  11289. res.set_content("Page Content Page Content", "text/plain");
  11290. });
  11291. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11292. std::string header = "Not Set";
  11293. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11294. res.set_header("X-Test", header);
  11295. res.set_content("Page Content Page Content", "text/plain");
  11296. });
  11297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, PORT);
  11305. {
  11306. auto res = cli.Get(
  11307. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11308. ASSERT_TRUE(res);
  11309. EXPECT_EQ("Page Content Page Content", res->body);
  11310. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11311. }
  11312. {
  11313. auto res = cli.Get(
  11314. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11315. ASSERT_TRUE(res);
  11316. EXPECT_EQ("Page Content Page Content", res->body);
  11317. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11318. }
  11319. }
  11320. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11321. auto handled = false;
  11322. Server svr;
  11323. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11324. thread t = thread([&] { svr.listen(HOST, PORT); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. ASSERT_FALSE(handled);
  11330. });
  11331. svr.wait_until_ready();
  11332. auto req = "POST /test HTTP/1.1\r\n"
  11333. "Content-Length: x\r\n"
  11334. "\r\n";
  11335. std::string response;
  11336. ASSERT_TRUE(send_request(1, req, &response));
  11337. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11338. response.substr(0, response.find("\r\n")));
  11339. }
  11340. #ifndef _WIN32
  11341. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11342. static constexpr char reject[] = "Unauthorized";
  11343. static constexpr char accept[] = "Upload accepted";
  11344. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11345. Server svr;
  11346. svr.set_expect_100_continue_handler(
  11347. [](const Request & /*req*/, Response &res) {
  11348. res.status = StatusCode::Unauthorized_401;
  11349. res.set_content(reject, "text/plain");
  11350. return res.status;
  11351. });
  11352. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11353. res.set_content(accept, "text/plain");
  11354. });
  11355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11356. auto se = detail::scope_exit([&] {
  11357. svr.stop();
  11358. thread.join();
  11359. ASSERT_FALSE(svr.is_running());
  11360. });
  11361. svr.wait_until_ready();
  11362. {
  11363. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11364. curl_easy_init(), &curl_easy_cleanup};
  11365. ASSERT_NE(curl, nullptr);
  11366. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11367. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11368. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11369. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11370. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11371. &curl_slist_free_all};
  11372. ASSERT_NE(list, nullptr);
  11373. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11374. struct read_data {
  11375. size_t read_size;
  11376. size_t total_size;
  11377. } data = {0, total_size};
  11378. using read_callback_t =
  11379. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11380. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11381. void *userdata) -> size_t {
  11382. read_data *d = (read_data *)userdata;
  11383. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11384. std::fill_n(ptr, size * nmemb, 'A');
  11385. d->read_size += size * nmemb;
  11386. return size * nmemb;
  11387. };
  11388. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11389. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11390. std::vector<char> buffer;
  11391. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11392. using write_callback_t =
  11393. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11394. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11395. void *userdata) -> size_t {
  11396. std::vector<char> *buf = (std::vector<char> *)userdata;
  11397. buf->reserve(buf->size() + size * nmemb + 1);
  11398. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11399. return size * nmemb;
  11400. };
  11401. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11402. {
  11403. const auto res = curl_easy_perform(curl.get());
  11404. ASSERT_EQ(res, CURLE_OK);
  11405. }
  11406. {
  11407. auto response_code = long{};
  11408. const auto res =
  11409. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11410. ASSERT_EQ(res, CURLE_OK);
  11411. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11412. }
  11413. {
  11414. auto dl = curl_off_t{};
  11415. const auto res =
  11416. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11417. ASSERT_EQ(res, CURLE_OK);
  11418. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11419. }
  11420. {
  11421. buffer.push_back('\0');
  11422. ASSERT_STRCASEEQ(buffer.data(), reject);
  11423. }
  11424. }
  11425. }
  11426. #endif
  11427. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11428. // Regression test for #2458.
  11429. //
  11430. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11431. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11432. // ticket can make the client socket spuriously readable during the
  11433. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11434. // the client withholds the body and then blocks reading a response that never
  11435. // comes, failing with `Failed to read connection`.
  11436. //
  11437. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11438. // within the timeout. This raw OpenSSL server deliberately never sends
  11439. // `100 Continue`; the client must still deliver the body and receive 200.
  11440. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11441. signal(SIGPIPE, SIG_IGN);
  11442. const auto port = PORT + 4;
  11443. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11444. ASSERT_NE(srv, INVALID_SOCKET);
  11445. int opt = 1;
  11446. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11447. sockaddr_in addr{};
  11448. addr.sin_family = AF_INET;
  11449. addr.sin_port = htons(static_cast<uint16_t>(port));
  11450. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11451. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11452. ASSERT_EQ(0, ::listen(srv, 1));
  11453. std::atomic<size_t> server_body_bytes{0};
  11454. auto server_thread = std::thread([&] {
  11455. sockaddr_in cli_addr{};
  11456. socklen_t cli_len = sizeof(cli_addr);
  11457. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11458. if (cli == INVALID_SOCKET) { return; }
  11459. // Bound the lifetime of the server side so a buggy client (which never
  11460. // sends the body) cannot make this thread block forever on join.
  11461. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11462. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11463. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11464. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11465. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11466. SSL *ssl = SSL_new(ctx);
  11467. SSL_set_fd(ssl, static_cast<int>(cli));
  11468. if (SSL_accept(ssl) > 0) {
  11469. // Read the request headers. Reading here also flushes the TLS 1.3
  11470. // session tickets to the client. Deliberately do NOT send
  11471. // `100 Continue`.
  11472. std::string buf;
  11473. char tmp[1024];
  11474. while (buf.find("\r\n\r\n") == std::string::npos) {
  11475. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11476. if (n <= 0) { break; }
  11477. buf.append(tmp, static_cast<size_t>(n));
  11478. }
  11479. // A correct client sends the body now; count what arrives.
  11480. auto pos = buf.find("\r\n\r\n");
  11481. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11482. while (body < 4096) {
  11483. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11484. if (n <= 0) { break; }
  11485. body += static_cast<size_t>(n);
  11486. }
  11487. server_body_bytes = body;
  11488. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11489. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11490. SSL_shutdown(ssl);
  11491. }
  11492. SSL_free(ssl);
  11493. detail::close_socket(cli);
  11494. SSL_CTX_free(ctx);
  11495. });
  11496. auto se = detail::scope_exit([&] {
  11497. server_thread.join();
  11498. detail::close_socket(srv);
  11499. });
  11500. SSLClient cli("127.0.0.1", port);
  11501. cli.enable_server_certificate_verification(false);
  11502. cli.set_connection_timeout(5, 0);
  11503. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11504. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11505. std::string body(4096, 'A');
  11506. auto res = cli.Put("/api/test", body, "application/json");
  11507. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11508. EXPECT_EQ(StatusCode::OK_200, res->status);
  11509. EXPECT_EQ(body.size(), server_body_bytes.load());
  11510. }
  11511. #endif
  11512. template <typename S, typename C>
  11513. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11514. svr.Get("/stream", [&](const Request &, Response &res) {
  11515. auto data = new std::string("01234567890123456789");
  11516. res.set_content_provider(
  11517. data->size(), "text/plain",
  11518. [&, data](size_t offset, size_t length, DataSink &sink) {
  11519. const size_t DATA_CHUNK_SIZE = 4;
  11520. const auto &d = *data;
  11521. std::this_thread::sleep_for(std::chrono::seconds(1));
  11522. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11523. return true;
  11524. },
  11525. [data](bool success) {
  11526. EXPECT_FALSE(success);
  11527. delete data;
  11528. });
  11529. });
  11530. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11531. auto i = new size_t(0);
  11532. res.set_content_provider(
  11533. "text/plain",
  11534. [i](size_t, DataSink &sink) {
  11535. if (*i < 5) {
  11536. std::this_thread::sleep_for(std::chrono::seconds(1));
  11537. sink.write("abcd", 4);
  11538. (*i)++;
  11539. } else {
  11540. sink.done();
  11541. }
  11542. return true;
  11543. },
  11544. [i](bool success) {
  11545. EXPECT_FALSE(success);
  11546. delete i;
  11547. });
  11548. });
  11549. svr.Get("/chunked", [&](const Request &, Response &res) {
  11550. auto i = new size_t(0);
  11551. res.set_chunked_content_provider(
  11552. "text/plain",
  11553. [i](size_t, DataSink &sink) {
  11554. if (*i < 5) {
  11555. std::this_thread::sleep_for(std::chrono::seconds(1));
  11556. sink.os << "abcd";
  11557. (*i)++;
  11558. } else {
  11559. sink.done();
  11560. }
  11561. return true;
  11562. },
  11563. [i](bool success) {
  11564. EXPECT_FALSE(success);
  11565. delete i;
  11566. });
  11567. });
  11568. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11569. auto se = detail::scope_exit([&] {
  11570. svr.stop();
  11571. listen_thread.join();
  11572. ASSERT_FALSE(svr.is_running());
  11573. });
  11574. svr.wait_until_ready();
  11575. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11576. {
  11577. auto start = std::chrono::steady_clock::now();
  11578. auto res = cli.Get("/stream");
  11579. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11580. std::chrono::steady_clock::now() - start)
  11581. .count();
  11582. ASSERT_FALSE(res);
  11583. EXPECT_EQ(Error::Read, res.error());
  11584. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11585. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11586. }
  11587. {
  11588. auto start = std::chrono::steady_clock::now();
  11589. auto res = cli.Get("/stream_without_length");
  11590. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11591. std::chrono::steady_clock::now() - start)
  11592. .count();
  11593. ASSERT_FALSE(res);
  11594. EXPECT_EQ(Error::Read, res.error());
  11595. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11596. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11597. }
  11598. {
  11599. auto start = std::chrono::steady_clock::now();
  11600. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11601. EXPECT_EQ("abcd", string(data, data_length));
  11602. return true;
  11603. });
  11604. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11605. std::chrono::steady_clock::now() - start)
  11606. .count();
  11607. ASSERT_FALSE(res);
  11608. EXPECT_EQ(Error::Read, res.error());
  11609. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11610. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11611. }
  11612. }
  11613. TEST(MaxTimeoutTest, ContentStream) {
  11614. time_t timeout = 2000;
  11615. time_t threshold = 200;
  11616. Server svr;
  11617. Client cli("localhost", PORT);
  11618. max_timeout_test(svr, cli, timeout, threshold);
  11619. }
  11620. #ifdef CPPHTTPLIB_SSL_ENABLED
  11621. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11622. time_t timeout = 2000;
  11623. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11625. SSLClient cli("localhost", PORT);
  11626. cli.enable_server_certificate_verification(false);
  11627. max_timeout_test(svr, cli, timeout, threshold);
  11628. }
  11629. #endif
  11630. class EventDispatcher {
  11631. public:
  11632. EventDispatcher() {}
  11633. bool wait_event(DataSink *sink) {
  11634. unique_lock<mutex> lk(m_);
  11635. int id = id_;
  11636. // Wait with timeout to prevent hanging if client disconnects
  11637. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11638. [&] { return cid_ == id; })) {
  11639. return false; // Timeout occurred
  11640. }
  11641. sink->write(message_.data(), message_.size());
  11642. return true;
  11643. }
  11644. void send_event(const string &message) {
  11645. lock_guard<mutex> lk(m_);
  11646. cid_ = id_++;
  11647. message_ = message;
  11648. cv_.notify_all();
  11649. }
  11650. private:
  11651. mutex m_;
  11652. condition_variable cv_;
  11653. atomic_int id_{0};
  11654. atomic_int cid_{-1};
  11655. string message_;
  11656. };
  11657. TEST(ClientInThreadTest, Issue2068) {
  11658. EventDispatcher ed;
  11659. Server svr;
  11660. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11661. res.set_chunked_content_provider("text/event-stream",
  11662. [&](size_t /*offset*/, DataSink &sink) {
  11663. return ed.wait_event(&sink);
  11664. });
  11665. });
  11666. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11667. svr.wait_until_ready();
  11668. thread event_thread([&] {
  11669. int id = 0;
  11670. while (svr.is_running()) {
  11671. this_thread::sleep_for(chrono::milliseconds(500));
  11672. std::stringstream ss;
  11673. ss << "data: " << id << "\n\n";
  11674. ed.send_event(ss.str());
  11675. id++;
  11676. }
  11677. });
  11678. auto se = detail::scope_exit([&] {
  11679. svr.stop();
  11680. listen_thread.join();
  11681. event_thread.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. {
  11685. auto client = detail::make_unique<Client>(HOST, PORT);
  11686. client->set_read_timeout(std::chrono::minutes(10));
  11687. std::atomic<bool> stop{false};
  11688. std::thread t([&] {
  11689. client->Get("/event1",
  11690. [&](const char *, size_t) -> bool { return !stop; });
  11691. });
  11692. std::this_thread::sleep_for(std::chrono::seconds(2));
  11693. stop = true;
  11694. client->stop();
  11695. t.join();
  11696. // Reset client after thread has finished
  11697. client.reset();
  11698. }
  11699. }
  11700. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11701. auto handled = false;
  11702. Server svr;
  11703. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11705. auto se = detail::scope_exit([&] {
  11706. svr.stop();
  11707. t.join();
  11708. ASSERT_FALSE(svr.is_running());
  11709. ASSERT_FALSE(handled);
  11710. });
  11711. svr.wait_until_ready();
  11712. // Two Content-Length headers with different values — must be rejected
  11713. auto req = "POST /test HTTP/1.1\r\n"
  11714. "Content-Length: 5\r\n"
  11715. "Content-Length: 10\r\n"
  11716. "\r\n"
  11717. "hello";
  11718. std::string response;
  11719. ASSERT_TRUE(send_request(1, req, &response));
  11720. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11721. response.substr(0, response.find("\r\n")));
  11722. }
  11723. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11724. auto handled = false;
  11725. Server svr;
  11726. svr.Post("/test", [&](const Request &, Response &res) {
  11727. handled = true;
  11728. res.set_content("ok", "text/plain");
  11729. });
  11730. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. t.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. ASSERT_TRUE(handled);
  11736. });
  11737. svr.wait_until_ready();
  11738. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11739. auto req = "POST /test HTTP/1.1\r\n"
  11740. "Content-Length: 5\r\n"
  11741. "Content-Length: 5\r\n"
  11742. "\r\n"
  11743. "hello";
  11744. std::string response;
  11745. ASSERT_TRUE(send_request(1, req, &response));
  11746. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11747. }
  11748. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11749. Server svr;
  11750. svr.Get("/", [](const Request &req, Response &res) {
  11751. EXPECT_EQ(2U, req.trailers.size());
  11752. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11753. // Denied
  11754. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11755. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11756. // Accepted
  11757. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11758. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11759. EXPECT_TRUE(req.has_trailer("X-World"));
  11760. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11761. res.set_content("ok", "text/plain");
  11762. });
  11763. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11764. auto se = detail::scope_exit([&] {
  11765. svr.stop();
  11766. t.join();
  11767. ASSERT_FALSE(svr.is_running());
  11768. });
  11769. svr.wait_until_ready();
  11770. const std::string req = "GET / HTTP/1.1\r\n"
  11771. "Transfer-Encoding: chunked\r\n"
  11772. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11773. "\r\n"
  11774. "0\r\n"
  11775. "Content-Length: 10\r\n"
  11776. "Host: internal.local\r\n"
  11777. "Content-Type: malicious/content\r\n"
  11778. "Cookie: any\r\n"
  11779. "Set-Cookie: any\r\n"
  11780. "X-Forwarded-For: attacker.com\r\n"
  11781. "X-Real-Ip: 1.1.1.1\r\n"
  11782. "X-Hello: hello\r\n"
  11783. "X-World: world\r\n"
  11784. "\r\n";
  11785. std::string res;
  11786. ASSERT_TRUE(send_request(1, req, &res));
  11787. }
  11788. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11789. Server svr;
  11790. std::string observed_remote_addr;
  11791. std::string observed_xff;
  11792. svr.Get("/ip", [&](const Request &req, Response &res) {
  11793. observed_remote_addr = req.remote_addr;
  11794. observed_xff = req.get_header_value("X-Forwarded-For");
  11795. res.set_content("ok", "text/plain");
  11796. });
  11797. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11798. auto se = detail::scope_exit([&] {
  11799. svr.stop();
  11800. t.join();
  11801. ASSERT_FALSE(svr.is_running());
  11802. });
  11803. svr.wait_until_ready();
  11804. Client cli(HOST, PORT);
  11805. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11806. ASSERT_TRUE(res);
  11807. EXPECT_EQ(StatusCode::OK_200, res->status);
  11808. EXPECT_EQ(observed_xff, "203.0.113.66");
  11809. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11810. observed_remote_addr == "127.0.0.1");
  11811. }
  11812. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11813. Server svr;
  11814. svr.set_trusted_proxies({"203.0.113.66"});
  11815. std::string observed_remote_addr;
  11816. std::string observed_xff;
  11817. svr.Get("/ip", [&](const Request &req, Response &res) {
  11818. observed_remote_addr = req.remote_addr;
  11819. observed_xff = req.get_header_value("X-Forwarded-For");
  11820. res.set_content("ok", "text/plain");
  11821. });
  11822. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11823. auto se = detail::scope_exit([&] {
  11824. svr.stop();
  11825. t.join();
  11826. ASSERT_FALSE(svr.is_running());
  11827. });
  11828. svr.wait_until_ready();
  11829. Client cli(HOST, PORT);
  11830. auto res = cli.Get("/ip");
  11831. ASSERT_TRUE(res);
  11832. EXPECT_EQ(StatusCode::OK_200, res->status);
  11833. EXPECT_EQ(observed_xff, "");
  11834. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11835. observed_remote_addr == "127.0.0.1");
  11836. }
  11837. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11838. Server svr;
  11839. svr.set_trusted_proxies({"203.0.113.66"});
  11840. std::string observed_remote_addr;
  11841. std::string observed_xff;
  11842. svr.Get("/ip", [&](const Request &req, Response &res) {
  11843. observed_remote_addr = req.remote_addr;
  11844. observed_xff = req.get_header_value("X-Forwarded-For");
  11845. res.set_content("ok", "text/plain");
  11846. });
  11847. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11848. auto se = detail::scope_exit([&] {
  11849. svr.stop();
  11850. t.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli(HOST, PORT);
  11855. auto res =
  11856. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11857. ASSERT_TRUE(res);
  11858. EXPECT_EQ(StatusCode::OK_200, res->status);
  11859. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11860. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11861. }
  11862. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11863. Server svr;
  11864. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11865. std::string observed_remote_addr;
  11866. std::string observed_xff;
  11867. svr.Get("/ip", [&](const Request &req, Response &res) {
  11868. observed_remote_addr = req.remote_addr;
  11869. observed_xff = req.get_header_value("X-Forwarded-For");
  11870. res.set_content("ok", "text/plain");
  11871. });
  11872. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11873. auto se = detail::scope_exit([&] {
  11874. svr.stop();
  11875. t.join();
  11876. ASSERT_FALSE(svr.is_running());
  11877. });
  11878. svr.wait_until_ready();
  11879. Client cli(HOST, PORT);
  11880. auto res = cli.Get(
  11881. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11882. ASSERT_TRUE(res);
  11883. EXPECT_EQ(StatusCode::OK_200, res->status);
  11884. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11885. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11886. }
  11887. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11888. Server svr;
  11889. svr.set_trusted_proxies({"192.0.2.45"});
  11890. std::string observed_remote_addr;
  11891. std::string observed_xff;
  11892. svr.Get("/ip", [&](const Request &req, Response &res) {
  11893. observed_remote_addr = req.remote_addr;
  11894. observed_xff = req.get_header_value("X-Forwarded-For");
  11895. res.set_content("ok", "text/plain");
  11896. });
  11897. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11898. auto se = detail::scope_exit([&] {
  11899. svr.stop();
  11900. t.join();
  11901. ASSERT_FALSE(svr.is_running());
  11902. });
  11903. svr.wait_until_ready();
  11904. Client cli(HOST, PORT);
  11905. auto res =
  11906. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11907. ASSERT_TRUE(res);
  11908. EXPECT_EQ(StatusCode::OK_200, res->status);
  11909. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11910. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11911. }
  11912. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11913. Server svr;
  11914. svr.set_trusted_proxies({"192.0.2.45"});
  11915. std::string observed_remote_addr;
  11916. std::string observed_xff;
  11917. svr.Get("/ip", [&](const Request &req, Response &res) {
  11918. observed_remote_addr = req.remote_addr;
  11919. observed_xff = req.get_header_value("X-Forwarded-For");
  11920. res.set_content("ok", "text/plain");
  11921. });
  11922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11923. auto se = detail::scope_exit([&] {
  11924. svr.stop();
  11925. t.join();
  11926. ASSERT_FALSE(svr.is_running());
  11927. });
  11928. svr.wait_until_ready();
  11929. Client cli(HOST, PORT);
  11930. auto res = cli.Get(
  11931. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11932. ASSERT_TRUE(res);
  11933. EXPECT_EQ(StatusCode::OK_200, res->status);
  11934. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11935. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11936. }
  11937. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11938. Server svr;
  11939. svr.set_trusted_proxies({"192.0.2.45"});
  11940. std::string observed_remote_addr;
  11941. std::string observed_xff;
  11942. svr.Get("/ip", [&](const Request &req, Response &res) {
  11943. observed_remote_addr = req.remote_addr;
  11944. observed_xff = req.get_header_value("X-Forwarded-For");
  11945. res.set_content("ok", "text/plain");
  11946. });
  11947. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11948. auto se = detail::scope_exit([&] {
  11949. svr.stop();
  11950. t.join();
  11951. ASSERT_FALSE(svr.is_running());
  11952. });
  11953. svr.wait_until_ready();
  11954. std::string raw_req =
  11955. "GET /ip HTTP/1.1\r\n"
  11956. "Host: localhost\r\n"
  11957. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11958. "Connection: close\r\n"
  11959. "\r\n";
  11960. std::string out;
  11961. ASSERT_TRUE(send_request(5, raw_req, &out));
  11962. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11963. // Header parser trims surrounding whitespace of the header value
  11964. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11965. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11966. }
  11967. // An X-Forwarded-For header whose value parses to zero IP segments must not
  11968. // crash the server (it used to call front() on an empty vector inside
  11969. // get_client_ip). The connection-level remote address must be retained instead.
  11970. static void run_malformed_xff_test(const std::string &xff_value) {
  11971. Server svr;
  11972. svr.set_trusted_proxies({"192.0.2.45"});
  11973. std::string observed_remote_addr;
  11974. svr.Get("/ip", [&](const Request &req, Response &res) {
  11975. observed_remote_addr = req.remote_addr;
  11976. res.set_content("ok", "text/plain");
  11977. });
  11978. int port = 0;
  11979. thread t = thread([&]() {
  11980. port = svr.bind_to_any_port(HOST);
  11981. svr.listen_after_bind();
  11982. });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. t.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. Client cli(HOST, port);
  11990. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  11991. ASSERT_TRUE(res);
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11994. observed_remote_addr == "127.0.0.1");
  11995. }
  11996. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  11997. run_malformed_xff_test("");
  11998. }
  11999. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12000. run_malformed_xff_test(",");
  12001. }
  12002. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12003. run_malformed_xff_test(", , ,");
  12004. }
  12005. #ifndef _WIN32
  12006. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12007. Server svr;
  12008. svr.Post("/post", [&](const Request &req, Response &res) {
  12009. res.set_content(req.body, "text/plain");
  12010. });
  12011. svr.Put("/put", [&](const Request &req, Response &res) {
  12012. res.set_content(req.body, "text/plain");
  12013. });
  12014. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12015. res.set_content(req.body, "text/plain");
  12016. });
  12017. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12018. res.set_content(req.body, "text/plain");
  12019. });
  12020. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12021. auto se = detail::scope_exit([&] {
  12022. svr.stop();
  12023. t.join();
  12024. ASSERT_FALSE(svr.is_running());
  12025. });
  12026. svr.wait_until_ready();
  12027. std::string resp;
  12028. // POST without Content-Length
  12029. ASSERT_TRUE(send_request(5,
  12030. "POST /post HTTP/1.1\r\n"
  12031. "Host: localhost\r\n"
  12032. "Connection: close\r\n"
  12033. "\r\n",
  12034. &resp));
  12035. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12036. // PUT without Content-Length
  12037. resp.clear();
  12038. ASSERT_TRUE(send_request(5,
  12039. "PUT /put HTTP/1.1\r\n"
  12040. "Host: localhost\r\n"
  12041. "Connection: close\r\n"
  12042. "\r\n",
  12043. &resp));
  12044. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12045. // PATCH without Content-Length
  12046. resp.clear();
  12047. ASSERT_TRUE(send_request(5,
  12048. "PATCH /patch HTTP/1.1\r\n"
  12049. "Host: localhost\r\n"
  12050. "Connection: close\r\n"
  12051. "\r\n",
  12052. &resp));
  12053. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12054. // DELETE without Content-Length
  12055. resp.clear();
  12056. ASSERT_TRUE(send_request(5,
  12057. "DELETE /delete HTTP/1.1\r\n"
  12058. "Host: localhost\r\n"
  12059. "Connection: close\r\n"
  12060. "\r\n",
  12061. &resp));
  12062. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12063. }
  12064. #endif
  12065. //==============================================================================
  12066. // open_stream() Tests
  12067. //==============================================================================
  12068. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12069. std::string result;
  12070. char buf[8192];
  12071. ssize_t n;
  12072. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12073. result.append(buf, static_cast<size_t>(n));
  12074. }
  12075. return result;
  12076. }
  12077. // Mock stream for unit tests
  12078. class MockStream : public Stream {
  12079. public:
  12080. std::string data;
  12081. size_t pos = 0;
  12082. ssize_t error_after = -1; // -1 = no error
  12083. explicit MockStream(const std::string &d, ssize_t err = -1)
  12084. : data(d), error_after(err) {}
  12085. bool is_readable() const override { return true; }
  12086. bool wait_readable() const override { return true; }
  12087. bool wait_writable() const override { return true; }
  12088. ssize_t read(char *ptr, size_t size) override {
  12089. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12090. if (pos >= data.size()) return 0;
  12091. size_t limit =
  12092. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12093. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12094. std::memcpy(ptr, data.data() + pos, to_read);
  12095. pos += to_read;
  12096. return static_cast<ssize_t>(to_read);
  12097. }
  12098. ssize_t write(const char *, size_t) override { return -1; }
  12099. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12100. ip = "127.0.0.1";
  12101. port = 0;
  12102. }
  12103. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12104. ip = "127.0.0.1";
  12105. port = 0;
  12106. }
  12107. socket_t socket() const override { return INVALID_SOCKET; }
  12108. time_t duration() const override { return 0; }
  12109. };
  12110. TEST(StreamHandleTest, Basic) {
  12111. ClientImpl::StreamHandle handle;
  12112. EXPECT_FALSE(handle.is_valid());
  12113. handle.response = detail::make_unique<Response>();
  12114. handle.error = Error::Connection;
  12115. EXPECT_FALSE(handle.is_valid());
  12116. handle.error = Error::Success;
  12117. EXPECT_TRUE(handle.is_valid());
  12118. }
  12119. TEST(BodyReaderTest, Basic) {
  12120. MockStream stream("Hello, World!");
  12121. detail::BodyReader reader;
  12122. reader.stream = &stream;
  12123. reader.content_length = 13;
  12124. char buf[32];
  12125. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12126. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12127. EXPECT_TRUE(reader.eof);
  12128. }
  12129. TEST(BodyReaderTest, NoStream) {
  12130. detail::BodyReader reader;
  12131. char buf[32];
  12132. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12133. EXPECT_EQ(Error::Connection, reader.last_error);
  12134. }
  12135. TEST(BodyReaderTest, Error) {
  12136. MockStream stream("Hello, World!", 5);
  12137. detail::BodyReader reader;
  12138. reader.stream = &stream;
  12139. reader.content_length = 13;
  12140. char buf[32];
  12141. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12142. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12143. EXPECT_EQ(Error::Read, reader.last_error);
  12144. }
  12145. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12146. // Mock-based StreamHandle tests relying on private internals are removed.
  12147. class OpenStreamTest : public ::testing::Test {
  12148. protected:
  12149. void SetUp() override {
  12150. svr_.Get("/hello", [](const Request &, Response &res) {
  12151. res.set_content("Hello World!", "text/plain");
  12152. });
  12153. svr_.Get("/large", [](const Request &, Response &res) {
  12154. res.set_content(std::string(10000, 'X'), "text/plain");
  12155. });
  12156. svr_.Get("/chunked", [](const Request &, Response &res) {
  12157. res.set_chunked_content_provider("text/plain",
  12158. [](size_t offset, DataSink &sink) {
  12159. if (offset < 15) {
  12160. sink.write("chunk", 5);
  12161. return true;
  12162. }
  12163. sink.done();
  12164. return true;
  12165. });
  12166. });
  12167. svr_.Get("/compressible", [](const Request &, Response &res) {
  12168. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12169. DataSink &sink) {
  12170. if (offset < 100 * 1024) {
  12171. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12172. sink.write(chunk.data(), chunk.size());
  12173. return true;
  12174. }
  12175. sink.done();
  12176. return true;
  12177. });
  12178. });
  12179. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12180. [](const Request & /*req*/, Response &res) {
  12181. auto i = new int(0);
  12182. res.set_header("Trailer", "Content-Length, X-Allowed");
  12183. res.set_chunked_content_provider(
  12184. "text/plain",
  12185. [i](size_t /*offset*/, DataSink &sink) {
  12186. switch (*i) {
  12187. case 0: sink.os << "123"; break;
  12188. case 1: sink.os << "456"; break;
  12189. case 2: sink.os << "789"; break;
  12190. case 3: {
  12191. sink.done_with_trailer(
  12192. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12193. } break;
  12194. }
  12195. (*i)++;
  12196. return true;
  12197. },
  12198. [i](bool success) {
  12199. EXPECT_TRUE(success);
  12200. delete i;
  12201. });
  12202. });
  12203. // Echo headers endpoint for header-related tests
  12204. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12205. std::string body;
  12206. for (const auto &h : req.headers) {
  12207. body.append(h.first);
  12208. body.push_back(':');
  12209. body.append(h.second);
  12210. body.push_back('\n');
  12211. }
  12212. res.set_content(body, "text/plain");
  12213. });
  12214. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12215. std::string body;
  12216. for (const auto &h : req.headers) {
  12217. body.append(h.first);
  12218. body.push_back(':');
  12219. body.append(h.second);
  12220. body.push_back('\n');
  12221. }
  12222. res.set_content(body, "text/plain");
  12223. });
  12224. port_ = svr_.bind_to_any_port("127.0.0.1");
  12225. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12226. svr_.wait_until_ready();
  12227. }
  12228. void TearDown() override {
  12229. svr_.stop();
  12230. if (thread_.joinable()) thread_.join();
  12231. }
  12232. Server svr_;
  12233. std::thread thread_;
  12234. int port_ = 0;
  12235. };
  12236. TEST_F(OpenStreamTest, Basic) {
  12237. Client cli("127.0.0.1", port_);
  12238. auto handle = cli.open_stream("GET", "/hello");
  12239. EXPECT_TRUE(handle.is_valid());
  12240. EXPECT_EQ("Hello World!", read_all(handle));
  12241. }
  12242. TEST_F(OpenStreamTest, SmallBuffer) {
  12243. Client cli("127.0.0.1", port_);
  12244. auto handle = cli.open_stream("GET", "/hello");
  12245. std::string result;
  12246. char buf[4];
  12247. ssize_t n;
  12248. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12249. result.append(buf, static_cast<size_t>(n));
  12250. EXPECT_EQ("Hello World!", result);
  12251. }
  12252. TEST_F(OpenStreamTest, DefaultHeaders) {
  12253. Client cli("127.0.0.1", port_);
  12254. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12255. {
  12256. auto handle = cli.open_stream("GET", "/echo-headers");
  12257. ASSERT_TRUE(handle.is_valid());
  12258. auto body = read_all(handle);
  12259. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12260. std::string::npos);
  12261. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12262. std::string::npos);
  12263. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12264. }
  12265. // open_stream POST with body and no explicit content_type should NOT add
  12266. // text/plain Content-Type (behavior differs from non-streaming path), but
  12267. // should include Content-Length
  12268. {
  12269. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12270. ASSERT_TRUE(handle.is_valid());
  12271. auto body = read_all(handle);
  12272. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12273. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12274. }
  12275. // open_stream POST with explicit Content-Type should preserve it
  12276. {
  12277. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12278. {{"Content-Type", "application/custom"}},
  12279. "{}", "application/custom");
  12280. ASSERT_TRUE(handle.is_valid());
  12281. auto body = read_all(handle);
  12282. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12283. }
  12284. // User-specified User-Agent must not be overwritten for stream API
  12285. {
  12286. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12287. {{"User-Agent", "MyAgent/1.2"}});
  12288. ASSERT_TRUE(handle.is_valid());
  12289. auto body = read_all(handle);
  12290. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12291. }
  12292. }
  12293. TEST_F(OpenStreamTest, Large) {
  12294. Client cli("127.0.0.1", port_);
  12295. auto handle = cli.open_stream("GET", "/large");
  12296. EXPECT_EQ(10000u, read_all(handle).size());
  12297. }
  12298. TEST_F(OpenStreamTest, ConnectionError) {
  12299. Client cli("127.0.0.1", 9999);
  12300. auto handle = cli.open_stream("GET", "/hello");
  12301. EXPECT_FALSE(handle.is_valid());
  12302. }
  12303. TEST_F(OpenStreamTest, Chunked) {
  12304. Client cli("127.0.0.1", port_);
  12305. auto handle = cli.open_stream("GET", "/chunked");
  12306. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12307. "Transfer-Encoding") == "chunked");
  12308. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12309. }
  12310. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12311. Client cli("127.0.0.1", port_);
  12312. auto handle =
  12313. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12314. ASSERT_TRUE(handle.is_valid());
  12315. // Consume body to allow trailers to be received/parsed
  12316. auto body = read_all(handle);
  12317. // Explicitly parse trailers (ensure trailers are available for assertion)
  12318. handle.parse_trailers_if_needed();
  12319. EXPECT_EQ(std::string("123456789"), body);
  12320. // The response should include a Trailer header declaring both names
  12321. ASSERT_TRUE(handle.response);
  12322. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12323. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12324. handle.response->get_header_value("Trailer"));
  12325. // Prohibited trailer must not be present
  12326. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12327. // Allowed trailer should be present
  12328. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12329. EXPECT_EQ(std::string("yes"),
  12330. handle.response->get_trailer_value("X-Allowed"));
  12331. // Verify trailers are NOT present as regular headers
  12332. EXPECT_EQ(std::string(""),
  12333. handle.response->get_header_value("Content-Length"));
  12334. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12335. }
  12336. static std::thread serve_single_response(std::promise<int> &port_promise,
  12337. const std::string &response) {
  12338. return std::thread([&port_promise, response] {
  12339. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12340. default_socket_options(srv);
  12341. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12342. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12343. sockaddr_in addr{};
  12344. addr.sin_family = AF_INET;
  12345. addr.sin_port = htons(0); // Let OS assign a free port
  12346. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12347. int opt = 1;
  12348. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12349. #ifdef _WIN32
  12350. reinterpret_cast<const char *>(&opt),
  12351. #else
  12352. &opt,
  12353. #endif
  12354. sizeof(opt));
  12355. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12356. ::listen(srv, 1) != 0) {
  12357. port_promise.set_value(-1);
  12358. detail::close_socket(srv);
  12359. return;
  12360. }
  12361. socklen_t addr_len = sizeof(addr);
  12362. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12363. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12364. sockaddr_in cli_addr{};
  12365. socklen_t cli_len = sizeof(cli_addr);
  12366. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12367. if (cli != INVALID_SOCKET) {
  12368. // Read the complete HTTP request (until the blank line that terminates
  12369. // headers) before sending the response. If the server closes the socket
  12370. // while the client's request data is still unread in the kernel receive
  12371. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12372. // connection on both sides: it discards the client's receive buffer
  12373. // (which already holds our response) and causes any in-progress write on
  12374. // the client to fail with ECONNRESET. Reading all request data first
  12375. // ensures close() emits a graceful FIN.
  12376. {
  12377. char rbuf[256];
  12378. std::string req;
  12379. while (req.find("\r\n\r\n") == std::string::npos) {
  12380. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12381. if (n <= 0) { break; }
  12382. req.append(rbuf, static_cast<size_t>(n));
  12383. }
  12384. }
  12385. ::send(cli,
  12386. #ifdef _WIN32
  12387. static_cast<const char *>(response.c_str()),
  12388. static_cast<int>(response.size()),
  12389. #else
  12390. response.c_str(), response.size(),
  12391. #endif
  12392. 0);
  12393. detail::close_socket(cli);
  12394. }
  12395. detail::close_socket(srv);
  12396. });
  12397. }
  12398. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12399. #ifndef _WIN32
  12400. signal(SIGPIPE, SIG_IGN);
  12401. #endif
  12402. std::promise<int> port_promise;
  12403. auto port_future = port_promise.get_future();
  12404. auto server_thread =
  12405. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12406. "Content-Type: text/plain\r\n"
  12407. "Content-Length: not-a-number\r\n"
  12408. "Connection: close\r\n"
  12409. "\r\n"
  12410. "hello");
  12411. auto port = port_future.get();
  12412. ASSERT_GT(port, 0);
  12413. Client cli("127.0.0.1", port);
  12414. auto handle = cli.open_stream("GET", "/");
  12415. EXPECT_FALSE(handle.is_valid());
  12416. server_thread.join();
  12417. }
  12418. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12419. #ifndef _WIN32
  12420. signal(SIGPIPE, SIG_IGN);
  12421. #endif
  12422. std::promise<int> port_promise;
  12423. auto port_future = port_promise.get_future();
  12424. auto server_thread = serve_single_response(
  12425. port_promise, "HTTP/1.1 200 OK\r\n"
  12426. "Content-Type: text/plain\r\n"
  12427. "Content-Length: 99999999999999999999999999\r\n"
  12428. "Connection: close\r\n"
  12429. "\r\n"
  12430. "hello");
  12431. auto port = port_future.get();
  12432. ASSERT_GT(port, 0);
  12433. // Before the fix, std::stoull would throw std::out_of_range here and
  12434. // crash the process. After the fix, strtoull silently clamps to
  12435. // ULLONG_MAX so the stream opens without crashing. The important thing
  12436. // is that the process does NOT terminate.
  12437. Client cli("127.0.0.1", port);
  12438. auto handle = cli.open_stream("GET", "/");
  12439. EXPECT_TRUE(handle.is_valid());
  12440. server_thread.join();
  12441. }
  12442. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12443. TEST_F(OpenStreamTest, Gzip) {
  12444. Client cli("127.0.0.1", port_);
  12445. auto handle = cli.open_stream("GET", "/compressible", {},
  12446. {{"Accept-Encoding", "gzip"}});
  12447. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12448. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12449. }
  12450. #endif
  12451. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12452. TEST_F(OpenStreamTest, Brotli) {
  12453. Client cli("127.0.0.1", port_);
  12454. auto handle =
  12455. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12456. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12457. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12458. }
  12459. #endif
  12460. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12461. TEST_F(OpenStreamTest, Zstd) {
  12462. Client cli("127.0.0.1", port_);
  12463. auto handle = cli.open_stream("GET", "/compressible", {},
  12464. {{"Accept-Encoding", "zstd"}});
  12465. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12466. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12467. }
  12468. #endif
  12469. #ifdef CPPHTTPLIB_SSL_ENABLED
  12470. class SSLOpenStreamTest : public ::testing::Test {
  12471. protected:
  12472. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12473. void SetUp() override {
  12474. svr_.Get("/hello", [](const Request &, Response &res) {
  12475. res.set_content("Hello SSL World!", "text/plain");
  12476. });
  12477. svr_.Get("/chunked", [](const Request &, Response &res) {
  12478. res.set_chunked_content_provider("text/plain",
  12479. [](size_t offset, DataSink &sink) {
  12480. if (offset < 15) {
  12481. sink.write("chunk", 5);
  12482. return true;
  12483. }
  12484. sink.done();
  12485. return true;
  12486. });
  12487. });
  12488. svr_.Post("/echo", [](const Request &req, Response &res) {
  12489. res.set_content(req.body, req.get_header_value("Content-Type"));
  12490. });
  12491. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12492. std::string body = req.body;
  12493. res.set_chunked_content_provider(
  12494. "text/plain", [body](size_t offset, DataSink &sink) {
  12495. if (offset < body.size()) {
  12496. sink.write(body.data() + offset, body.size() - offset);
  12497. }
  12498. sink.done();
  12499. return true;
  12500. });
  12501. });
  12502. port_ = svr_.bind_to_any_port("127.0.0.1");
  12503. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12504. svr_.wait_until_ready();
  12505. }
  12506. void TearDown() override {
  12507. svr_.stop();
  12508. if (thread_.joinable()) thread_.join();
  12509. }
  12510. SSLServer svr_;
  12511. std::thread thread_;
  12512. int port_ = 0;
  12513. };
  12514. TEST_F(SSLOpenStreamTest, Basic) {
  12515. SSLClient cli("127.0.0.1", port_);
  12516. cli.enable_server_certificate_verification(false);
  12517. auto handle = cli.open_stream("GET", "/hello");
  12518. ASSERT_TRUE(handle.is_valid());
  12519. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12520. }
  12521. TEST_F(SSLOpenStreamTest, Chunked) {
  12522. SSLClient cli("127.0.0.1", port_);
  12523. cli.enable_server_certificate_verification(false);
  12524. auto handle = cli.open_stream("GET", "/chunked");
  12525. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12526. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12527. "Transfer-Encoding") == "chunked");
  12528. auto body = read_all(handle);
  12529. EXPECT_EQ("chunkchunkchunk", body);
  12530. }
  12531. TEST_F(SSLOpenStreamTest, Post) {
  12532. SSLClient cli("127.0.0.1", port_);
  12533. cli.enable_server_certificate_verification(false);
  12534. auto handle =
  12535. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12536. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12537. EXPECT_EQ(200, handle.response->status);
  12538. auto body = read_all(handle);
  12539. EXPECT_EQ("Hello SSL POST", body);
  12540. }
  12541. TEST_F(SSLOpenStreamTest, PostChunked) {
  12542. SSLClient cli("127.0.0.1", port_);
  12543. cli.enable_server_certificate_verification(false);
  12544. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12545. "Chunked SSL Data", "text/plain");
  12546. ASSERT_TRUE(handle.is_valid());
  12547. EXPECT_EQ(200, handle.response->status);
  12548. auto body = read_all(handle);
  12549. EXPECT_EQ("Chunked SSL Data", body);
  12550. }
  12551. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12552. // Content-Length is terminated by the server closing the connection. When the
  12553. // SSL peer sends a close_notify after the body, the client must treat it as a
  12554. // clean EOF and return a successful response rather than an error.
  12555. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12557. ASSERT_TRUE(svr.is_valid());
  12558. svr.set_keep_alive_max_count(1);
  12559. const std::string expected_body = "Hello from connection-close response!";
  12560. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12561. res.set_content_provider("text/plain",
  12562. [&](size_t offset, DataSink &sink) -> bool {
  12563. if (offset < expected_body.size()) {
  12564. sink.write(expected_body.data() + offset,
  12565. expected_body.size() - offset);
  12566. }
  12567. sink.done();
  12568. return true;
  12569. });
  12570. });
  12571. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12572. auto se = detail::scope_exit([&] {
  12573. svr.stop();
  12574. listen_thread.join();
  12575. ASSERT_FALSE(svr.is_running());
  12576. });
  12577. svr.wait_until_ready();
  12578. SSLClient cli(HOST, PORT);
  12579. cli.enable_server_certificate_verification(false);
  12580. auto res = cli.Get("/no-content-length");
  12581. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12582. EXPECT_EQ(StatusCode::OK_200, res->status);
  12583. EXPECT_EQ(expected_body, res->body);
  12584. }
  12585. #endif // CPPHTTPLIB_SSL_ENABLED
  12586. //==============================================================================
  12587. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12588. // results for various scenarios.
  12589. //==============================================================================
  12590. TEST(ParityTest, GetVsOpenStream) {
  12591. Server svr;
  12592. const std::string path = "/parity";
  12593. const std::string content = "Parity test content: hello world";
  12594. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12595. res.set_content(content, "text/plain");
  12596. });
  12597. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12598. auto se = detail::scope_exit([&] {
  12599. svr.stop();
  12600. t.join();
  12601. ASSERT_FALSE(svr.is_running());
  12602. });
  12603. svr.wait_until_ready();
  12604. Client cli(HOST, PORT);
  12605. // Non-stream path
  12606. auto r1 = cli.Get(path);
  12607. ASSERT_TRUE(r1);
  12608. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12609. // Stream path
  12610. auto h = cli.open_stream("GET", path);
  12611. ASSERT_TRUE(h.is_valid());
  12612. EXPECT_EQ(r1->body, read_all(h));
  12613. }
  12614. // Helper to compress data with provided compressor type T
  12615. template <typename Compressor>
  12616. static std::string compress_payload_for_parity(const std::string &in) {
  12617. std::string out;
  12618. Compressor compressor;
  12619. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12620. [&](const char *data, size_t n) {
  12621. out.append(data, n);
  12622. return true;
  12623. });
  12624. EXPECT_TRUE(ok);
  12625. return out;
  12626. }
  12627. // Helper function for compression parity tests
  12628. template <typename Compressor>
  12629. static void test_compression_parity(const std::string &original,
  12630. const std::string &path,
  12631. const std::string &encoding) {
  12632. const std::string compressed =
  12633. compress_payload_for_parity<Compressor>(original);
  12634. Server svr;
  12635. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12636. res.set_content(compressed, "application/octet-stream");
  12637. res.set_header("Content-Encoding", encoding);
  12638. });
  12639. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12640. auto se = detail::scope_exit([&] {
  12641. svr.stop();
  12642. t.join();
  12643. ASSERT_FALSE(svr.is_running());
  12644. });
  12645. svr.wait_until_ready();
  12646. Client cli(HOST, PORT);
  12647. // Non-streaming
  12648. {
  12649. auto res = cli.Get(path);
  12650. ASSERT_TRUE(res);
  12651. EXPECT_EQ(StatusCode::OK_200, res->status);
  12652. EXPECT_EQ(original, res->body);
  12653. }
  12654. // Streaming
  12655. {
  12656. auto h = cli.open_stream("GET", path);
  12657. ASSERT_TRUE(h.is_valid());
  12658. EXPECT_EQ(original, read_all(h));
  12659. }
  12660. }
  12661. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12662. TEST(ParityTest, Gzip) {
  12663. test_compression_parity<detail::gzip_compressor>(
  12664. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12665. }
  12666. #endif
  12667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12668. TEST(ParityTest, Brotli) {
  12669. test_compression_parity<detail::brotli_compressor>(
  12670. "Hello, brotli parity test payload", "/parity-br", "br");
  12671. }
  12672. #endif
  12673. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12674. TEST(ParityTest, Zstd) {
  12675. test_compression_parity<detail::zstd_compressor>(
  12676. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12677. }
  12678. #endif
  12679. //==============================================================================
  12680. // New Stream API Tests
  12681. //==============================================================================
  12682. inline std::string read_body(httplib::stream::Result &result) {
  12683. std::string body;
  12684. while (result.next()) {
  12685. body.append(result.data(), result.size());
  12686. }
  12687. return body;
  12688. }
  12689. TEST(ClientConnectionTest, Basic) {
  12690. httplib::ClientConnection conn;
  12691. EXPECT_FALSE(conn.is_open());
  12692. conn.sock = 1;
  12693. EXPECT_TRUE(conn.is_open());
  12694. httplib::ClientConnection conn2(std::move(conn));
  12695. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12696. conn2.sock = INVALID_SOCKET;
  12697. }
  12698. // Unified test server for all stream::* tests
  12699. class StreamApiTest : public ::testing::Test {
  12700. protected:
  12701. void SetUp() override {
  12702. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12703. res.set_content("Hello World!", "text/plain");
  12704. });
  12705. svr_.Get("/echo-params",
  12706. [](const httplib::Request &req, httplib::Response &res) {
  12707. std::string r;
  12708. for (const auto &p : req.params) {
  12709. if (!r.empty()) r += "&";
  12710. r += p.first + "=" + p.second;
  12711. }
  12712. res.set_content(r, "text/plain");
  12713. });
  12714. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12715. res.set_content(req.body, req.get_header_value("Content-Type"));
  12716. });
  12717. svr_.Post("/echo-headers",
  12718. [](const httplib::Request &req, httplib::Response &res) {
  12719. std::string r;
  12720. for (const auto &h : req.headers)
  12721. r += h.first + ": " + h.second + "\n";
  12722. res.set_content(r, "text/plain");
  12723. });
  12724. svr_.Post("/echo-params",
  12725. [](const httplib::Request &req, httplib::Response &res) {
  12726. std::string r = "params:";
  12727. for (const auto &p : req.params)
  12728. r += p.first + "=" + p.second + ";";
  12729. res.set_content(r + " body:" + req.body, "text/plain");
  12730. });
  12731. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12732. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12733. });
  12734. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12735. res.set_content("PUT:" + req.body, "text/plain");
  12736. });
  12737. svr_.Patch("/echo",
  12738. [](const httplib::Request &req, httplib::Response &res) {
  12739. res.set_content("PATCH:" + req.body, "text/plain");
  12740. });
  12741. svr_.Delete(
  12742. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12743. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12744. "text/plain");
  12745. });
  12746. svr_.Get("/head-test",
  12747. [](const httplib::Request &, httplib::Response &res) {
  12748. res.set_content("body for HEAD", "text/plain");
  12749. });
  12750. svr_.Options("/options",
  12751. [](const httplib::Request &, httplib::Response &res) {
  12752. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12753. });
  12754. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12755. svr_.wait_until_ready();
  12756. }
  12757. void TearDown() override {
  12758. svr_.stop();
  12759. if (thread_.joinable()) thread_.join();
  12760. }
  12761. httplib::Server svr_;
  12762. std::thread thread_;
  12763. };
  12764. // stream::Get tests
  12765. TEST_F(StreamApiTest, GetBasic) {
  12766. httplib::Client cli(HOST, PORT);
  12767. auto result = httplib::stream::Get(cli, "/hello");
  12768. ASSERT_TRUE(result.is_valid());
  12769. EXPECT_EQ(200, result.status());
  12770. EXPECT_EQ("Hello World!", read_body(result));
  12771. }
  12772. TEST_F(StreamApiTest, GetWithParams) {
  12773. httplib::Client cli(HOST, PORT);
  12774. httplib::Params params{{"foo", "bar"}};
  12775. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12776. ASSERT_TRUE(result.is_valid());
  12777. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12778. }
  12779. TEST_F(StreamApiTest, GetConnectionError) {
  12780. httplib::Client cli(HOST, 9999);
  12781. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12782. }
  12783. TEST_F(StreamApiTest, Get404) {
  12784. httplib::Client cli(HOST, PORT);
  12785. auto result = httplib::stream::Get(cli, "/nonexistent");
  12786. EXPECT_TRUE(result.is_valid());
  12787. EXPECT_EQ(404, result.status());
  12788. }
  12789. // stream::Post tests
  12790. TEST_F(StreamApiTest, PostBasic) {
  12791. httplib::Client cli(HOST, PORT);
  12792. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12793. "application/json");
  12794. ASSERT_TRUE(result.is_valid());
  12795. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12796. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12797. }
  12798. TEST_F(StreamApiTest, PostWithHeaders) {
  12799. httplib::Client cli(HOST, PORT);
  12800. httplib::Headers headers{{"X-Custom", "value"}};
  12801. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12802. "text/plain");
  12803. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12804. }
  12805. TEST_F(StreamApiTest, PostWithParams) {
  12806. httplib::Client cli(HOST, PORT);
  12807. httplib::Params params{{"k", "v"}};
  12808. auto result =
  12809. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12810. auto body = read_body(result);
  12811. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12812. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12813. }
  12814. TEST_F(StreamApiTest, PostLarge) {
  12815. httplib::Client cli(HOST, PORT);
  12816. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12817. size_t total = 0;
  12818. while (result.next()) {
  12819. total += result.size();
  12820. }
  12821. EXPECT_EQ(100u * 1024u, total);
  12822. }
  12823. // stream::Put/Patch tests
  12824. TEST_F(StreamApiTest, PutAndPatch) {
  12825. httplib::Client cli(HOST, PORT);
  12826. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12827. EXPECT_EQ("PUT:test", read_body(put));
  12828. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12829. EXPECT_EQ("PATCH:test", read_body(patch));
  12830. }
  12831. // stream::Delete tests
  12832. TEST_F(StreamApiTest, Delete) {
  12833. httplib::Client cli(HOST, PORT);
  12834. auto del1 = httplib::stream::Delete(cli, "/resource");
  12835. EXPECT_EQ("Deleted", read_body(del1));
  12836. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12837. EXPECT_EQ("Deleted:data", read_body(del2));
  12838. }
  12839. // stream::Head/Options tests
  12840. TEST_F(StreamApiTest, HeadAndOptions) {
  12841. httplib::Client cli(HOST, PORT);
  12842. auto head = httplib::stream::Head(cli, "/head-test");
  12843. EXPECT_TRUE(head.is_valid());
  12844. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12845. auto opts = httplib::stream::Options(cli, "/options");
  12846. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12847. }
  12848. // SSL stream::* tests
  12849. #ifdef CPPHTTPLIB_SSL_ENABLED
  12850. class SSLStreamApiTest : public ::testing::Test {
  12851. protected:
  12852. void SetUp() override {
  12853. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12854. res.set_content("Hello SSL!", "text/plain");
  12855. });
  12856. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12857. res.set_content(req.body, "text/plain");
  12858. });
  12859. port_ = svr_.bind_to_any_port("127.0.0.1");
  12860. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12861. svr_.wait_until_ready();
  12862. }
  12863. void TearDown() override {
  12864. svr_.stop();
  12865. if (thread_.joinable()) thread_.join();
  12866. }
  12867. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12868. std::thread thread_;
  12869. int port_ = 0;
  12870. };
  12871. TEST_F(SSLStreamApiTest, GetAndPost) {
  12872. httplib::SSLClient cli("127.0.0.1", port_);
  12873. cli.enable_server_certificate_verification(false);
  12874. auto get = httplib::stream::Get(cli, "/hello");
  12875. EXPECT_EQ("Hello SSL!", read_body(get));
  12876. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12877. EXPECT_EQ("test", read_body(post));
  12878. }
  12879. #endif
  12880. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12881. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12882. // BodyReader
  12883. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12884. // Test that read timeout during streaming is detected
  12885. // Use a large content-length response where server delays mid-stream
  12886. Server svr;
  12887. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12888. // Send a large response with delay in the middle
  12889. res.set_content_provider(
  12890. 1000, // content_length
  12891. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12892. if (offset < 100) {
  12893. // Send first 100 bytes immediately
  12894. std::string data(100, 'A');
  12895. sink.write(data.c_str(), data.size());
  12896. return true;
  12897. }
  12898. // Then delay longer than client timeout
  12899. std::this_thread::sleep_for(std::chrono::seconds(3));
  12900. std::string data(900, 'B');
  12901. sink.write(data.c_str(), data.size());
  12902. return true;
  12903. });
  12904. });
  12905. auto port = 8091;
  12906. std::thread t([&]() { svr.listen("localhost", port); });
  12907. svr.wait_until_ready();
  12908. Client cli("localhost", port);
  12909. cli.set_read_timeout(1, 0); // 1 second timeout
  12910. auto handle = cli.open_stream("GET", "/slow-stream");
  12911. ASSERT_TRUE(handle.is_valid());
  12912. char buf[256];
  12913. ssize_t total = 0;
  12914. ssize_t n;
  12915. bool got_error = false;
  12916. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12917. total += n;
  12918. }
  12919. if (n < 0) {
  12920. got_error = true;
  12921. // Should be timeout or read error
  12922. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12923. handle.get_read_error() == Error::Read)
  12924. << "Actual error: " << to_string(handle.get_read_error());
  12925. }
  12926. // Either we got an error, or we got less data than expected
  12927. EXPECT_TRUE(got_error || total < 1000)
  12928. << "Expected timeout but got all " << total << " bytes";
  12929. svr.stop();
  12930. t.join();
  12931. }
  12932. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12933. // Test connection closed detection via BodyReader
  12934. Server svr;
  12935. std::atomic<bool> close_now{false};
  12936. svr.Get("/will-close", [&](const Request &, Response &res) {
  12937. res.set_content_provider(
  12938. 10000, // Large content_length that we won't fully send
  12939. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12940. if (offset < 100) {
  12941. std::string data(100, 'X');
  12942. sink.write(data.c_str(), data.size());
  12943. return true;
  12944. }
  12945. // Wait for signal then abort
  12946. while (!close_now) {
  12947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12948. }
  12949. return false; // Abort - server will close connection
  12950. });
  12951. });
  12952. auto port = 8092;
  12953. std::thread t([&]() { svr.listen("localhost", port); });
  12954. svr.wait_until_ready();
  12955. Client cli("localhost", port);
  12956. auto handle = cli.open_stream("GET", "/will-close");
  12957. ASSERT_TRUE(handle.is_valid());
  12958. char buf[256];
  12959. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12960. EXPECT_GT(n, 0) << "First read should succeed";
  12961. // Signal server to close
  12962. close_now = true;
  12963. // Keep reading until error or EOF
  12964. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12965. // Keep reading
  12966. }
  12967. // Should get an error since content_length wasn't satisfied
  12968. if (n < 0) {
  12969. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12970. handle.get_read_error() == Error::Read)
  12971. << "Actual error: " << to_string(handle.get_read_error());
  12972. }
  12973. svr.stop();
  12974. t.join();
  12975. }
  12976. #ifdef CPPHTTPLIB_SSL_ENABLED
  12977. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12978. // Test that read timeout during SSL streaming is detected
  12979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12980. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12981. res.set_content_provider(
  12982. 1000, "text/plain",
  12983. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12984. if (offset < 100) {
  12985. std::string data(100, 'A');
  12986. sink.write(data.c_str(), data.size());
  12987. return true;
  12988. }
  12989. std::this_thread::sleep_for(std::chrono::seconds(3));
  12990. std::string data(900, 'B');
  12991. sink.write(data.c_str(), data.size());
  12992. return true;
  12993. });
  12994. });
  12995. auto port = 8093;
  12996. std::thread t([&]() { svr.listen("localhost", port); });
  12997. svr.wait_until_ready();
  12998. SSLClient cli("localhost", port);
  12999. cli.enable_server_certificate_verification(false);
  13000. cli.set_read_timeout(1, 0); // 1 second timeout
  13001. auto handle = cli.open_stream("GET", "/slow-stream");
  13002. ASSERT_TRUE(handle.is_valid());
  13003. char buf[256];
  13004. ssize_t total = 0;
  13005. ssize_t n;
  13006. bool got_error = false;
  13007. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13008. total += n;
  13009. }
  13010. if (n < 0) {
  13011. got_error = true;
  13012. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13013. handle.get_read_error() == Error::Read)
  13014. << "Actual error: " << to_string(handle.get_read_error());
  13015. }
  13016. EXPECT_TRUE(got_error || total < 1000)
  13017. << "Expected timeout but got all " << total << " bytes";
  13018. svr.stop();
  13019. t.join();
  13020. }
  13021. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13022. // Test SSL connection closed detection
  13023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13024. std::atomic<bool> close_now{false};
  13025. svr.Get("/will-close", [&](const Request &, Response &res) {
  13026. res.set_content_provider(
  13027. 10000, "text/plain",
  13028. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13029. if (offset < 100) {
  13030. std::string data(100, 'X');
  13031. sink.write(data.c_str(), data.size());
  13032. return true;
  13033. }
  13034. while (!close_now) {
  13035. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13036. }
  13037. return false;
  13038. });
  13039. });
  13040. auto port = 8094;
  13041. std::thread t([&]() { svr.listen("localhost", port); });
  13042. svr.wait_until_ready();
  13043. SSLClient cli("localhost", port);
  13044. cli.enable_server_certificate_verification(false);
  13045. auto handle = cli.open_stream("GET", "/will-close");
  13046. ASSERT_TRUE(handle.is_valid());
  13047. char buf[256];
  13048. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13049. EXPECT_GT(n, 0);
  13050. // Signal server to close
  13051. close_now = true;
  13052. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13053. // Keep reading
  13054. }
  13055. if (n < 0) {
  13056. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13057. handle.get_read_error() == Error::Read)
  13058. << "Actual error: " << to_string(handle.get_read_error());
  13059. }
  13060. svr.stop();
  13061. t.join();
  13062. }
  13063. #endif
  13064. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13065. using namespace httplib;
  13066. // Create a test file
  13067. const char *fname = "etag_testfile.txt";
  13068. const char *content = "etag-content";
  13069. {
  13070. std::ofstream ofs(fname);
  13071. ofs << content;
  13072. ASSERT_TRUE(ofs.good());
  13073. }
  13074. Server svr;
  13075. svr.set_mount_point("/static", ".");
  13076. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13077. svr.wait_until_ready();
  13078. Client cli(HOST, PORT);
  13079. // First request: should get 200 with ETag header
  13080. auto res1 = cli.Get("/static/etag_testfile.txt");
  13081. ASSERT_TRUE(res1);
  13082. ASSERT_EQ(200, res1->status);
  13083. ASSERT_TRUE(res1->has_header("ETag"));
  13084. std::string etag = res1->get_header_value("ETag");
  13085. EXPECT_FALSE(etag.empty());
  13086. // Verify ETag format: W/"hex-hex"
  13087. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13088. EXPECT_EQ('W', etag[0]);
  13089. EXPECT_EQ('/', etag[1]);
  13090. EXPECT_EQ('"', etag[2]);
  13091. EXPECT_EQ('"', etag.back());
  13092. // Exact match: expect 304 Not Modified
  13093. Headers h2 = {{"If-None-Match", etag}};
  13094. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13095. ASSERT_TRUE(res2);
  13096. EXPECT_EQ(304, res2->status);
  13097. // Wildcard match: expect 304 Not Modified
  13098. Headers h3 = {{"If-None-Match", "*"}};
  13099. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13100. ASSERT_TRUE(res3);
  13101. EXPECT_EQ(304, res3->status);
  13102. // Non-matching ETag: expect 200
  13103. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13104. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13105. ASSERT_TRUE(res4);
  13106. EXPECT_EQ(200, res4->status);
  13107. // Multiple ETags with one matching: expect 304
  13108. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13109. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13110. ASSERT_TRUE(res5);
  13111. EXPECT_EQ(304, res5->status);
  13112. svr.stop();
  13113. t.join();
  13114. std::remove(fname);
  13115. }
  13116. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13117. using namespace httplib;
  13118. Server svr;
  13119. svr.set_mount_point("/static", ".");
  13120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13121. svr.wait_until_ready();
  13122. Client cli(HOST, PORT);
  13123. // Send If-None-Match: * to a non-existent file
  13124. Headers h = {{"If-None-Match", "*"}};
  13125. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13126. ASSERT_TRUE(res);
  13127. EXPECT_EQ(404, res->status);
  13128. svr.stop();
  13129. t.join();
  13130. }
  13131. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13132. using namespace httplib;
  13133. // Create a test file
  13134. const char *fname = "etag_boundary_testfile.txt";
  13135. const char *content = "boundary-test";
  13136. {
  13137. std::ofstream ofs(fname);
  13138. ofs << content;
  13139. ASSERT_TRUE(ofs.good());
  13140. }
  13141. Server svr;
  13142. svr.set_mount_point("/static", ".");
  13143. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13144. svr.wait_until_ready();
  13145. Client cli(HOST, PORT);
  13146. // Get the actual ETag
  13147. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13148. ASSERT_TRUE(res1);
  13149. ASSERT_EQ(200, res1->status);
  13150. ASSERT_TRUE(res1->has_header("ETag"));
  13151. std::string etag = res1->get_header_value("ETag");
  13152. // Test 1: Very long ETag value (longer than actual ETag)
  13153. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13154. Headers h1 = {{"If-None-Match", "W/"
  13155. "\"very-long-etag-value-that-is-much-longer-"
  13156. "than-the-actual-etag-value\""}};
  13157. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13158. ASSERT_TRUE(res2);
  13159. EXPECT_EQ(200, res2->status); // Should not match
  13160. // Test 2: Long string followed by wildcard
  13161. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13162. // string)
  13163. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13164. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13165. ASSERT_TRUE(res3);
  13166. EXPECT_EQ(304, res3->status); // Should match on "*"
  13167. // Test 3: Wildcard followed by long string
  13168. // Should match on "*" immediately and return 304
  13169. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13170. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13171. ASSERT_TRUE(res4);
  13172. EXPECT_EQ(304, res4->status); // Should match on "*"
  13173. // Test 4: Multiple long non-matching values
  13174. // Should NOT match and return 200 (test that all comparisons are safe)
  13175. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13176. "W/\"second-long-non-matching-value\", "
  13177. "W/\"third-long-non-matching-value\""}};
  13178. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13179. ASSERT_TRUE(res5);
  13180. EXPECT_EQ(200, res5->status); // Should not match
  13181. // Test 5: Single character that is not "*" (edge case)
  13182. Headers h5 = {{"If-None-Match", "X"}};
  13183. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13184. ASSERT_TRUE(res6);
  13185. EXPECT_EQ(200, res6->status); // Should not match
  13186. svr.stop();
  13187. t.join();
  13188. std::remove(fname);
  13189. }
  13190. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13191. using namespace httplib;
  13192. // Create a test file
  13193. const char *fname = "ims_testfile.txt";
  13194. const char *content = "if-modified-since-test";
  13195. {
  13196. std::ofstream ofs(fname);
  13197. ofs << content;
  13198. ASSERT_TRUE(ofs.good());
  13199. }
  13200. Server svr;
  13201. svr.set_mount_point("/static", ".");
  13202. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13203. svr.wait_until_ready();
  13204. Client cli(HOST, PORT);
  13205. // First request: should get 200 with Last-Modified header
  13206. auto res1 = cli.Get("/static/ims_testfile.txt");
  13207. ASSERT_TRUE(res1);
  13208. ASSERT_EQ(200, res1->status);
  13209. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13210. std::string last_modified = res1->get_header_value("Last-Modified");
  13211. EXPECT_FALSE(last_modified.empty());
  13212. // If-Modified-Since with same time: expect 304
  13213. Headers h2 = {{"If-Modified-Since", last_modified}};
  13214. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13215. ASSERT_TRUE(res2);
  13216. EXPECT_EQ(304, res2->status);
  13217. // If-Modified-Since with future time: expect 304
  13218. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13219. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13220. ASSERT_TRUE(res3);
  13221. EXPECT_EQ(304, res3->status);
  13222. // If-Modified-Since with past time: expect 200
  13223. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13224. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13225. ASSERT_TRUE(res4);
  13226. EXPECT_EQ(200, res4->status);
  13227. // If-None-Match takes precedence over If-Modified-Since
  13228. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13229. ASSERT_TRUE(res1->has_header("ETag"));
  13230. std::string etag = res1->get_header_value("ETag");
  13231. Headers h5 = {{"If-None-Match", etag},
  13232. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13233. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13234. ASSERT_TRUE(res5);
  13235. EXPECT_EQ(304, res5->status);
  13236. svr.stop();
  13237. t.join();
  13238. std::remove(fname);
  13239. }
  13240. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13241. using namespace httplib;
  13242. Server svr;
  13243. // Endpoint that returns compressible content
  13244. svr.Get("/compressible", [](const Request &, Response &res) {
  13245. // Return a large enough body to trigger compression
  13246. std::string body(1000, 'a');
  13247. res.set_content(body, "text/plain");
  13248. });
  13249. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13250. svr.wait_until_ready();
  13251. Client cli(HOST, PORT);
  13252. // Request with gzip support: should get Vary header when compressed
  13253. cli.set_compress(true);
  13254. auto res1 = cli.Get("/compressible");
  13255. ASSERT_TRUE(res1);
  13256. EXPECT_EQ(200, res1->status);
  13257. // If Content-Encoding is set, Vary should also be set
  13258. if (res1->has_header("Content-Encoding")) {
  13259. EXPECT_TRUE(res1->has_header("Vary"));
  13260. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13261. }
  13262. // Request without Accept-Encoding header: should not have compression
  13263. Headers h_no_compress;
  13264. auto res2 = cli.Get("/compressible", h_no_compress);
  13265. ASSERT_TRUE(res2);
  13266. EXPECT_EQ(200, res2->status);
  13267. // Verify Vary header is present when compression is applied
  13268. // (the exact behavior depends on server configuration)
  13269. svr.stop();
  13270. t.join();
  13271. }
  13272. TEST(ETagTest, IfRangeWithETag) {
  13273. using namespace httplib;
  13274. // Create a test file with known content
  13275. const char *fname = "if_range_testfile.txt";
  13276. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13277. {
  13278. std::ofstream ofs(fname);
  13279. ofs << content;
  13280. ASSERT_TRUE(ofs.good());
  13281. }
  13282. Server svr;
  13283. svr.set_mount_point("/static", ".");
  13284. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13285. svr.wait_until_ready();
  13286. Client cli(HOST, PORT);
  13287. // First request: get ETag
  13288. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13289. ASSERT_TRUE(res1);
  13290. ASSERT_EQ(200, res1->status);
  13291. ASSERT_TRUE(res1->has_header("ETag"));
  13292. std::string etag = res1->get_header_value("ETag");
  13293. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13294. // Since our server generates weak ETags (W/"..."), If-Range with our
  13295. // ETag should NOT result in partial content - it should return full content.
  13296. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13297. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13298. ASSERT_TRUE(res2);
  13299. // Weak ETag in If-Range -> full content (200), not partial (206)
  13300. EXPECT_EQ(200, res2->status);
  13301. EXPECT_EQ(content, res2->body);
  13302. EXPECT_FALSE(res2->has_header("Content-Range"));
  13303. // Range request with non-matching If-Range (ETag): should get 200 (full
  13304. // content)
  13305. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13306. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13307. ASSERT_TRUE(res3);
  13308. EXPECT_EQ(200, res3->status);
  13309. EXPECT_EQ(content, res3->body);
  13310. EXPECT_FALSE(res3->has_header("Content-Range"));
  13311. // Range request with strong ETag (hypothetical - our server doesn't generate
  13312. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13313. // should return full content)
  13314. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13315. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13316. ASSERT_TRUE(res4);
  13317. EXPECT_EQ(200, res4->status);
  13318. EXPECT_EQ(content, res4->body);
  13319. EXPECT_FALSE(res4->has_header("Content-Range"));
  13320. svr.stop();
  13321. t.join();
  13322. std::remove(fname);
  13323. }
  13324. TEST(ETagTest, IfRangeWithDate) {
  13325. using namespace httplib;
  13326. // Create a test file
  13327. const char *fname = "if_range_date_testfile.txt";
  13328. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13329. {
  13330. std::ofstream ofs(fname);
  13331. ofs << content;
  13332. ASSERT_TRUE(ofs.good());
  13333. }
  13334. Server svr;
  13335. svr.set_mount_point("/static", ".");
  13336. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13337. svr.wait_until_ready();
  13338. Client cli(HOST, PORT);
  13339. // First request: get Last-Modified
  13340. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13341. ASSERT_TRUE(res1);
  13342. ASSERT_EQ(200, res1->status);
  13343. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13344. std::string last_modified = res1->get_header_value("Last-Modified");
  13345. // Range request with matching If-Range (date): should get 206
  13346. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13347. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13348. ASSERT_TRUE(res2);
  13349. EXPECT_EQ(206, res2->status);
  13350. EXPECT_EQ("FGHIJ", res2->body);
  13351. // Range request with old If-Range date: should get 200 (full content)
  13352. Headers h3 = {{"Range", "bytes=5-9"},
  13353. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13354. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13355. ASSERT_TRUE(res3);
  13356. EXPECT_EQ(200, res3->status);
  13357. EXPECT_EQ(content, res3->body);
  13358. // Range request with future If-Range date: should get 206
  13359. Headers h4 = {{"Range", "bytes=0-4"},
  13360. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13361. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13362. ASSERT_TRUE(res4);
  13363. EXPECT_EQ(206, res4->status);
  13364. EXPECT_EQ("ABCDE", res4->body);
  13365. svr.stop();
  13366. t.join();
  13367. std::remove(fname);
  13368. }
  13369. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13370. using namespace httplib;
  13371. const char *fname = "etag_malformed.txt";
  13372. const char *content = "malformed-etag";
  13373. {
  13374. std::ofstream ofs(fname);
  13375. ofs << content;
  13376. ASSERT_TRUE(ofs.good());
  13377. }
  13378. Server svr;
  13379. svr.set_mount_point("/static", ".");
  13380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13381. svr.wait_until_ready();
  13382. Client cli(HOST, PORT);
  13383. // baseline: should get 200 and an ETag
  13384. auto res1 = cli.Get("/static/etag_malformed.txt");
  13385. ASSERT_TRUE(res1);
  13386. ASSERT_EQ(200, res1->status);
  13387. ASSERT_TRUE(res1->has_header("ETag"));
  13388. // Malformed ETag value (missing quotes) should be treated as non-matching
  13389. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13390. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13391. ASSERT_TRUE(res_bad);
  13392. EXPECT_EQ(200, res_bad->status);
  13393. // Whitespace-only header value should be considered invalid / non-matching
  13394. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13395. "Host: localhost\r\n"
  13396. "If-None-Match: \r\n"
  13397. "Connection: close\r\n"
  13398. "\r\n";
  13399. std::string out;
  13400. ASSERT_TRUE(send_request(5, raw_req, &out));
  13401. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13402. svr.stop();
  13403. t.join();
  13404. std::remove(fname);
  13405. }
  13406. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13407. using namespace httplib;
  13408. const char *fname = "ims_invalid_format.txt";
  13409. const char *content = "ims-bad-format";
  13410. {
  13411. std::ofstream ofs(fname);
  13412. ofs << content;
  13413. ASSERT_TRUE(ofs.good());
  13414. }
  13415. Server svr;
  13416. svr.set_mount_point("/static", ".");
  13417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13418. svr.wait_until_ready();
  13419. Client cli(HOST, PORT);
  13420. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13421. ASSERT_TRUE(res1);
  13422. ASSERT_EQ(200, res1->status);
  13423. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13424. // If-Modified-Since with invalid format should not result in 304
  13425. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13426. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13427. ASSERT_TRUE(res_bad);
  13428. EXPECT_EQ(200, res_bad->status);
  13429. // If-Range with invalid date format should be treated as mismatch -> full
  13430. // content (200)
  13431. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13432. {"If-Range", "invalid-date"}};
  13433. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13434. ASSERT_TRUE(res_ifrange);
  13435. EXPECT_EQ(200, res_ifrange->status);
  13436. svr.stop();
  13437. t.join();
  13438. std::remove(fname);
  13439. }
  13440. TEST(ETagTest, IfRangeWithMalformedETag) {
  13441. using namespace httplib;
  13442. const char *fname = "ifrange_malformed.txt";
  13443. const std::string content = "0123456789";
  13444. {
  13445. std::ofstream ofs(fname);
  13446. ofs << content;
  13447. ASSERT_TRUE(ofs.good());
  13448. }
  13449. Server svr;
  13450. svr.set_mount_point("/static", ".");
  13451. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13452. svr.wait_until_ready();
  13453. Client cli(HOST, PORT);
  13454. // First request: get ETag
  13455. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13456. ASSERT_TRUE(res1);
  13457. ASSERT_EQ(200, res1->status);
  13458. ASSERT_TRUE(res1->has_header("ETag"));
  13459. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13460. // full content (200)
  13461. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13462. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13463. ASSERT_TRUE(res2);
  13464. EXPECT_EQ(200, res2->status);
  13465. EXPECT_EQ(content, res2->body);
  13466. svr.stop();
  13467. t.join();
  13468. std::remove(fname);
  13469. }
  13470. TEST(ETagTest, ExtremeLargeDateValues) {
  13471. using namespace httplib;
  13472. const char *fname = "ims_extreme_date.txt";
  13473. const char *content = "ims-extreme-date";
  13474. {
  13475. std::ofstream ofs(fname);
  13476. ofs << content;
  13477. ASSERT_TRUE(ofs.good());
  13478. }
  13479. Server svr;
  13480. svr.set_mount_point("/static", ".");
  13481. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13482. svr.wait_until_ready();
  13483. Client cli(HOST, PORT);
  13484. auto res1 = cli.Get(std::string("/static/") + fname);
  13485. ASSERT_TRUE(res1);
  13486. ASSERT_EQ(200, res1->status);
  13487. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13488. // Extremely large year that may overflow date parsing routines.
  13489. Headers h_large_date = {
  13490. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13491. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13492. ASSERT_TRUE(res_bad);
  13493. // Expect server to treat this as invalid/mismatch and return full content
  13494. EXPECT_EQ(200, res_bad->status);
  13495. // If-Range with extremely large date should be treated as mismatch -> full
  13496. // content (200)
  13497. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13498. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13499. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13500. ASSERT_TRUE(res_ifrange);
  13501. EXPECT_EQ(200, res_ifrange->status);
  13502. svr.stop();
  13503. t.join();
  13504. std::remove(fname);
  13505. }
  13506. TEST(ETagTest, NegativeFileModificationTime) {
  13507. using namespace httplib;
  13508. const char *fname = "ims_negative_mtime.txt";
  13509. const std::string content = "negative-mtime";
  13510. {
  13511. std::ofstream ofs(fname);
  13512. ofs << content;
  13513. ASSERT_TRUE(ofs.good());
  13514. }
  13515. // Try to set file mtime to a negative value. This may fail on some
  13516. // platforms/filesystems; if it fails, the test will still verify server
  13517. // behaves safely by performing a regular conditional request.
  13518. #if defined(__APPLE__) || defined(__linux__)
  13519. bool set_negative = false;
  13520. do {
  13521. struct timeval times[2];
  13522. // access time: now
  13523. times[0].tv_sec = time(nullptr);
  13524. times[0].tv_usec = 0;
  13525. // modification time: negative (e.g., -1)
  13526. times[1].tv_sec = -1;
  13527. times[1].tv_usec = 0;
  13528. if (utimes(fname, times) == 0) { set_negative = true; }
  13529. } while (0);
  13530. #else
  13531. bool set_negative = false;
  13532. #endif
  13533. Server svr;
  13534. svr.set_mount_point("/static", ".");
  13535. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13536. svr.wait_until_ready();
  13537. Client cli(HOST, PORT);
  13538. auto res1 = cli.Get(std::string("/static/") + fname);
  13539. ASSERT_TRUE(res1);
  13540. ASSERT_EQ(200, res1->status);
  13541. bool has_last_modified = res1->has_header("Last-Modified");
  13542. std::string last_modified;
  13543. if (has_last_modified) {
  13544. last_modified = res1->get_header_value("Last-Modified");
  13545. }
  13546. if (set_negative) {
  13547. // If we successfully set a negative mtime, ensure server returns a
  13548. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13549. // with an old date and ensure server handles it without crash.
  13550. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13551. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13552. ASSERT_TRUE(res2);
  13553. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13554. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13555. } else {
  13556. // Could not set negative mtime on this platform; fall back to verifying
  13557. // that normal invalid/malformed dates are treated safely (non-304).
  13558. Headers h_bad_date = {
  13559. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13560. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13561. ASSERT_TRUE(res_bad);
  13562. EXPECT_EQ(200, res_bad->status);
  13563. }
  13564. svr.stop();
  13565. t.join();
  13566. std::remove(fname);
  13567. }
  13568. //==============================================================================
  13569. // SSE Parsing Tests
  13570. //==============================================================================
  13571. class SSEParsingTest : public ::testing::Test {
  13572. protected:
  13573. // Test helper that mimics SSE parsing behavior
  13574. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13575. int &retry_ms) {
  13576. // Blank line signals end of event
  13577. if (line.empty() || line == "\r") { return true; }
  13578. // Lines starting with ':' are comments (ignored)
  13579. if (!line.empty() && line[0] == ':') { return false; }
  13580. // Find the colon separator
  13581. auto colon_pos = line.find(':');
  13582. if (colon_pos == std::string::npos) {
  13583. // Line with no colon is treated as field name with empty value
  13584. return false;
  13585. }
  13586. std::string field = line.substr(0, colon_pos);
  13587. std::string value;
  13588. // Value starts after colon, skip optional single space
  13589. if (colon_pos + 1 < line.size()) {
  13590. size_t value_start = colon_pos + 1;
  13591. if (line[value_start] == ' ') { value_start++; }
  13592. value = line.substr(value_start);
  13593. // Remove trailing \r if present
  13594. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13595. }
  13596. // Handle known fields
  13597. if (field == "event") {
  13598. msg.event = value;
  13599. } else if (field == "data") {
  13600. // Multiple data lines are concatenated with newlines
  13601. if (!msg.data.empty()) { msg.data += "\n"; }
  13602. msg.data += value;
  13603. } else if (field == "id") {
  13604. // Empty id is valid (clears the last event ID)
  13605. msg.id = value;
  13606. } else if (field == "retry") {
  13607. // Parse retry interval in milliseconds
  13608. {
  13609. int v = 0;
  13610. auto res =
  13611. detail::from_chars(value.data(), value.data() + value.size(), v);
  13612. if (res.ec == std::errc{}) { retry_ms = v; }
  13613. }
  13614. }
  13615. // Unknown fields are ignored per SSE spec
  13616. return false;
  13617. }
  13618. };
  13619. // Test: Single-line data
  13620. TEST_F(SSEParsingTest, SingleLineData) {
  13621. sse::SSEMessage msg;
  13622. int retry_ms = 3000;
  13623. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13624. EXPECT_EQ(msg.data, "hello");
  13625. EXPECT_EQ(msg.event, "message");
  13626. // Blank line ends event
  13627. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13628. }
  13629. // Test: Multi-line data
  13630. TEST_F(SSEParsingTest, MultiLineData) {
  13631. sse::SSEMessage msg;
  13632. int retry_ms = 3000;
  13633. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13634. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13635. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13636. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13637. }
  13638. // Test: Custom event types
  13639. TEST_F(SSEParsingTest, CustomEventType) {
  13640. sse::SSEMessage msg;
  13641. int retry_ms = 3000;
  13642. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13643. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13644. EXPECT_EQ(msg.event, "update");
  13645. EXPECT_EQ(msg.data, "payload");
  13646. }
  13647. // Test: Event ID handling
  13648. TEST_F(SSEParsingTest, EventIdHandling) {
  13649. sse::SSEMessage msg;
  13650. int retry_ms = 3000;
  13651. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13652. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13653. EXPECT_EQ(msg.id, "12345");
  13654. }
  13655. // Test: Empty event ID (clears last event ID)
  13656. TEST_F(SSEParsingTest, EmptyEventId) {
  13657. sse::SSEMessage msg;
  13658. msg.id = "previous";
  13659. int retry_ms = 3000;
  13660. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13661. EXPECT_EQ(msg.id, "");
  13662. }
  13663. // Test: Retry field parsing
  13664. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13665. sse::SSEMessage msg;
  13666. int retry_ms = 3000;
  13667. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13668. EXPECT_EQ(retry_ms, 5000);
  13669. }
  13670. // Test: Invalid retry value
  13671. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13672. sse::SSEMessage msg;
  13673. int retry_ms = 3000;
  13674. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13675. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13676. }
  13677. // Test: Comments (lines starting with :)
  13678. TEST_F(SSEParsingTest, CommentsIgnored) {
  13679. sse::SSEMessage msg;
  13680. int retry_ms = 3000;
  13681. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13682. EXPECT_EQ(msg.data, "");
  13683. EXPECT_EQ(msg.event, "message");
  13684. }
  13685. // Test: Colon in value
  13686. TEST_F(SSEParsingTest, ColonInValue) {
  13687. sse::SSEMessage msg;
  13688. int retry_ms = 3000;
  13689. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13690. EXPECT_EQ(msg.data, "hello:world:test");
  13691. }
  13692. // Test: Line with no colon (field name only)
  13693. TEST_F(SSEParsingTest, FieldNameOnly) {
  13694. sse::SSEMessage msg;
  13695. int retry_ms = 3000;
  13696. // According to SSE spec, this is treated as field name with empty value
  13697. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13698. // Since we don't recognize "data" without colon, data should be empty
  13699. EXPECT_EQ(msg.data, "");
  13700. }
  13701. // Test: Trailing \r handling
  13702. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13703. sse::SSEMessage msg;
  13704. int retry_ms = 3000;
  13705. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13706. EXPECT_EQ(msg.data, "hello");
  13707. }
  13708. // Test: Unknown fields ignored
  13709. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13710. sse::SSEMessage msg;
  13711. int retry_ms = 3000;
  13712. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13713. EXPECT_EQ(msg.data, "");
  13714. EXPECT_EQ(msg.event, "message");
  13715. }
  13716. // Test: Space after colon is optional
  13717. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13718. sse::SSEMessage msg1, msg2;
  13719. int retry_ms = 3000;
  13720. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13721. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13722. EXPECT_EQ(msg1.data, "hello");
  13723. EXPECT_EQ(msg2.data, "hello");
  13724. }
  13725. // Test: SSEMessage clear
  13726. TEST_F(SSEParsingTest, MessageClear) {
  13727. sse::SSEMessage msg;
  13728. msg.event = "custom";
  13729. msg.data = "some data";
  13730. msg.id = "123";
  13731. msg.clear();
  13732. EXPECT_EQ(msg.event, "message");
  13733. EXPECT_EQ(msg.data, "");
  13734. EXPECT_EQ(msg.id, "");
  13735. }
  13736. // Test: Complete event parsing
  13737. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13738. sse::SSEMessage msg;
  13739. int retry_ms = 3000;
  13740. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13741. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13742. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13743. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13744. // Blank line ends event
  13745. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13746. EXPECT_EQ(msg.event, "notification");
  13747. EXPECT_EQ(msg.id, "evt-42");
  13748. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13749. EXPECT_EQ(retry_ms, 1000);
  13750. }
  13751. //==============================================================================
  13752. // Integration Tests with Server
  13753. //==============================================================================
  13754. class SSEIntegrationTest : public ::testing::Test {
  13755. protected:
  13756. void SetUp() override {
  13757. stop_server_.store(false);
  13758. events_.clear();
  13759. server_ = httplib::detail::make_unique<Server>();
  13760. setup_server();
  13761. start_server();
  13762. }
  13763. void TearDown() override {
  13764. stop_server_.store(true);
  13765. event_cv_.notify_all();
  13766. server_->stop();
  13767. if (server_thread_.joinable()) { server_thread_.join(); }
  13768. }
  13769. void setup_server() {
  13770. // Simple SSE endpoint
  13771. server_->Get("/events", [this](const Request &req, Response &res) {
  13772. auto last_id = req.get_header_value("Last-Event-ID");
  13773. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13774. res.set_chunked_content_provider(
  13775. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13776. std::unique_lock<std::mutex> lock(event_mutex_);
  13777. if (event_cv_.wait_for(
  13778. lock, std::chrono::milliseconds(200), [this] {
  13779. return !events_.empty() || stop_server_.load();
  13780. })) {
  13781. if (stop_server_.load()) { return false; }
  13782. if (!events_.empty()) {
  13783. std::string event = events_.front();
  13784. events_.erase(events_.begin());
  13785. sink.write(event.data(), event.size());
  13786. return true;
  13787. }
  13788. }
  13789. return !stop_server_.load();
  13790. });
  13791. });
  13792. // Endpoint that returns error
  13793. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13794. res.status = 500;
  13795. res.set_content("Internal Server Error", "text/plain");
  13796. });
  13797. // Endpoint for custom event types
  13798. server_->Get("/custom-events", [](const Request &, Response &res) {
  13799. res.set_chunked_content_provider(
  13800. "text/event-stream", [](size_t offset, DataSink &sink) {
  13801. if (offset == 0) {
  13802. std::string event = "event: update\ndata: updated\n\n"
  13803. "event: delete\ndata: deleted\n\n";
  13804. sink.write(event.data(), event.size());
  13805. }
  13806. return false; // End stream after sending
  13807. });
  13808. });
  13809. }
  13810. void start_server() {
  13811. port_ = server_->bind_to_any_port(HOST);
  13812. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13813. // Wait for server to start
  13814. while (!server_->is_running()) {
  13815. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13816. }
  13817. }
  13818. int get_port() const { return port_; }
  13819. void send_event(const std::string &event) {
  13820. std::lock_guard<std::mutex> lock(event_mutex_);
  13821. events_.push_back(event);
  13822. event_cv_.notify_all();
  13823. }
  13824. std::unique_ptr<Server> server_;
  13825. std::thread server_thread_;
  13826. std::mutex event_mutex_;
  13827. std::condition_variable event_cv_;
  13828. std::vector<std::string> events_;
  13829. std::atomic<bool> stop_server_{false};
  13830. std::string last_received_event_id_;
  13831. int port_ = 0;
  13832. };
  13833. // Test: Successful connection and on_open callback
  13834. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13835. // Add a simple endpoint that sends one event and closes
  13836. server_->Get("/simple-event", [](const Request &, Response &res) {
  13837. res.set_chunked_content_provider(
  13838. "text/event-stream", [](size_t offset, DataSink &sink) {
  13839. if (offset == 0) {
  13840. std::string event = "data: hello\n\n";
  13841. sink.write(event.data(), event.size());
  13842. }
  13843. return false; // Close stream after sending
  13844. });
  13845. });
  13846. Client client("localhost", get_port());
  13847. sse::SSEClient sse(client, "/simple-event");
  13848. std::atomic<bool> open_called{false};
  13849. std::atomic<bool> message_received{false};
  13850. sse.on_open([&open_called]() { open_called.store(true); });
  13851. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13852. if (msg.data == "hello") { message_received.store(true); }
  13853. });
  13854. sse.set_reconnect_interval(100);
  13855. sse.set_max_reconnect_attempts(1);
  13856. // Start async
  13857. sse.start_async();
  13858. // Wait for message to be processed
  13859. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13860. sse.stop();
  13861. EXPECT_TRUE(open_called.load());
  13862. EXPECT_TRUE(message_received.load());
  13863. }
  13864. // Test: on_message callback
  13865. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13866. // Endpoint that sends multiple events then closes
  13867. server_->Get("/multi-event", [](const Request &, Response &res) {
  13868. res.set_chunked_content_provider(
  13869. "text/event-stream", [](size_t offset, DataSink &sink) {
  13870. if (offset == 0) {
  13871. std::string events = "data: message1\n\ndata: message2\n\n";
  13872. sink.write(events.data(), events.size());
  13873. }
  13874. return false;
  13875. });
  13876. });
  13877. Client client("localhost", get_port());
  13878. sse::SSEClient sse(client, "/multi-event");
  13879. std::vector<std::string> received_messages;
  13880. std::mutex messages_mutex;
  13881. sse.on_message([&](const sse::SSEMessage &msg) {
  13882. std::lock_guard<std::mutex> lock(messages_mutex);
  13883. received_messages.push_back(msg.data);
  13884. });
  13885. sse.set_reconnect_interval(100);
  13886. sse.set_max_reconnect_attempts(1);
  13887. sse.start_async();
  13888. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13889. sse.stop();
  13890. std::lock_guard<std::mutex> lock(messages_mutex);
  13891. EXPECT_GE(received_messages.size(), 2u);
  13892. if (received_messages.size() >= 2) {
  13893. EXPECT_EQ(received_messages[0], "message1");
  13894. EXPECT_EQ(received_messages[1], "message2");
  13895. }
  13896. }
  13897. // Test: on_event for specific types
  13898. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13899. Client client("localhost", get_port());
  13900. sse::SSEClient sse(client, "/custom-events");
  13901. std::atomic<bool> update_received{false};
  13902. std::atomic<bool> delete_received{false};
  13903. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13904. if (msg.data == "updated") { update_received.store(true); }
  13905. });
  13906. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13907. if (msg.data == "deleted") { delete_received.store(true); }
  13908. });
  13909. sse.set_max_reconnect_attempts(1);
  13910. sse.start_async();
  13911. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13912. sse.stop();
  13913. EXPECT_TRUE(update_received.load());
  13914. EXPECT_TRUE(delete_received.load());
  13915. }
  13916. // Test: on_error callback on connection failure
  13917. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13918. // Connect to a non-existent port
  13919. Client client("localhost", 59999);
  13920. sse::SSEClient sse(client, "/events");
  13921. std::atomic<bool> error_called{false};
  13922. Error received_error = Error::Success;
  13923. sse.on_error([&](Error err) {
  13924. error_called.store(true);
  13925. received_error = err;
  13926. });
  13927. sse.set_reconnect_interval(50);
  13928. sse.set_max_reconnect_attempts(1);
  13929. sse.start_async();
  13930. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13931. sse.stop();
  13932. EXPECT_TRUE(error_called.load());
  13933. EXPECT_NE(received_error, Error::Success);
  13934. }
  13935. // Test: Last-Event-ID header sent on reconnect
  13936. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13937. // Endpoint that sends event with ID
  13938. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13939. res.set_chunked_content_provider(
  13940. "text/event-stream", [](size_t offset, DataSink &sink) {
  13941. if (offset == 0) {
  13942. std::string event = "id: evt-123\ndata: test\n\n";
  13943. sink.write(event.data(), event.size());
  13944. }
  13945. return false;
  13946. });
  13947. });
  13948. Client client("localhost", get_port());
  13949. sse::SSEClient sse(client, "/event-with-id");
  13950. std::atomic<bool> id_received{false};
  13951. sse.on_message([&](const sse::SSEMessage &msg) {
  13952. if (!msg.id.empty()) { id_received.store(true); }
  13953. });
  13954. sse.set_reconnect_interval(100);
  13955. sse.set_max_reconnect_attempts(1);
  13956. sse.start_async();
  13957. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13958. sse.stop();
  13959. EXPECT_TRUE(id_received.load());
  13960. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13961. }
  13962. // Test: Manual stop
  13963. TEST_F(SSEIntegrationTest, ManualStop) {
  13964. // Endpoint that sends one event and stays open briefly
  13965. std::atomic<bool> handler_running{true};
  13966. server_->Get("/stay-open", [&handler_running](const Request &,
  13967. Response &res) {
  13968. res.set_chunked_content_provider(
  13969. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13970. if (offset == 0) {
  13971. std::string event = "data: connected\n\n";
  13972. sink.write(event.data(), event.size());
  13973. }
  13974. // Keep connection open while handler_running is true
  13975. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13976. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13977. }
  13978. return false;
  13979. });
  13980. });
  13981. Client client("localhost", get_port());
  13982. sse::SSEClient sse(client, "/stay-open");
  13983. std::atomic<bool> connected{false};
  13984. sse.on_open([&connected]() { connected.store(true); });
  13985. sse.set_reconnect_interval(100);
  13986. sse.set_max_reconnect_attempts(1);
  13987. sse.start_async();
  13988. // Wait for connection to establish
  13989. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13990. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13991. }
  13992. EXPECT_TRUE(connected.load());
  13993. EXPECT_TRUE(sse.is_connected());
  13994. // Signal handler to stop
  13995. handler_running.store(false);
  13996. // Stop SSE client
  13997. sse.stop();
  13998. EXPECT_FALSE(sse.is_connected());
  13999. }
  14000. // Test: SSEClient with custom headers
  14001. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14002. // Setup a server endpoint that checks for custom header
  14003. std::atomic<bool> header_received{false};
  14004. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14005. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14006. header_received.store(true);
  14007. }
  14008. res.set_chunked_content_provider("text/event-stream",
  14009. [](size_t, DataSink &) { return false; });
  14010. });
  14011. Client client("localhost", get_port());
  14012. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14013. sse::SSEClient sse(client, "/header-check", headers);
  14014. sse.set_max_reconnect_attempts(1);
  14015. sse.start_async();
  14016. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14017. sse.stop();
  14018. EXPECT_TRUE(header_received.load());
  14019. }
  14020. // Test: Reconnect interval configuration
  14021. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14022. Client client("localhost", get_port());
  14023. sse::SSEClient sse(client, "/events");
  14024. auto &result = sse.set_reconnect_interval(500);
  14025. // Builder pattern should return reference to self
  14026. EXPECT_EQ(&result, &sse);
  14027. }
  14028. // Test: Max reconnect attempts
  14029. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14030. // Connect to non-existent port to force reconnects
  14031. Client client("localhost", 59998);
  14032. sse::SSEClient sse(client, "/events");
  14033. std::atomic<int> error_count{0};
  14034. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14035. sse.set_reconnect_interval(50);
  14036. sse.set_max_reconnect_attempts(2);
  14037. auto start = std::chrono::steady_clock::now();
  14038. sse.start(); // Blocking call
  14039. auto end = std::chrono::steady_clock::now();
  14040. // Should have stopped after 2 failed attempts
  14041. EXPECT_GE(error_count.load(), 2);
  14042. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14043. auto duration =
  14044. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14045. #ifdef _WIN32
  14046. // Windows is much slower for socket connection failures
  14047. EXPECT_LT(duration.count(), 7000);
  14048. #else
  14049. EXPECT_LT(duration.count(), 1000);
  14050. #endif
  14051. }
  14052. // Test: Multi-line data in integration
  14053. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14054. // Endpoint with multi-line data
  14055. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14056. res.set_chunked_content_provider(
  14057. "text/event-stream", [](size_t offset, DataSink &sink) {
  14058. if (offset == 0) {
  14059. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14060. sink.write(event.data(), event.size());
  14061. }
  14062. return false;
  14063. });
  14064. });
  14065. Client client("localhost", get_port());
  14066. sse::SSEClient sse(client, "/multiline-data");
  14067. std::string received_data;
  14068. std::mutex data_mutex;
  14069. sse.on_message([&](const sse::SSEMessage &msg) {
  14070. std::lock_guard<std::mutex> lock(data_mutex);
  14071. received_data = msg.data;
  14072. });
  14073. sse.set_reconnect_interval(100);
  14074. sse.set_max_reconnect_attempts(1);
  14075. sse.start_async();
  14076. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14077. sse.stop();
  14078. std::lock_guard<std::mutex> lock(data_mutex);
  14079. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14080. }
  14081. // Test: Auto-reconnect after server disconnection
  14082. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14083. std::atomic<int> connection_count{0};
  14084. std::atomic<int> message_count{0};
  14085. // Endpoint that sends one event and closes, forcing reconnect
  14086. server_->Get("/reconnect-test",
  14087. [&connection_count](const Request &, Response &res) {
  14088. connection_count.fetch_add(1);
  14089. res.set_chunked_content_provider(
  14090. "text/event-stream", [](size_t offset, DataSink &sink) {
  14091. if (offset == 0) {
  14092. std::string event = "data: hello\n\n";
  14093. sink.write(event.data(), event.size());
  14094. }
  14095. return false; // Close connection after sending
  14096. });
  14097. });
  14098. Client client("localhost", get_port());
  14099. sse::SSEClient sse(client, "/reconnect-test");
  14100. sse.on_message([&message_count](const sse::SSEMessage &) {
  14101. message_count.fetch_add(1);
  14102. });
  14103. sse.set_reconnect_interval(100);
  14104. sse.set_max_reconnect_attempts(3);
  14105. sse.start_async();
  14106. // Wait long enough for multiple reconnects
  14107. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14108. sse.stop();
  14109. // Should have connected multiple times (initial + reconnects)
  14110. EXPECT_GE(connection_count.load(), 2);
  14111. // Should have received messages from multiple connections
  14112. EXPECT_GE(message_count.load(), 2);
  14113. }
  14114. // Test: Last-Event-ID sent on reconnect
  14115. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14116. std::atomic<int> connection_count{0};
  14117. std::vector<std::string> received_last_event_ids;
  14118. std::mutex id_mutex;
  14119. // Endpoint that checks Last-Event-ID header and sends event with ID
  14120. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14121. int conn = connection_count.fetch_add(1);
  14122. // Capture the Last-Event-ID header from each connection
  14123. {
  14124. std::lock_guard<std::mutex> lock(id_mutex);
  14125. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14126. }
  14127. res.set_chunked_content_provider(
  14128. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14129. if (offset == 0) {
  14130. std::string event =
  14131. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14132. sink.write(event.data(), event.size());
  14133. }
  14134. return false;
  14135. });
  14136. });
  14137. Client client("localhost", get_port());
  14138. sse::SSEClient sse(client, "/reconnect-with-id");
  14139. sse.set_reconnect_interval(100);
  14140. sse.set_max_reconnect_attempts(3);
  14141. sse.start_async();
  14142. // Wait for at least 2 connections
  14143. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14144. sse.stop();
  14145. // Verify behavior
  14146. std::lock_guard<std::mutex> lock(id_mutex);
  14147. EXPECT_GE(received_last_event_ids.size(), 2u);
  14148. // First connection should have no Last-Event-ID
  14149. if (!received_last_event_ids.empty()) {
  14150. EXPECT_EQ(received_last_event_ids[0], "");
  14151. }
  14152. // Second connection should have Last-Event-ID from first connection
  14153. if (received_last_event_ids.size() >= 2) {
  14154. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14155. }
  14156. }
  14157. // Test: set_headers updates headers used on reconnect
  14158. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14159. std::vector<std::string> received_tokens;
  14160. std::mutex token_mutex;
  14161. // Endpoint that captures Authorization header
  14162. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14163. {
  14164. std::lock_guard<std::mutex> lock(token_mutex);
  14165. received_tokens.push_back(req.get_header_value("Authorization"));
  14166. }
  14167. res.set_chunked_content_provider(
  14168. "text/event-stream", [](size_t offset, DataSink &sink) {
  14169. if (offset == 0) {
  14170. std::string event = "data: hello\n\n";
  14171. sink.write(event.data(), event.size());
  14172. }
  14173. return false; // Close connection to trigger reconnect
  14174. });
  14175. });
  14176. Client client("localhost", get_port());
  14177. Headers headers = {{"Authorization", "Bearer old-token"}};
  14178. sse::SSEClient sse(client, "/auth-check", headers);
  14179. // Update headers on each successful connection
  14180. sse.on_open(
  14181. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14182. sse.set_reconnect_interval(100);
  14183. sse.set_max_reconnect_attempts(3);
  14184. sse.start_async();
  14185. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14186. sse.stop();
  14187. std::lock_guard<std::mutex> lock(token_mutex);
  14188. ASSERT_GE(received_tokens.size(), 2u);
  14189. // First connection uses original header
  14190. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14191. // Second connection uses updated header from set_headers
  14192. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14193. }
  14194. // Test: 401 allows reconnection (so on_error can refresh headers)
  14195. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14196. std::atomic<int> connection_count{0};
  14197. // Endpoint: returns 401 on first attempt, 200 on second
  14198. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14199. int conn = connection_count.fetch_add(1);
  14200. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14201. res.status = StatusCode::Unauthorized_401;
  14202. res.set_content("Unauthorized", "text/plain");
  14203. return;
  14204. }
  14205. res.set_chunked_content_provider(
  14206. "text/event-stream", [](size_t offset, DataSink &sink) {
  14207. if (offset == 0) {
  14208. std::string event = "data: authenticated\n\n";
  14209. sink.write(event.data(), event.size());
  14210. }
  14211. return false;
  14212. });
  14213. });
  14214. Client client("localhost", get_port());
  14215. Headers headers = {{"Authorization", "Bearer expired"}};
  14216. sse::SSEClient sse(client, "/auth-retry", headers);
  14217. std::atomic<bool> message_received{false};
  14218. // Refresh token on error
  14219. sse.on_error(
  14220. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14221. sse.on_message([&](const sse::SSEMessage &msg) {
  14222. if (msg.data == "authenticated") { message_received.store(true); }
  14223. });
  14224. sse.set_reconnect_interval(100);
  14225. sse.set_max_reconnect_attempts(3);
  14226. sse.start_async();
  14227. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14228. sse.stop();
  14229. // Should have reconnected after 401 and succeeded with new token
  14230. EXPECT_GE(connection_count.load(), 2);
  14231. EXPECT_TRUE(message_received.load());
  14232. }
  14233. TEST(Issue2318Test, EmptyHostString) {
  14234. {
  14235. httplib::Client cli_empty("", PORT);
  14236. auto res = cli_empty.Get("/");
  14237. ASSERT_FALSE(res);
  14238. EXPECT_EQ(httplib::Error::Connection, res.error());
  14239. }
  14240. {
  14241. httplib::Client cli(" ", PORT);
  14242. auto res = cli.Get("/");
  14243. ASSERT_FALSE(res);
  14244. EXPECT_EQ(httplib::Error::Connection, res.error());
  14245. }
  14246. }
  14247. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14248. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14249. Server svr;
  14250. // Set a small payload limit (1KB)
  14251. svr.set_payload_max_length(1024);
  14252. svr.Post("/test", [&](const Request &req, Response &res) {
  14253. res.set_content("Body size: " + std::to_string(req.body.size()),
  14254. "text/plain");
  14255. });
  14256. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14257. auto se = detail::scope_exit([&] {
  14258. svr.stop();
  14259. listen_thread.join();
  14260. });
  14261. svr.wait_until_ready();
  14262. // Create data that compresses well but exceeds limit when decompressed
  14263. // 8KB of repeated null bytes compresses to a very small size
  14264. std::string original_data(8 * 1024, '\0');
  14265. // Compress the data using gzip
  14266. std::string compressed_data;
  14267. detail::gzip_compressor compressor;
  14268. compressor.compress(original_data.data(), original_data.size(), true,
  14269. [&](const char *data, size_t size) {
  14270. compressed_data.append(data, size);
  14271. return true;
  14272. });
  14273. // Verify compression worked (compressed should be much smaller)
  14274. ASSERT_LT(compressed_data.size(), original_data.size());
  14275. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14276. // Send compressed data with Content-Encoding: gzip
  14277. Client cli(HOST, PORT);
  14278. Headers headers = {{"Content-Encoding", "gzip"}};
  14279. auto res =
  14280. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14281. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14282. ASSERT_TRUE(res);
  14283. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14284. }
  14285. #endif
  14286. // ============================================================================
  14287. // OpenSSL-Specific Tests
  14288. // ============================================================================
  14289. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14290. X509 *readCertificate(const std::string &strFileName) {
  14291. std::ifstream inStream(strFileName);
  14292. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14293. std::istreambuf_iterator<char>());
  14294. if (strCertPEM.empty()) return (nullptr);
  14295. BIO *pbCert = BIO_new(BIO_s_mem());
  14296. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14297. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14298. BIO_free(pbCert);
  14299. return (pCert);
  14300. }
  14301. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14302. std::ifstream inStream(strFileName);
  14303. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14304. std::istreambuf_iterator<char>());
  14305. if (strPrivateKeyPEM.empty()) return (nullptr);
  14306. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14307. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14308. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14309. BIO_free(pbPrivKey);
  14310. return (pPrivateKey);
  14311. }
  14312. TEST(BindServerTest, UpdateCerts) {
  14313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14314. int port = svr.bind_to_any_port("0.0.0.0");
  14315. ASSERT_TRUE(svr.is_valid());
  14316. ASSERT_TRUE(port > 0);
  14317. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14318. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14319. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14320. ASSERT_TRUE(cert != nullptr);
  14321. ASSERT_TRUE(ca_cert != nullptr);
  14322. ASSERT_TRUE(key != nullptr);
  14323. X509_STORE *cert_store = X509_STORE_new();
  14324. X509_STORE_add_cert(cert_store, ca_cert);
  14325. // svr.update_certs(cert, key, cert_store); // deprecated
  14326. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14327. CLIENT_CA_CERT_FILE);
  14328. ASSERT_TRUE(svr.is_valid());
  14329. svr.stop();
  14330. X509_STORE_free(cert_store);
  14331. X509_free(cert);
  14332. X509_free(ca_cert);
  14333. EVP_PKEY_free(key);
  14334. }
  14335. // Test that update_certs() updates client CA list correctly
  14336. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14337. // Start with file-based constructor
  14338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14339. ASSERT_TRUE(svr.is_valid());
  14340. // Initially no client CA list should be set
  14341. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14342. ASSERT_TRUE(ssl_ctx != nullptr);
  14343. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14344. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14345. EXPECT_EQ(0, count_before);
  14346. // Now update with client CA (PEM string)
  14347. std::string cert_pem, key_pem, ca_pem;
  14348. read_file(SERVER_CERT_FILE, cert_pem);
  14349. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14350. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14351. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14352. ASSERT_TRUE(svr.is_valid());
  14353. // Now client CA list should be set
  14354. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14355. ASSERT_TRUE(ca_list_after != nullptr);
  14356. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14357. }
  14358. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14359. // Test that the file-path SSLServer constructor properly sets the client CA
  14360. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14362. ASSERT_TRUE(svr.is_valid());
  14363. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14364. ASSERT_TRUE(ssl_ctx != nullptr);
  14365. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14366. ASSERT_TRUE(ca_list != nullptr);
  14367. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14368. }
  14369. #endif
  14370. // ============================================================================
  14371. // MbedTLS-Specific Tests
  14372. // ============================================================================
  14373. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14374. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14375. using namespace httplib::tls;
  14376. // Track if callback was invoked
  14377. bool callback_invoked = false;
  14378. // The callback receives void* ctx which is actually MbedTlsContext*
  14379. // We can access the mbedtls_ssl_config via the context
  14380. auto setup_callback = [&callback_invoked](void *ctx) {
  14381. callback_invoked = true;
  14382. // Cast to MbedTlsContext* to access the ssl config
  14383. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14384. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14385. // Use static variables to hold certificate data (simplified for test)
  14386. static mbedtls_x509_crt own_cert;
  14387. static mbedtls_pk_context own_key;
  14388. static mbedtls_x509_crt ca_chain;
  14389. static bool initialized = false;
  14390. if (!initialized) {
  14391. mbedtls_x509_crt_init(&own_cert);
  14392. mbedtls_pk_init(&own_key);
  14393. mbedtls_x509_crt_init(&ca_chain);
  14394. // Load server certificate
  14395. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14396. return false;
  14397. }
  14398. // Load server private key
  14399. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14400. #if MBEDTLS_VERSION_MAJOR >= 3
  14401. ,
  14402. mbedtls_ctr_drbg_random, nullptr
  14403. #endif
  14404. ) != 0) {
  14405. return false;
  14406. }
  14407. // Load CA chain for client verification
  14408. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14409. return false;
  14410. }
  14411. initialized = true;
  14412. }
  14413. // Configure the SSL config
  14414. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14415. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14416. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14417. // Set minimum TLS version using mbedTLS native API
  14418. #if MBEDTLS_VERSION_MAJOR >= 3
  14419. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14420. #else
  14421. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14422. MBEDTLS_SSL_MINOR_VERSION_3);
  14423. #endif
  14424. return true;
  14425. };
  14426. SSLServer svr(setup_callback);
  14427. ASSERT_TRUE(svr.is_valid());
  14428. ASSERT_TRUE(callback_invoked);
  14429. svr.Get("/test", [&](const Request &req, Response &res) {
  14430. res.set_content("test", "text/plain");
  14431. auto cert = req.peer_cert();
  14432. ASSERT_TRUE(static_cast<bool>(cert));
  14433. auto common_name = cert.subject_cn();
  14434. EXPECT_EQ("Common Name", common_name);
  14435. });
  14436. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. });
  14442. svr.wait_until_ready();
  14443. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14444. cli.enable_server_certificate_verification(false);
  14445. cli.set_connection_timeout(30);
  14446. auto res = cli.Get("/test");
  14447. ASSERT_TRUE(res);
  14448. ASSERT_EQ(StatusCode::OK_200, res->status);
  14449. }
  14450. #endif
  14451. // WebSocket Tests
  14452. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14453. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14454. // defining the meaning of these bits has been negotiated.
  14455. auto make_frame = [](uint8_t first_byte) {
  14456. std::string frame;
  14457. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14458. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14459. frame += "Hello";
  14460. return frame;
  14461. };
  14462. // RSV1 set (0x40)
  14463. {
  14464. detail::BufferStream strm;
  14465. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14466. ws::Opcode opcode;
  14467. std::string payload;
  14468. bool fin;
  14469. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14470. false, 1024));
  14471. }
  14472. // RSV2 set (0x20)
  14473. {
  14474. detail::BufferStream strm;
  14475. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14476. ws::Opcode opcode;
  14477. std::string payload;
  14478. bool fin;
  14479. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14480. false, 1024));
  14481. }
  14482. // RSV3 set (0x10)
  14483. {
  14484. detail::BufferStream strm;
  14485. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14486. ws::Opcode opcode;
  14487. std::string payload;
  14488. bool fin;
  14489. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14490. false, 1024));
  14491. }
  14492. // No RSV bits set - should succeed
  14493. {
  14494. detail::BufferStream strm;
  14495. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14496. ws::Opcode opcode;
  14497. std::string payload;
  14498. bool fin;
  14499. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14500. false, 1024));
  14501. EXPECT_EQ(ws::Opcode::Text, opcode);
  14502. EXPECT_EQ("Hello", payload);
  14503. EXPECT_TRUE(fin);
  14504. }
  14505. }
  14506. TEST(WebSocketTest, ControlFrameValidation) {
  14507. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14508. // payload length <= 125.
  14509. // Ping with FIN=0 - must be rejected
  14510. {
  14511. detail::BufferStream strm;
  14512. std::string frame;
  14513. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14514. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14515. strm.write(frame.data(), frame.size());
  14516. ws::Opcode opcode;
  14517. std::string payload;
  14518. bool fin;
  14519. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14520. false, 1024));
  14521. }
  14522. // Close with FIN=0 - must be rejected
  14523. {
  14524. detail::BufferStream strm;
  14525. std::string frame;
  14526. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14527. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14528. strm.write(frame.data(), frame.size());
  14529. ws::Opcode opcode;
  14530. std::string payload;
  14531. bool fin;
  14532. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14533. false, 1024));
  14534. }
  14535. // Ping with payload_len=126 (extended length) - must be rejected
  14536. {
  14537. detail::BufferStream strm;
  14538. std::string frame;
  14539. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14540. frame += static_cast<char>(126); // payload_len=126 (>125)
  14541. frame += static_cast<char>(0x00); // extended length high byte
  14542. frame += static_cast<char>(126); // extended length low byte
  14543. frame += std::string(126, 'x');
  14544. strm.write(frame.data(), frame.size());
  14545. ws::Opcode opcode;
  14546. std::string payload;
  14547. bool fin;
  14548. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14549. false, 1024));
  14550. }
  14551. // Ping with FIN=1 and payload_len=125 - should succeed
  14552. {
  14553. detail::BufferStream strm;
  14554. std::string frame;
  14555. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14556. frame += static_cast<char>(125); // payload_len=125
  14557. frame += std::string(125, 'x');
  14558. strm.write(frame.data(), frame.size());
  14559. ws::Opcode opcode;
  14560. std::string payload;
  14561. bool fin;
  14562. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14563. false, 1024));
  14564. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14565. EXPECT_EQ(125u, payload.size());
  14566. EXPECT_TRUE(fin);
  14567. }
  14568. }
  14569. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14570. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14571. // length MUST be 0.
  14572. // MSB set - must be rejected
  14573. {
  14574. detail::BufferStream strm;
  14575. std::string frame;
  14576. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14577. frame += static_cast<char>(127); // 64-bit extended length
  14578. frame += static_cast<char>(0x80); // MSB set (invalid)
  14579. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14580. strm.write(frame.data(), frame.size());
  14581. ws::Opcode opcode;
  14582. std::string payload;
  14583. bool fin;
  14584. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14585. false, 1024));
  14586. }
  14587. // MSB clear - should pass length parsing (will be rejected by max_len,
  14588. // but that's a different check; use a small length to verify)
  14589. {
  14590. detail::BufferStream strm;
  14591. std::string frame;
  14592. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14593. frame += static_cast<char>(127); // 64-bit extended length
  14594. frame += std::string(7, '\0'); // high bytes = 0
  14595. frame += static_cast<char>(0x03); // length = 3
  14596. frame += "abc";
  14597. strm.write(frame.data(), frame.size());
  14598. ws::Opcode opcode;
  14599. std::string payload;
  14600. bool fin;
  14601. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14602. false, 1024));
  14603. EXPECT_EQ(ws::Opcode::Text, opcode);
  14604. EXPECT_EQ("abc", payload);
  14605. }
  14606. }
  14607. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14608. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14609. // Valid UTF-8
  14610. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14611. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14612. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14613. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14614. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14615. // Invalid UTF-8
  14616. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14617. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14618. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14619. EXPECT_FALSE(
  14620. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14621. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14622. }
  14623. TEST(WebSocketTest, ConnectAndDisconnect) {
  14624. Server svr;
  14625. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14626. std::string msg;
  14627. while (ws.read(msg)) {}
  14628. });
  14629. auto port = svr.bind_to_any_port(HOST);
  14630. std::thread t([&]() { svr.listen_after_bind(); });
  14631. svr.wait_until_ready();
  14632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14633. ASSERT_TRUE(client.connect());
  14634. EXPECT_TRUE(client.is_open());
  14635. client.close();
  14636. EXPECT_FALSE(client.is_open());
  14637. svr.stop();
  14638. t.join();
  14639. }
  14640. TEST(WebSocketTest, ValidURL) {
  14641. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14642. EXPECT_TRUE(ws1.is_valid());
  14643. ws::WebSocketClient ws2("ws://example.com/path");
  14644. EXPECT_TRUE(ws2.is_valid());
  14645. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14646. EXPECT_TRUE(ws3.is_valid());
  14647. #ifdef CPPHTTPLIB_SSL_ENABLED
  14648. ws::WebSocketClient wss1("wss://example.com/path");
  14649. EXPECT_TRUE(wss1.is_valid());
  14650. ws::WebSocketClient wss2("wss://example.com:443/path");
  14651. EXPECT_TRUE(wss2.is_valid());
  14652. #endif
  14653. }
  14654. TEST(WebSocketTest, InvalidURL) {
  14655. // No scheme
  14656. ws::WebSocketClient ws1("localhost:8080/path");
  14657. EXPECT_FALSE(ws1.is_valid());
  14658. // No path
  14659. ws::WebSocketClient ws2("ws://localhost:8080");
  14660. EXPECT_FALSE(ws2.is_valid());
  14661. // Empty string
  14662. ws::WebSocketClient ws3("");
  14663. EXPECT_FALSE(ws3.is_valid());
  14664. // Missing host
  14665. ws::WebSocketClient ws4("ws://:8080/path");
  14666. EXPECT_FALSE(ws4.is_valid());
  14667. // Port number overflow — should not crash
  14668. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14669. EXPECT_FALSE(ws5.is_valid());
  14670. // Port out of range
  14671. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14672. EXPECT_FALSE(ws6.is_valid());
  14673. }
  14674. TEST(WebSocketTest, UnsupportedScheme) {
  14675. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14676. ws::WebSocketClient ws1("http://localhost:8080/path");
  14677. EXPECT_FALSE(ws1.is_valid());
  14678. ws::WebSocketClient ws2("https://localhost:8080/path");
  14679. EXPECT_FALSE(ws2.is_valid());
  14680. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14681. EXPECT_FALSE(ws3.is_valid());
  14682. #else
  14683. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14684. std::invalid_argument);
  14685. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14686. std::invalid_argument);
  14687. #endif
  14688. }
  14689. TEST(WebSocketTest, ConnectWhenInvalid) {
  14690. ws::WebSocketClient ws("not a valid url");
  14691. EXPECT_FALSE(ws.is_valid());
  14692. EXPECT_FALSE(ws.connect());
  14693. }
  14694. TEST(WebSocketTest, DefaultPort) {
  14695. ws::WebSocketClient ws1("ws://example.com/path");
  14696. EXPECT_TRUE(ws1.is_valid());
  14697. // ws:// defaults to port 80 (verified by successful parse)
  14698. #ifdef CPPHTTPLIB_SSL_ENABLED
  14699. ws::WebSocketClient ws2("wss://example.com/path");
  14700. EXPECT_TRUE(ws2.is_valid());
  14701. // wss:// defaults to port 443 (verified by successful parse)
  14702. #endif
  14703. }
  14704. TEST(WebSocketTest, IPv6LiteralAddress) {
  14705. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14706. EXPECT_TRUE(ws1.is_valid());
  14707. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14708. EXPECT_TRUE(ws2.is_valid());
  14709. }
  14710. TEST(WebSocketTest, ComplexPath) {
  14711. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14712. EXPECT_TRUE(ws1.is_valid());
  14713. ws::WebSocketClient ws2("ws://localhost:8080/");
  14714. EXPECT_TRUE(ws2.is_valid());
  14715. }
  14716. class WebSocketIntegrationTest : public ::testing::Test {
  14717. protected:
  14718. void SetUp() override {
  14719. server_ = httplib::detail::make_unique<Server>();
  14720. setup_server();
  14721. start_server();
  14722. }
  14723. void TearDown() override {
  14724. server_->stop();
  14725. if (server_thread_.joinable()) { server_thread_.join(); }
  14726. }
  14727. void setup_server() {
  14728. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14729. std::string msg;
  14730. ws::ReadResult ret;
  14731. while ((ret = ws.read(msg))) {
  14732. if (ret == ws::Binary) {
  14733. ws.send(msg.data(), msg.size());
  14734. } else {
  14735. ws.send(msg);
  14736. }
  14737. }
  14738. });
  14739. server_->WebSocket("/ws-echo-string",
  14740. [](const Request &, ws::WebSocket &ws) {
  14741. std::string msg;
  14742. while (ws.read(msg)) {
  14743. ws.send("echo: " + msg);
  14744. }
  14745. });
  14746. server_->WebSocket(
  14747. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14748. // Echo back request metadata
  14749. ws.send("path:" + req.path);
  14750. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14751. std::string msg;
  14752. while (ws.read(msg)) {}
  14753. });
  14754. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14755. std::string msg;
  14756. ws.read(msg); // wait for a message
  14757. ws.close();
  14758. });
  14759. server_->WebSocket("/ws-close-status",
  14760. [](const Request &, ws::WebSocket &ws) {
  14761. std::string msg;
  14762. ws.read(msg); // wait for a message
  14763. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14764. });
  14765. server_->WebSocket(
  14766. "/ws-subprotocol",
  14767. [](const Request &, ws::WebSocket &ws) {
  14768. std::string msg;
  14769. while (ws.read(msg)) {
  14770. ws.send(msg);
  14771. }
  14772. },
  14773. [](const std::vector<std::string> &protocols) -> std::string {
  14774. for (const auto &p : protocols) {
  14775. if (p == "graphql-ws") { return p; }
  14776. }
  14777. return "";
  14778. });
  14779. }
  14780. void start_server() {
  14781. port_ = server_->bind_to_any_port(HOST);
  14782. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14783. server_->wait_until_ready();
  14784. }
  14785. std::unique_ptr<Server> server_;
  14786. std::thread server_thread_;
  14787. int port_ = 0;
  14788. };
  14789. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14791. "/ws-echo");
  14792. ASSERT_TRUE(client.connect());
  14793. ASSERT_TRUE(client.is_open());
  14794. ASSERT_TRUE(client.send("Hello WebSocket"));
  14795. std::string msg;
  14796. EXPECT_EQ(ws::Text, client.read(msg));
  14797. EXPECT_EQ("Hello WebSocket", msg);
  14798. client.close();
  14799. }
  14800. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14801. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14802. "/ws-echo");
  14803. ASSERT_TRUE(client.connect());
  14804. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14805. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14806. std::string msg;
  14807. EXPECT_EQ(ws::Binary, client.read(msg));
  14808. EXPECT_EQ(binary_data, msg);
  14809. client.close();
  14810. }
  14811. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14813. "/ws-echo");
  14814. ASSERT_TRUE(client.connect());
  14815. for (int i = 0; i < 10; i++) {
  14816. auto text = "message " + std::to_string(i);
  14817. ASSERT_TRUE(client.send(text));
  14818. std::string msg;
  14819. ASSERT_TRUE(client.read(msg));
  14820. EXPECT_EQ(text, msg);
  14821. }
  14822. client.close();
  14823. }
  14824. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14826. "/ws-close");
  14827. ASSERT_TRUE(client.connect());
  14828. // Send a message to trigger the server to close
  14829. ASSERT_TRUE(client.send("trigger close"));
  14830. // The server will close, so read should return false
  14831. std::string msg;
  14832. EXPECT_FALSE(client.read(msg));
  14833. EXPECT_FALSE(client.is_open());
  14834. }
  14835. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14837. "/ws-echo");
  14838. ASSERT_TRUE(client.connect());
  14839. // 128KB message
  14840. std::string large_data(128 * 1024, 'X');
  14841. ASSERT_TRUE(client.send(large_data));
  14842. std::string msg;
  14843. ASSERT_TRUE(client.read(msg));
  14844. EXPECT_EQ(large_data, msg);
  14845. client.close();
  14846. }
  14847. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14848. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14849. "/ws-echo");
  14850. ASSERT_TRUE(client.connect());
  14851. const int num_threads = 4;
  14852. std::vector<std::thread> threads;
  14853. std::atomic<int> send_count{0};
  14854. for (int t = 0; t < num_threads; t++) {
  14855. threads.emplace_back([&client, &send_count, t]() {
  14856. for (int i = 0; i < 5; i++) {
  14857. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14858. if (client.send(text)) { send_count++; }
  14859. }
  14860. });
  14861. }
  14862. for (auto &th : threads) {
  14863. th.join();
  14864. }
  14865. int received = 0;
  14866. std::string msg;
  14867. while (received < send_count.load()) {
  14868. if (!client.read(msg)) { break; }
  14869. received++;
  14870. }
  14871. EXPECT_EQ(send_count.load(), received);
  14872. client.close();
  14873. }
  14874. TEST_F(WebSocketIntegrationTest, ReadString) {
  14875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14876. "/ws-echo-string");
  14877. ASSERT_TRUE(client.connect());
  14878. ASSERT_TRUE(client.send("hello"));
  14879. std::string msg;
  14880. ASSERT_TRUE(client.read(msg));
  14881. EXPECT_EQ("echo: hello", msg);
  14882. ASSERT_TRUE(client.send("world"));
  14883. ASSERT_TRUE(client.read(msg));
  14884. EXPECT_EQ("echo: world", msg);
  14885. client.close();
  14886. }
  14887. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14888. Headers headers = {{"X-Test-Header", "test-value"}};
  14889. ws::WebSocketClient client(
  14890. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14891. ASSERT_TRUE(client.connect());
  14892. std::string msg;
  14893. ASSERT_TRUE(client.read(msg));
  14894. EXPECT_EQ("path:/ws-request-info", msg);
  14895. ASSERT_TRUE(client.read(msg));
  14896. EXPECT_EQ("header:test-value", msg);
  14897. client.close();
  14898. }
  14899. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14900. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14901. "/ws-echo");
  14902. client.set_read_timeout(1, 0); // 1 second
  14903. ASSERT_TRUE(client.connect());
  14904. // Don't send anything — server echo handler waits for a message,
  14905. // so read() should time out and return false.
  14906. std::string msg;
  14907. EXPECT_FALSE(client.read(msg));
  14908. }
  14909. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14910. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14911. "/ws-echo");
  14912. client.set_read_timeout(5, 0);
  14913. ASSERT_TRUE(client.connect());
  14914. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14915. // The server should reject it and close the connection.
  14916. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14917. client.send(oversized);
  14918. // The server's read() should have failed due to payload limit,
  14919. // so our read() should return false (connection closed).
  14920. std::string msg;
  14921. EXPECT_FALSE(client.read(msg));
  14922. }
  14923. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14925. "/ws-echo");
  14926. client.set_read_timeout(10, 0);
  14927. ASSERT_TRUE(client.connect());
  14928. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14929. // This should succeed.
  14930. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14931. ASSERT_TRUE(client.send(at_limit));
  14932. std::string msg;
  14933. ASSERT_TRUE(client.read(msg));
  14934. EXPECT_EQ(at_limit.size(), msg.size());
  14935. client.close();
  14936. }
  14937. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14939. "/nonexistent");
  14940. EXPECT_FALSE(client.connect());
  14941. EXPECT_FALSE(client.is_open());
  14942. }
  14943. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14945. "/ws-echo");
  14946. ASSERT_TRUE(client.connect());
  14947. ASSERT_TRUE(client.send(""));
  14948. std::string msg;
  14949. EXPECT_EQ(ws::Text, client.read(msg));
  14950. EXPECT_EQ("", msg);
  14951. client.close();
  14952. }
  14953. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14954. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14955. "/ws-echo");
  14956. // First connection
  14957. ASSERT_TRUE(client.connect());
  14958. ASSERT_TRUE(client.send("first"));
  14959. std::string msg;
  14960. ASSERT_TRUE(client.read(msg));
  14961. EXPECT_EQ("first", msg);
  14962. client.close();
  14963. EXPECT_FALSE(client.is_open());
  14964. // Reconnect using the same client object
  14965. ASSERT_TRUE(client.connect());
  14966. ASSERT_TRUE(client.is_open());
  14967. ASSERT_TRUE(client.send("second"));
  14968. ASSERT_TRUE(client.read(msg));
  14969. EXPECT_EQ("second", msg);
  14970. client.close();
  14971. }
  14972. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14974. "/ws-close-status");
  14975. ASSERT_TRUE(client.connect());
  14976. // Trigger the server to close with GoingAway status
  14977. ASSERT_TRUE(client.send("trigger"));
  14978. // read() should return false after receiving the close frame
  14979. std::string msg;
  14980. EXPECT_FALSE(client.read(msg));
  14981. EXPECT_FALSE(client.is_open());
  14982. }
  14983. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14984. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14985. "/ws-echo");
  14986. ASSERT_TRUE(client.connect());
  14987. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14988. EXPECT_FALSE(client.is_open());
  14989. }
  14990. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14991. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14992. ws::WebSocketClient client(
  14993. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14994. ASSERT_TRUE(client.connect());
  14995. // Server should have selected graphql-ws
  14996. EXPECT_EQ("graphql-ws", client.subprotocol());
  14997. client.close();
  14998. }
  14999. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15000. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15001. ws::WebSocketClient client(
  15002. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15003. ASSERT_TRUE(client.connect());
  15004. // Server should not have selected any subprotocol
  15005. EXPECT_TRUE(client.subprotocol().empty());
  15006. client.close();
  15007. }
  15008. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15009. // Connect without requesting any subprotocol
  15010. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15011. "/ws-subprotocol");
  15012. ASSERT_TRUE(client.connect());
  15013. EXPECT_TRUE(client.subprotocol().empty());
  15014. client.close();
  15015. }
  15016. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15018. "/ws-echo");
  15019. client.set_tcp_nodelay(true);
  15020. client.set_connection_timeout(3, 0);
  15021. bool socket_options_called = false;
  15022. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15023. ASSERT_TRUE(client.connect());
  15024. ASSERT_TRUE(client.is_open());
  15025. EXPECT_TRUE(socket_options_called);
  15026. ASSERT_TRUE(client.send("hello"));
  15027. std::string msg;
  15028. auto result = client.read(msg);
  15029. EXPECT_EQ(result, ws::ReadResult::Text);
  15030. EXPECT_EQ(msg, "hello");
  15031. client.close();
  15032. }
  15033. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15034. Server svr;
  15035. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15036. if (!req.has_header("Authorization")) {
  15037. res.status = StatusCode::Unauthorized_401;
  15038. res.set_content("Unauthorized", "text/plain");
  15039. return Server::HandlerResponse::Handled;
  15040. }
  15041. return Server::HandlerResponse::Unhandled;
  15042. });
  15043. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15044. std::string msg;
  15045. while (ws.read(msg)) {
  15046. ws.send(msg);
  15047. }
  15048. });
  15049. auto port = svr.bind_to_any_port("localhost");
  15050. std::thread t([&]() { svr.listen_after_bind(); });
  15051. svr.wait_until_ready();
  15052. // Without Authorization header - should be rejected before upgrade
  15053. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15054. EXPECT_FALSE(client1.connect());
  15055. // With Authorization header - should succeed
  15056. Headers headers = {{"Authorization", "Bearer token123"}};
  15057. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15058. headers);
  15059. ASSERT_TRUE(client2.connect());
  15060. ASSERT_TRUE(client2.send("hello"));
  15061. std::string msg;
  15062. ASSERT_TRUE(client2.read(msg));
  15063. EXPECT_EQ("hello", msg);
  15064. client2.close();
  15065. svr.stop();
  15066. t.join();
  15067. }
  15068. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15069. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15070. protected:
  15071. void SetUp() override {
  15072. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15073. SERVER_PRIVATE_KEY_FILE);
  15074. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15075. std::string msg;
  15076. ws::ReadResult ret;
  15077. while ((ret = ws.read(msg))) {
  15078. if (ret == ws::Binary) {
  15079. ws.send(msg.data(), msg.size());
  15080. } else {
  15081. ws.send(msg);
  15082. }
  15083. }
  15084. });
  15085. port_ = server_->bind_to_any_port(HOST);
  15086. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15087. server_->wait_until_ready();
  15088. }
  15089. void TearDown() override {
  15090. server_->stop();
  15091. if (server_thread_.joinable()) { server_thread_.join(); }
  15092. }
  15093. std::unique_ptr<SSLServer> server_;
  15094. std::thread server_thread_;
  15095. int port_ = 0;
  15096. };
  15097. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15098. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15099. "/ws-echo");
  15100. client.enable_server_certificate_verification(false);
  15101. ASSERT_TRUE(client.connect());
  15102. ASSERT_TRUE(client.is_open());
  15103. ASSERT_TRUE(client.send("Hello WSS"));
  15104. std::string msg;
  15105. EXPECT_EQ(ws::Text, client.read(msg));
  15106. EXPECT_EQ("Hello WSS", msg);
  15107. client.close();
  15108. }
  15109. #endif
  15110. #if !defined(_WIN32)
  15111. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15112. auto secret_dir = std::string("./symlink_test_secret");
  15113. auto served_dir = std::string("./symlink_test_served");
  15114. auto secret_file = secret_dir + "/secret.txt";
  15115. auto symlink_path = served_dir + "/escape";
  15116. // Setup: create directories and files
  15117. mkdir(secret_dir.c_str(), 0755);
  15118. mkdir(served_dir.c_str(), 0755);
  15119. {
  15120. std::ofstream ofs(secret_file);
  15121. ofs << "SECRET_DATA";
  15122. }
  15123. // Create symlink using absolute path so it resolves correctly
  15124. #ifdef PATH_MAX
  15125. char abs_secret[PATH_MAX];
  15126. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15127. #else
  15128. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15129. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15130. ASSERT_NE(nullptr, abs_secret);
  15131. #endif
  15132. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15133. auto se = detail::scope_exit([&] {
  15134. unlink(symlink_path.c_str());
  15135. unlink(secret_file.c_str());
  15136. rmdir(served_dir.c_str());
  15137. rmdir(secret_dir.c_str());
  15138. });
  15139. Server svr;
  15140. svr.set_mount_point("/", served_dir);
  15141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15142. auto se2 = detail::scope_exit([&] {
  15143. svr.stop();
  15144. listen_thread.join();
  15145. });
  15146. svr.wait_until_ready();
  15147. Client cli("localhost", PORT);
  15148. // Symlink pointing outside base dir should be blocked
  15149. auto res = cli.Get("/escape/secret.txt");
  15150. ASSERT_TRUE(res);
  15151. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15152. }
  15153. #endif
  15154. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15155. // A GET request with Content-Length to a static file handler must have its
  15156. // body drained before the keep-alive connection is reused. Otherwise the
  15157. // unread body bytes are interpreted as the next HTTP request.
  15158. //
  15159. // The body is sent AFTER receiving the first response (as in the original
  15160. // PoC) so that the stream_line_reader cannot buffer it together with the
  15161. // headers of the first request.
  15162. Server svr;
  15163. svr.set_mount_point("/", "./www");
  15164. std::atomic<int> smuggled_count(0);
  15165. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15166. smuggled_count++;
  15167. res.set_content("oops", "text/plain");
  15168. });
  15169. auto port = svr.bind_to_any_port("localhost");
  15170. thread t = thread([&] { svr.listen_after_bind(); });
  15171. auto se = detail::scope_exit([&] {
  15172. svr.stop();
  15173. t.join();
  15174. });
  15175. svr.wait_until_ready();
  15176. auto error = Error::Success;
  15177. auto sock = detail::create_client_socket(
  15178. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15179. /*connection_timeout_sec=*/2, 0,
  15180. /*read_timeout_sec=*/2, 0,
  15181. /*write_timeout_sec=*/2, 0, std::string(), error);
  15182. ASSERT_NE(INVALID_SOCKET, sock);
  15183. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15184. // The "smuggled" request will be sent as the body of the outer GET
  15185. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15186. "Host: localhost\r\n"
  15187. "Connection: close\r\n"
  15188. "\r\n";
  15189. // Step 1: Send only the outer request headers (no body yet)
  15190. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15191. "Host: localhost\r\n"
  15192. "Content-Length: " +
  15193. std::to_string(smuggled.size()) +
  15194. "\r\n"
  15195. "\r\n";
  15196. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15197. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15198. // Step 2: Read the first response (server serves file without reading body)
  15199. std::string first_response;
  15200. char buf[4096];
  15201. for (;;) {
  15202. auto n = recv(sock, buf, sizeof(buf), 0);
  15203. if (n <= 0) break;
  15204. first_response.append(buf, static_cast<size_t>(n));
  15205. // Stop once we have a complete response (headers + body)
  15206. auto hdr_end = first_response.find("\r\n\r\n");
  15207. if (hdr_end != std::string::npos) {
  15208. // Check for Content-Length to know when the body is complete
  15209. auto cl_pos = first_response.find("Content-Length:");
  15210. if (cl_pos != std::string::npos) {
  15211. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15212. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15213. auto cl = std::stoul(
  15214. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15215. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15216. } else {
  15217. break; // No Content-Length, assume headers-only response
  15218. }
  15219. }
  15220. }
  15221. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15222. // Step 3: Now send the body, which looks like a new HTTP request.
  15223. // On a vulnerable server the keep-alive loop reads this as a second request.
  15224. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15225. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15226. // Step 4: Try to read a second response (should NOT exist after fix)
  15227. std::string second_response;
  15228. for (;;) {
  15229. auto n = recv(sock, buf, sizeof(buf), 0);
  15230. if (n <= 0) break;
  15231. second_response.append(buf, static_cast<size_t>(n));
  15232. }
  15233. // The smuggled request must NOT have been processed
  15234. EXPECT_EQ(0, smuggled_count.load());
  15235. }
  15236. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15237. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15238. // must be rejected with 400 Bad Request.
  15239. Server svr;
  15240. svr.Post("/test", [&](const Request &, Response &res) {
  15241. res.set_content("ok", "text/plain");
  15242. });
  15243. thread t = thread([&] { svr.listen(HOST, PORT); });
  15244. auto se = detail::scope_exit([&] {
  15245. svr.stop();
  15246. t.join();
  15247. ASSERT_FALSE(svr.is_running());
  15248. });
  15249. svr.wait_until_ready();
  15250. // Exact "chunked"
  15251. {
  15252. auto req = "POST /test HTTP/1.1\r\n"
  15253. "Host: localhost\r\n"
  15254. "Content-Length: 5\r\n"
  15255. "Transfer-Encoding: chunked\r\n"
  15256. "Connection: close\r\n"
  15257. "\r\n"
  15258. "hello";
  15259. std::string response;
  15260. ASSERT_TRUE(send_request(1, req, &response));
  15261. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15262. response.substr(0, response.find("\r\n")));
  15263. }
  15264. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15265. {
  15266. auto req = "POST /test HTTP/1.1\r\n"
  15267. "Host: localhost\r\n"
  15268. "Content-Length: 5\r\n"
  15269. "Transfer-Encoding: gzip, chunked\r\n"
  15270. "Connection: close\r\n"
  15271. "\r\n"
  15272. "hello";
  15273. std::string response;
  15274. ASSERT_TRUE(send_request(1, req, &response));
  15275. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15276. response.substr(0, response.find("\r\n")));
  15277. }
  15278. }
  15279. // Regression for issue #2450: a DELETE without Content-Length on a
  15280. // keep-alive connection must not let the post-response drain consume the
  15281. // next request's bytes.
  15282. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15283. Server svr;
  15284. std::atomic<int> delete_count(0);
  15285. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15286. delete_count++;
  15287. res.status = StatusCode::NoContent_204;
  15288. });
  15289. auto port = svr.bind_to_any_port(HOST);
  15290. thread t = thread([&] { svr.listen_after_bind(); });
  15291. auto se = detail::scope_exit([&] {
  15292. svr.stop();
  15293. t.join();
  15294. });
  15295. svr.wait_until_ready();
  15296. auto error = Error::Success;
  15297. auto sock = detail::create_client_socket(
  15298. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15299. /*connection_timeout_sec=*/2, 0,
  15300. /*read_timeout_sec=*/2, 0,
  15301. /*write_timeout_sec=*/2, 0, std::string(), error);
  15302. ASSERT_NE(INVALID_SOCKET, sock);
  15303. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15304. auto send_request_and_read_response = [&](const std::string &req,
  15305. std::string &out) -> bool {
  15306. auto sent = send(sock, req.data(), req.size(), 0);
  15307. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15308. char buf[4096];
  15309. for (;;) {
  15310. auto n = recv(sock, buf, sizeof(buf), 0);
  15311. if (n <= 0) { return !out.empty(); }
  15312. out.append(buf, static_cast<size_t>(n));
  15313. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15314. }
  15315. };
  15316. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15317. "Host: localhost\r\n"
  15318. "\r\n";
  15319. std::string resp1;
  15320. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15321. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15322. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15323. "Host: localhost\r\n"
  15324. "Connection: close\r\n"
  15325. "\r\n";
  15326. std::string resp2;
  15327. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15328. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15329. EXPECT_EQ(2, delete_count.load());
  15330. }
  15331. namespace no_proxy_test {
  15332. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15333. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15334. // calling listen().
  15335. class ScopedServer {
  15336. public:
  15337. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15338. ~ScopedServer() {
  15339. svr_.stop();
  15340. if (th_.joinable()) { th_.join(); }
  15341. }
  15342. Server &svr() { return svr_; }
  15343. int port() const { return port_; }
  15344. void listen() {
  15345. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15346. svr_.wait_until_ready();
  15347. }
  15348. private:
  15349. Server svr_;
  15350. std::thread th_;
  15351. int port_ = 0;
  15352. };
  15353. class ProxyAndTargetServers {
  15354. public:
  15355. ProxyAndTargetServers() {
  15356. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15357. proxy_hits_++;
  15358. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15359. res.set_content("via-proxy", "text/plain");
  15360. });
  15361. target_.Get(".*", [this](const Request &req, Response &res) {
  15362. target_hits_++;
  15363. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15364. res.set_content("direct", "text/plain");
  15365. });
  15366. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15367. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15368. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15369. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15370. proxy_mock_.wait_until_ready();
  15371. target_.wait_until_ready();
  15372. }
  15373. ~ProxyAndTargetServers() {
  15374. proxy_mock_.stop();
  15375. target_.stop();
  15376. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15377. if (target_thread_.joinable()) { target_thread_.join(); }
  15378. }
  15379. Server &proxy_mock() { return proxy_mock_; }
  15380. Server &target() { return target_; }
  15381. int proxy_port() const { return proxy_port_; }
  15382. int target_port() const { return target_port_; }
  15383. int proxy_hits() const { return proxy_hits_.load(); }
  15384. int target_hits() const { return target_hits_.load(); }
  15385. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15386. void reset_counters() {
  15387. proxy_hits_ = 0;
  15388. target_hits_ = 0;
  15389. last_had_proxy_authz_ = false;
  15390. }
  15391. private:
  15392. Server proxy_mock_;
  15393. Server target_;
  15394. std::thread proxy_thread_;
  15395. std::thread target_thread_;
  15396. int proxy_port_ = 0;
  15397. int target_port_ = 0;
  15398. std::atomic<int> proxy_hits_{0};
  15399. std::atomic<int> target_hits_{0};
  15400. std::atomic<bool> last_had_proxy_authz_{false};
  15401. };
  15402. inline std::unique_ptr<Client> make_client(const std::string &host,
  15403. ProxyAndTargetServers &s) {
  15404. auto cli = detail::make_unique<Client>(host, s.target_port());
  15405. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15406. cli->set_proxy("127.0.0.1", s.proxy_port());
  15407. return cli;
  15408. }
  15409. } // namespace no_proxy_test
  15410. using no_proxy_test::make_client;
  15411. using no_proxy_test::ProxyAndTargetServers;
  15412. TEST(NoProxyTest, ExactHostnameBypasses) {
  15413. ProxyAndTargetServers s;
  15414. auto cli = make_client("example.com", s);
  15415. cli->set_no_proxy({"example.com"});
  15416. auto res = cli->Get("/");
  15417. ASSERT_TRUE(res);
  15418. EXPECT_EQ(0, s.proxy_hits());
  15419. EXPECT_EQ(1, s.target_hits());
  15420. }
  15421. TEST(NoProxyTest, SubdomainBypasses) {
  15422. ProxyAndTargetServers s;
  15423. auto cli = make_client("foo.example.com", s);
  15424. cli->set_no_proxy({"example.com"});
  15425. auto res = cli->Get("/");
  15426. ASSERT_TRUE(res);
  15427. EXPECT_EQ(0, s.proxy_hits());
  15428. EXPECT_EQ(1, s.target_hits());
  15429. }
  15430. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15431. // Regression guard: "evilexample.com" must not be considered a subdomain
  15432. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15433. // check would let traffic bypass the proxy and leak credentials direct
  15434. // to the attacker host.
  15435. ProxyAndTargetServers s;
  15436. auto cli = make_client("evilexample.com", s);
  15437. cli->set_no_proxy({"example.com"});
  15438. auto res = cli->Get("/");
  15439. ASSERT_TRUE(res);
  15440. EXPECT_GE(s.proxy_hits(), 1);
  15441. EXPECT_EQ(0, s.target_hits());
  15442. }
  15443. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15444. ProxyAndTargetServers s;
  15445. auto cli = make_client("example.com.evil.com", s);
  15446. cli->set_no_proxy({"example.com"});
  15447. auto res = cli->Get("/");
  15448. ASSERT_TRUE(res);
  15449. EXPECT_GE(s.proxy_hits(), 1);
  15450. EXPECT_EQ(0, s.target_hits());
  15451. }
  15452. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15453. ProxyAndTargetServers s;
  15454. auto cli = make_client("example.com", s);
  15455. cli->set_no_proxy({".example.com"});
  15456. auto res = cli->Get("/");
  15457. ASSERT_TRUE(res);
  15458. EXPECT_EQ(0, s.proxy_hits());
  15459. EXPECT_EQ(1, s.target_hits());
  15460. }
  15461. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15462. ProxyAndTargetServers s;
  15463. auto cli = make_client("Example.COM", s);
  15464. cli->set_no_proxy({"EXAMPLE.com"});
  15465. auto res = cli->Get("/");
  15466. ASSERT_TRUE(res);
  15467. EXPECT_EQ(0, s.proxy_hits());
  15468. EXPECT_EQ(1, s.target_hits());
  15469. }
  15470. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15471. ProxyAndTargetServers s;
  15472. auto cli = make_client("example.com.", s);
  15473. cli->set_no_proxy({"example.com"});
  15474. auto res = cli->Get("/");
  15475. ASSERT_TRUE(res);
  15476. EXPECT_EQ(0, s.proxy_hits());
  15477. EXPECT_EQ(1, s.target_hits());
  15478. }
  15479. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15480. // Trailing dots must be normalized on BOTH sides — host and entry.
  15481. // An implementation that only strips the host-side trailing dot would
  15482. // fail to match host "example.com" against entry "example.com." because
  15483. // a literal substring search would compare 11 chars against 12.
  15484. ProxyAndTargetServers s;
  15485. auto cli = make_client("example.com", s);
  15486. cli->set_no_proxy({"example.com."});
  15487. auto res = cli->Get("/");
  15488. ASSERT_TRUE(res);
  15489. EXPECT_EQ(0, s.proxy_hits());
  15490. EXPECT_EQ(1, s.target_hits());
  15491. }
  15492. TEST(NoProxyTest, WildcardBypassesEverything) {
  15493. ProxyAndTargetServers s;
  15494. auto cli = make_client("anything.invalid.test", s);
  15495. cli->set_no_proxy({"*"});
  15496. auto res = cli->Get("/");
  15497. ASSERT_TRUE(res);
  15498. EXPECT_EQ(0, s.proxy_hits());
  15499. EXPECT_EQ(1, s.target_hits());
  15500. }
  15501. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15502. ProxyAndTargetServers s;
  15503. Client cli("127.0.0.1", s.target_port());
  15504. cli.set_proxy("127.0.0.1", s.proxy_port());
  15505. cli.set_no_proxy({"127.0.0.1"});
  15506. auto res = cli.Get("/");
  15507. ASSERT_TRUE(res);
  15508. EXPECT_EQ(0, s.proxy_hits());
  15509. EXPECT_EQ(1, s.target_hits());
  15510. }
  15511. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  15512. ProxyAndTargetServers s;
  15513. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  15514. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  15515. cli.set_proxy("127.0.0.1", s.proxy_port());
  15516. cli.set_no_proxy({"::1"});
  15517. auto res = cli.Get("/");
  15518. ASSERT_TRUE(res);
  15519. EXPECT_EQ(0, s.proxy_hits());
  15520. EXPECT_EQ(1, s.target_hits());
  15521. }
  15522. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  15523. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  15524. // must still be recognized as IPv6 for CIDR matching. Implementations
  15525. // that detect IPv6 only when the host begins with '[' would parse the
  15526. // host as a hostname and miss the match.
  15527. ProxyAndTargetServers s;
  15528. Client cli("fe80::1", s.target_port());
  15529. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15530. cli.set_proxy("127.0.0.1", s.proxy_port());
  15531. cli.set_no_proxy({"fe80::/10"});
  15532. auto res = cli.Get("/");
  15533. ASSERT_TRUE(res);
  15534. EXPECT_EQ(0, s.proxy_hits());
  15535. EXPECT_EQ(1, s.target_hits());
  15536. }
  15537. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  15538. ProxyAndTargetServers s;
  15539. Client cli("::1", s.target_port());
  15540. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  15541. cli.set_proxy("127.0.0.1", s.proxy_port());
  15542. cli.set_no_proxy({"[::1]"});
  15543. auto res = cli.Get("/");
  15544. ASSERT_TRUE(res);
  15545. EXPECT_EQ(0, s.proxy_hits());
  15546. EXPECT_EQ(1, s.target_hits());
  15547. }
  15548. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  15549. ProxyAndTargetServers s;
  15550. Client cli("fe80::1", s.target_port());
  15551. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15552. cli.set_proxy("127.0.0.1", s.proxy_port());
  15553. cli.set_no_proxy({"[fe80::]/10"});
  15554. auto res = cli.Get("/");
  15555. ASSERT_TRUE(res);
  15556. EXPECT_EQ(0, s.proxy_hits());
  15557. EXPECT_EQ(1, s.target_hits());
  15558. }
  15559. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  15560. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  15561. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  15562. // tricks via address-family conversion.
  15563. ProxyAndTargetServers s;
  15564. Client cli("::ffff:127.0.0.1", s.target_port());
  15565. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  15566. cli.set_proxy("127.0.0.1", s.proxy_port());
  15567. cli.set_no_proxy({"127.0.0.1"});
  15568. auto res = cli.Get("/");
  15569. ASSERT_TRUE(res);
  15570. EXPECT_GE(s.proxy_hits(), 1);
  15571. EXPECT_EQ(0, s.target_hits());
  15572. }
  15573. TEST(NoProxyTest, IPv4CidrMatch) {
  15574. ProxyAndTargetServers s;
  15575. Client cli("127.0.0.1", s.target_port());
  15576. cli.set_proxy("127.0.0.1", s.proxy_port());
  15577. cli.set_no_proxy({"127.0.0.0/8"});
  15578. auto res = cli.Get("/");
  15579. ASSERT_TRUE(res);
  15580. EXPECT_EQ(0, s.proxy_hits());
  15581. EXPECT_EQ(1, s.target_hits());
  15582. }
  15583. TEST(NoProxyTest, IPv4CidrNonMatch) {
  15584. ProxyAndTargetServers s;
  15585. Client cli("127.0.0.1", s.target_port());
  15586. cli.set_proxy("127.0.0.1", s.proxy_port());
  15587. cli.set_no_proxy({"10.0.0.0/8"});
  15588. auto res = cli.Get("/");
  15589. ASSERT_TRUE(res);
  15590. EXPECT_GE(s.proxy_hits(), 1);
  15591. EXPECT_EQ(0, s.target_hits());
  15592. }
  15593. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  15594. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  15595. // IPv4 target matches.
  15596. ProxyAndTargetServers s;
  15597. Client cli("127.0.0.1", s.target_port());
  15598. cli.set_proxy("127.0.0.1", s.proxy_port());
  15599. cli.set_no_proxy({"0.0.0.0/0"});
  15600. auto res = cli.Get("/");
  15601. ASSERT_TRUE(res);
  15602. EXPECT_EQ(0, s.proxy_hits());
  15603. EXPECT_EQ(1, s.target_hits());
  15604. }
  15605. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  15606. ProxyAndTargetServers s;
  15607. Client cli("127.0.0.1", s.target_port());
  15608. cli.set_proxy("127.0.0.1", s.proxy_port());
  15609. cli.set_no_proxy({"127.0.0.1"});
  15610. auto res = cli.Get("/");
  15611. ASSERT_TRUE(res);
  15612. EXPECT_EQ(0, s.proxy_hits());
  15613. EXPECT_EQ(1, s.target_hits());
  15614. }
  15615. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  15616. ProxyAndTargetServers s;
  15617. Client cli("127.0.0.1", s.target_port());
  15618. cli.set_proxy("127.0.0.1", s.proxy_port());
  15619. cli.set_no_proxy({"127.0.0.0/33"});
  15620. auto res = cli.Get("/");
  15621. ASSERT_TRUE(res);
  15622. EXPECT_GE(s.proxy_hits(), 1);
  15623. EXPECT_EQ(0, s.target_hits());
  15624. }
  15625. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  15626. // Empty prefix after the slash must be rejected, not silently treated as /32.
  15627. ProxyAndTargetServers s;
  15628. Client cli("127.0.0.1", s.target_port());
  15629. cli.set_proxy("127.0.0.1", s.proxy_port());
  15630. cli.set_no_proxy({"127.0.0.1/"});
  15631. auto res = cli.Get("/");
  15632. ASSERT_TRUE(res);
  15633. EXPECT_GE(s.proxy_hits(), 1);
  15634. EXPECT_EQ(0, s.target_hits());
  15635. }
  15636. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  15637. ProxyAndTargetServers s;
  15638. auto cli = make_client("internal.corp", s);
  15639. cli->set_proxy_basic_auth("u", "p");
  15640. cli->set_no_proxy({"internal.corp"});
  15641. auto res = cli->Get("/");
  15642. ASSERT_TRUE(res);
  15643. EXPECT_EQ(1, s.target_hits());
  15644. EXPECT_EQ(0, s.proxy_hits());
  15645. EXPECT_FALSE(s.last_had_proxy_authz())
  15646. << "Proxy-Authorization must not be sent direct to the target";
  15647. }
  15648. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  15649. ProxyAndTargetServers s;
  15650. auto cli = make_client("public.example", s);
  15651. cli->set_proxy_basic_auth("u", "p");
  15652. cli->set_no_proxy({"internal.corp"}); // does not match
  15653. auto res = cli->Get("/");
  15654. ASSERT_TRUE(res);
  15655. EXPECT_GE(s.proxy_hits(), 1);
  15656. EXPECT_TRUE(s.last_had_proxy_authz());
  15657. }
  15658. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  15659. ProxyAndTargetServers s;
  15660. auto cli = make_client("anything.test", s);
  15661. auto res = cli->Get("/");
  15662. ASSERT_TRUE(res);
  15663. EXPECT_GE(s.proxy_hits(), 1);
  15664. EXPECT_EQ(0, s.target_hits());
  15665. }
  15666. TEST(NoProxyTest, PortSpecificEntryRejected) {
  15667. ProxyAndTargetServers s;
  15668. auto cli = make_client("example.com", s);
  15669. cli->set_no_proxy({"example.com:8080"});
  15670. auto res = cli->Get("/");
  15671. ASSERT_TRUE(res);
  15672. EXPECT_GE(s.proxy_hits(), 1);
  15673. EXPECT_EQ(0, s.target_hits());
  15674. }
  15675. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  15676. ProxyAndTargetServers s;
  15677. auto cli = make_client("anything.test", s);
  15678. cli->set_no_proxy({"", " ", "\t"});
  15679. auto res = cli->Get("/");
  15680. ASSERT_TRUE(res);
  15681. EXPECT_GE(s.proxy_hits(), 1);
  15682. EXPECT_EQ(0, s.target_hits());
  15683. }
  15684. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  15685. // An entry with leading/trailing whitespace must still match — env-style
  15686. // values are commonly pasted with stray spaces and an implementation
  15687. // that feeds the raw token directly to inet_pton would fail to match
  15688. // valid CIDRs because of the spaces.
  15689. ProxyAndTargetServers s;
  15690. Client cli("127.0.0.1", s.target_port());
  15691. cli.set_proxy("127.0.0.1", s.proxy_port());
  15692. cli.set_no_proxy({" 127.0.0.0/8 "});
  15693. auto res = cli.Get("/");
  15694. ASSERT_TRUE(res);
  15695. EXPECT_EQ(0, s.proxy_hits());
  15696. EXPECT_EQ(1, s.target_hits());
  15697. }
  15698. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  15699. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  15700. // go direct and must NOT carry Proxy-Authorization.
  15701. std::atomic<int> proxy_hits{0};
  15702. std::atomic<int> target_hits{0};
  15703. std::atomic<bool> target_saw_authz{false};
  15704. no_proxy_test::ScopedServer proxy_mock, target;
  15705. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15706. proxy_hits++;
  15707. res.status = 302;
  15708. res.set_header("Location", "http://127.0.0.1:" +
  15709. std::to_string(target.port()) + "/landed");
  15710. });
  15711. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15712. target_hits++;
  15713. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  15714. res.set_content("direct", "text/plain");
  15715. });
  15716. proxy_mock.listen();
  15717. target.listen();
  15718. Client cli("public.example", target.port());
  15719. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15720. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15721. cli.set_proxy_basic_auth("u", "p");
  15722. cli.set_no_proxy({"127.0.0.1"});
  15723. cli.set_follow_location(true);
  15724. auto res = cli.Get("/redir");
  15725. ASSERT_TRUE(res);
  15726. EXPECT_GE(proxy_hits.load(), 1);
  15727. EXPECT_GE(target_hits.load(), 1);
  15728. EXPECT_FALSE(target_saw_authz.load());
  15729. }
  15730. #ifdef CPPHTTPLIB_SSL_ENABLED
  15731. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  15732. // Direct origin replying 407 must not trigger the digest retry; otherwise
  15733. // proxy creds would be sent to the (possibly hostile) origin.
  15734. std::atomic<int> target_hits{0};
  15735. std::atomic<bool> target_saw_proxy_authz{false};
  15736. no_proxy_test::ScopedServer target;
  15737. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15738. target_hits++;
  15739. if (req.has_header("Proxy-Authorization")) {
  15740. target_saw_proxy_authz = true;
  15741. }
  15742. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15743. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  15744. "nonce=\"abc\", algorithm=MD5");
  15745. });
  15746. target.listen();
  15747. // The proxy address is set to the target's port: the bypass MUST kick in;
  15748. // if it doesn't, the test still routes "via proxy" to the same server and
  15749. // the Proxy-Authorization assertion below catches the leak.
  15750. Client cli("evil.example", target.port());
  15751. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  15752. cli.set_proxy("127.0.0.1", target.port());
  15753. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15754. cli.set_no_proxy({"evil.example"});
  15755. auto res = cli.Get("/x");
  15756. ASSERT_TRUE(res);
  15757. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15758. EXPECT_EQ(1, target_hits.load());
  15759. EXPECT_FALSE(target_saw_proxy_authz.load());
  15760. }
  15761. #endif
  15762. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  15763. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  15764. std::atomic<int> proxy_hits{0};
  15765. std::atomic<int> bypass_hits{0};
  15766. std::atomic<bool> proxy_saw_c_url{false};
  15767. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  15768. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  15769. proxy_hits++;
  15770. if (req.path.find("/start") != std::string::npos) {
  15771. res.status = 302;
  15772. res.set_header("Location", "http://127.0.0.1:" +
  15773. std::to_string(bypass_server.port()) +
  15774. "/middle");
  15775. return;
  15776. }
  15777. if (req.path.find("/end") != std::string::npos) {
  15778. proxy_saw_c_url = true;
  15779. res.set_content("c-via-proxy", "text/plain");
  15780. return;
  15781. }
  15782. res.set_content("unexpected", "text/plain");
  15783. });
  15784. // public.example's "advertised" port is arbitrary (the request never lands
  15785. // there — it goes through the proxy), but use a dynamic value to stay
  15786. // friendly with sharded parallel runs.
  15787. int public_port = bypass_server.port();
  15788. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  15789. bypass_hits++;
  15790. res.status = 302;
  15791. res.set_header("Location", "http://public.example:" +
  15792. std::to_string(public_port) + "/end");
  15793. });
  15794. proxy_mock.listen();
  15795. bypass_server.listen();
  15796. Client cli("public.example", public_port);
  15797. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15798. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15799. cli.set_no_proxy({"127.0.0.1"});
  15800. cli.set_follow_location(true);
  15801. auto res = cli.Get("/start");
  15802. ASSERT_TRUE(res);
  15803. EXPECT_EQ(StatusCode::OK_200, res->status);
  15804. EXPECT_EQ("c-via-proxy", res->body);
  15805. EXPECT_GE(proxy_hits.load(), 2);
  15806. EXPECT_GE(bypass_hits.load(), 1);
  15807. EXPECT_TRUE(proxy_saw_c_url.load());
  15808. }
  15809. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  15810. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  15811. // request reconnects to the correct endpoint.
  15812. std::atomic<int> proxy_hits{0};
  15813. std::atomic<int> target_hits{0};
  15814. no_proxy_test::ScopedServer proxy_mock, target;
  15815. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15816. proxy_hits++;
  15817. res.set_content("via-proxy", "text/plain");
  15818. });
  15819. target.svr().Get(".*", [&](const Request &, Response &res) {
  15820. target_hits++;
  15821. res.set_content("direct", "text/plain");
  15822. });
  15823. proxy_mock.listen();
  15824. target.listen();
  15825. Client cli("public.example", target.port());
  15826. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15827. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15828. cli.set_keep_alive(true);
  15829. auto res1 = cli.Get("/a");
  15830. ASSERT_TRUE(res1);
  15831. EXPECT_EQ("via-proxy", res1->body);
  15832. EXPECT_EQ(1, proxy_hits.load());
  15833. EXPECT_EQ(0, target_hits.load());
  15834. cli.set_no_proxy({"public.example"});
  15835. auto res2 = cli.Get("/b");
  15836. ASSERT_TRUE(res2);
  15837. EXPECT_EQ("direct", res2->body);
  15838. EXPECT_EQ(1, proxy_hits.load());
  15839. EXPECT_EQ(1, target_hits.load());
  15840. }
  15841. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  15842. namespace proxy_tunnel_test {
  15843. // SSLServer counterpart to no_proxy_test::ScopedServer.
  15844. class ScopedSSLServer {
  15845. public:
  15846. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  15847. port_ = svr_.bind_to_any_port("127.0.0.1");
  15848. }
  15849. ~ScopedSSLServer() {
  15850. svr_.stop();
  15851. if (th_.joinable()) { th_.join(); }
  15852. }
  15853. SSLServer &svr() { return svr_; }
  15854. int port() const { return port_; }
  15855. void listen() {
  15856. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15857. svr_.wait_until_ready();
  15858. }
  15859. private:
  15860. SSLServer svr_;
  15861. std::thread th_;
  15862. int port_ = 0;
  15863. };
  15864. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  15865. class ScopedConnectProxy {
  15866. public:
  15867. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  15868. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  15869. if (listen_fd_ < 0) { return; }
  15870. int yes = 1;
  15871. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  15872. sockaddr_in a{};
  15873. a.sin_family = AF_INET;
  15874. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  15875. a.sin_port = 0;
  15876. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  15877. return;
  15878. }
  15879. socklen_t alen = sizeof(a);
  15880. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  15881. 0) {
  15882. return;
  15883. }
  15884. port_ = ntohs(a.sin_port);
  15885. if (::listen(listen_fd_, 1) != 0) { return; }
  15886. th_ = std::thread([this] { run(); });
  15887. }
  15888. ~ScopedConnectProxy() {
  15889. stop_ = true;
  15890. if (listen_fd_ >= 0) {
  15891. ::shutdown(listen_fd_, SHUT_RDWR);
  15892. ::close(listen_fd_);
  15893. }
  15894. if (th_.joinable()) { th_.join(); }
  15895. }
  15896. int port() const { return port_; }
  15897. int connect_hits() const { return connect_hits_.load(); }
  15898. private:
  15899. void run() {
  15900. while (!stop_.load()) {
  15901. fd_set rfds;
  15902. FD_ZERO(&rfds);
  15903. FD_SET(listen_fd_, &rfds);
  15904. timeval tv{0, 100 * 1000};
  15905. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  15906. if (sel <= 0) { continue; }
  15907. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  15908. if (client_fd < 0) { continue; }
  15909. std::string req;
  15910. char buf[2048];
  15911. while (req.find("\r\n\r\n") == std::string::npos) {
  15912. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  15913. if (n <= 0) { break; }
  15914. req.append(buf, static_cast<size_t>(n));
  15915. }
  15916. if (req.compare(0, 7, "CONNECT") != 0) {
  15917. ::close(client_fd);
  15918. continue;
  15919. }
  15920. connect_hits_++;
  15921. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  15922. ::send(client_fd, ok, std::strlen(ok), 0);
  15923. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  15924. sockaddr_in o{};
  15925. o.sin_family = AF_INET;
  15926. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  15927. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  15928. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  15929. 0) {
  15930. ::close(client_fd);
  15931. ::close(origin_fd);
  15932. continue;
  15933. }
  15934. auto forward = [](int from, int to) {
  15935. char b[8192];
  15936. for (;;) {
  15937. ssize_t n = ::recv(from, b, sizeof(b), 0);
  15938. if (n <= 0) { break; }
  15939. ssize_t off = 0;
  15940. while (off < n) {
  15941. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  15942. if (s <= 0) {
  15943. off = n;
  15944. break;
  15945. }
  15946. off += s;
  15947. }
  15948. }
  15949. ::shutdown(to, SHUT_WR);
  15950. };
  15951. std::thread t1([&] { forward(client_fd, origin_fd); });
  15952. std::thread t2([&] { forward(origin_fd, client_fd); });
  15953. t1.join();
  15954. t2.join();
  15955. ::close(client_fd);
  15956. ::close(origin_fd);
  15957. }
  15958. }
  15959. int forward_port_ = -1;
  15960. int listen_fd_ = -1;
  15961. int port_ = 0;
  15962. std::thread th_;
  15963. std::atomic<bool> stop_{false};
  15964. std::atomic<int> connect_hits_{0};
  15965. };
  15966. } // namespace proxy_tunnel_test
  15967. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  15968. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  15969. // retry; otherwise proxy creds would be sent to the origin.
  15970. std::atomic<int> origin_hits{0};
  15971. std::atomic<bool> origin_saw_proxy_authz{false};
  15972. proxy_tunnel_test::ScopedSSLServer origin;
  15973. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  15974. origin_hits++;
  15975. if (req.has_header("Proxy-Authorization")) {
  15976. origin_saw_proxy_authz = true;
  15977. }
  15978. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15979. res.set_header("Proxy-Authenticate",
  15980. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  15981. "algorithm=MD5");
  15982. });
  15983. origin.listen();
  15984. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  15985. ASSERT_NE(0, proxy.port());
  15986. SSLClient cli(HOST, origin.port());
  15987. cli.enable_server_certificate_verification(false);
  15988. cli.set_proxy(HOST, proxy.port());
  15989. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15990. auto res = cli.Get("/x");
  15991. ASSERT_TRUE(res);
  15992. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15993. EXPECT_EQ(1, origin_hits.load());
  15994. EXPECT_FALSE(origin_saw_proxy_authz.load());
  15995. EXPECT_EQ(1, proxy.connect_hits());
  15996. }
  15997. #endif