test.cc 637 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration (see the base64_encode note below): split builds move the
  361. // definition into httplib.cc, so re-declaring it here lets the test link.
  362. namespace httplib {
  363. namespace detail {
  364. bool is_chunked_transfer_encoding(const Headers &headers);
  365. } // namespace detail
  366. } // namespace httplib
  367. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  368. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  369. auto make = [](std::initializer_list<const char *> lines) {
  370. Headers h;
  371. for (auto te : lines) {
  372. if (te) { h.emplace("Transfer-Encoding", te); }
  373. }
  374. return h;
  375. };
  376. // Sole coding, matched case-insensitively.
  377. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  378. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  379. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  380. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  381. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  382. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  384. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  385. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  386. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  387. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  388. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  389. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  390. // portable, so any line naming chunked is treated as chunked (fail safe).
  391. // The result must not depend on the order the lines were added.
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  395. }
  396. // Forward declaration: in split builds split.py strips `inline` and moves the
  397. // definition into httplib.cc, so detail::base64_encode is not visible from the
  398. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  399. // in both header-only and split builds.
  400. namespace httplib {
  401. namespace detail {
  402. std::string base64_encode(const std::string &in);
  403. } // namespace detail
  404. } // namespace httplib
  405. TEST(Base64EncodeTest, KnownAnswers) {
  406. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  407. // where the accumulator's top bit is already set before the next shift.
  408. EXPECT_EQ("", detail::base64_encode(""));
  409. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  410. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  411. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  412. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  413. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  414. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  415. // High bytes keep the top bit set across several rounds.
  416. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  417. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  418. }
  419. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  420. string unescapedCharacters = "-_.!~*'()";
  421. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  422. }
  423. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  424. string reservedCharacters = ";,/?:@&=+$";
  425. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  426. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  427. }
  428. TEST(ClientQueryOrder, PreserveOrder) {
  429. // This test reproduces Issue #2259: client may reorder query parameters
  430. // when sending a GET request. The expected behavior is that the client
  431. // preserves the original query string order when the caller supplied it
  432. // as part of the path.
  433. Server svr;
  434. svr.Get("/", [&](const Request &req, Response &res) {
  435. // Echo back the raw target so the test can assert ordering
  436. res.set_content(req.target, "text/plain");
  437. });
  438. std::thread t{[&] { svr.listen(HOST, PORT); }};
  439. auto se = detail::scope_exit([&] {
  440. svr.stop();
  441. t.join();
  442. ASSERT_FALSE(svr.is_running());
  443. });
  444. svr.wait_until_ready();
  445. Client cli(HOST, PORT);
  446. ASSERT_TRUE(cli.is_valid());
  447. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  448. auto res = cli.Get(original);
  449. ASSERT_TRUE(res);
  450. // Expect the echoed target to exactly match the original path (order
  451. // preserved)
  452. EXPECT_EQ(res->body, original);
  453. }
  454. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  455. string chineseCharacters = U8("中国語");
  456. string russianCharacters = U8("дом");
  457. string brazilianCharacters = U8("óculos");
  458. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  459. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  460. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  461. "%D0%B4%D0%BE%D0%BC");
  462. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  463. }
  464. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  465. string unescapedCharacters = "-_.!~*'()";
  466. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  467. }
  468. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  469. string reservedCharacters = ";,/?:@&=+$";
  470. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  471. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  472. }
  473. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  474. string chineseCharacters = U8("中国語");
  475. string russianCharacters = U8("дом");
  476. string brazilianCharacters = U8("óculos");
  477. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  478. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  479. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  480. "%D0%B4%D0%BE%D0%BC");
  481. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  482. }
  483. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  484. // Issue #2082 use case: encoding path component with ampersand
  485. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  486. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  487. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  488. }
  489. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  490. string unescapedCharacters = "-_.!~*'()";
  491. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  492. }
  493. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  494. string reservedCharacters = ";,/?:@&=+$#";
  495. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  496. }
  497. TEST(EncodeUriTest, TestUTF8Characters) {
  498. string chineseCharacters = U8("中国語");
  499. string russianCharacters = U8("дом");
  500. string brazilianCharacters = U8("óculos");
  501. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  502. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  503. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriTest, TestCompleteUri) {
  507. string uri =
  508. "https://example.com/path/to/resource?query=value&param=test#fragment";
  509. EXPECT_EQ(
  510. httplib::encode_uri(uri),
  511. "https://example.com/path/to/resource?query=value&param=test#fragment");
  512. }
  513. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  514. string uri =
  515. "https://example.com/path with spaces/file name.html?q=hello world";
  516. EXPECT_EQ(httplib::encode_uri(uri),
  517. "https://example.com/path%20with%20spaces/"
  518. "file%20name.html?q=hello%20world");
  519. }
  520. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  521. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  522. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  523. }
  524. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  525. string unescapedCharacters = "-_.!~*'()";
  526. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  527. }
  528. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  529. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  530. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  531. string encodedBrazilian = "%C3%B3culos";
  532. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  533. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  534. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  535. }
  536. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  537. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  539. "Piri Tommy Villiers - on & on");
  540. }
  541. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  542. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  543. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  544. }
  545. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  546. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  547. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  548. }
  549. TEST(DecodeUriTest, TestUTF8Characters) {
  550. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  551. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  552. string encodedBrazilian = "%C3%B3culos";
  553. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  554. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  555. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  556. }
  557. TEST(DecodeUriTest, TestCompleteUri) {
  558. string encodedUri = "https://example.com/path%20with%20spaces/"
  559. "file%20name.html?q=hello%20world";
  560. EXPECT_EQ(
  561. httplib::decode_uri(encodedUri),
  562. "https://example.com/path with spaces/file name.html?q=hello world");
  563. }
  564. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  565. string original =
  566. "https://example.com/path with spaces/file name.html?q=hello world";
  567. string encoded = httplib::encode_uri(original);
  568. string decoded = httplib::decode_uri(encoded);
  569. EXPECT_EQ(decoded, original);
  570. }
  571. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  572. string original = "Piri Tommy Villiers - on & on";
  573. string encoded = httplib::encode_uri_component(original);
  574. string decoded = httplib::decode_uri_component(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(TrimTests, TrimStringTests) {
  578. EXPECT_EQ("abc", detail::trim_copy("abc"));
  579. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  580. EXPECT_TRUE(detail::trim_copy("").empty());
  581. }
  582. TEST(AsciiTest, LocaleIndependentClassification) {
  583. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  584. // which consult the global C locale: std::isalnum(0xC5) can return true
  585. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  586. // helpers must classify every byte by the ASCII grammar alone.
  587. for (int i = 0; i < 256; i++) {
  588. auto c = static_cast<char>(i);
  589. auto is_digit = i >= '0' && i <= '9';
  590. auto is_upper = i >= 'A' && i <= 'Z';
  591. auto is_lower = i >= 'a' && i <= 'z';
  592. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  593. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  594. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  595. << "byte " << i;
  596. }
  597. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  598. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  599. // Non-ASCII bytes must be percent-encoded, never passed through as
  600. // alphanumeric.
  601. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  602. }
  603. TEST(FromCharsTest, Double) {
  604. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  605. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  606. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  607. auto parse = [](const std::string &s, double &v) {
  608. return detail::from_chars(s.data(), s.data() + s.size(), v);
  609. };
  610. double v = -1.0;
  611. // Representative quality values.
  612. EXPECT_EQ(parse("0", v).ec, std::errc{});
  613. EXPECT_DOUBLE_EQ(v, 0.0);
  614. EXPECT_EQ(parse("1", v).ec, std::errc{});
  615. EXPECT_DOUBLE_EQ(v, 1.0);
  616. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  617. EXPECT_DOUBLE_EQ(v, 0.8);
  618. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.001);
  620. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. // A missing integer or fractional part is tolerated.
  623. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  624. EXPECT_DOUBLE_EQ(v, 0.5);
  625. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  626. EXPECT_DOUBLE_EQ(v, 5.0);
  627. // Values outside [0, 1] still parse; the caller range-checks them.
  628. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 123.456);
  630. // Stops at the first byte that is not part of the number and reports where.
  631. std::string trailing = "0.9, text/html";
  632. auto r = parse(trailing, v);
  633. EXPECT_EQ(r.ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.9);
  635. EXPECT_EQ(*r.ptr, ',');
  636. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  637. // outright, and an 'e'/'E' simply ends the number.
  638. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  639. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  640. std::string exp_input = "1.5e3";
  641. r = parse(exp_input, v);
  642. EXPECT_EQ(r.ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 1.5);
  644. EXPECT_EQ(*r.ptr, 'e');
  645. // Invalid inputs.
  646. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  648. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  649. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  650. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  651. // Pathological but well-formed inputs must stay bounded (no overflow, no
  652. // out-of-bounds table access) and stay within [0, 1] for the caller.
  653. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  654. std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.0);
  656. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  657. std::errc{});
  658. EXPECT_GE(v, 0.0);
  659. EXPECT_LE(v, 1.0);
  660. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  661. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  662. }
  663. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  664. // Simple case without quality values
  665. std::vector<std::string> result1;
  666. EXPECT_TRUE(detail::parse_accept_header(
  667. "text/html,application/json,text/plain", result1));
  668. EXPECT_EQ(result1.size(), 3U);
  669. EXPECT_EQ(result1[0], "text/html");
  670. EXPECT_EQ(result1[1], "application/json");
  671. EXPECT_EQ(result1[2], "text/plain");
  672. // With quality values
  673. std::vector<std::string> result2;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  676. EXPECT_EQ(result2.size(), 3U);
  677. EXPECT_EQ(result2[0], "application/json"); // highest q value
  678. EXPECT_EQ(result2[1], "text/html");
  679. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  680. }
  681. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  682. // Mixed with and without quality values
  683. std::vector<std::string> result;
  684. EXPECT_TRUE(detail::parse_accept_header(
  685. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  686. EXPECT_EQ(result.size(), 3U);
  687. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  688. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  689. EXPECT_EQ(result[2], "application/json"); // q=0.5
  690. }
  691. TEST(ParseAcceptHeaderTest, EdgeCases) {
  692. // Empty header
  693. std::vector<std::string> empty_result;
  694. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  695. EXPECT_TRUE(empty_result.empty());
  696. // Single type
  697. std::vector<std::string> single_result;
  698. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  699. EXPECT_EQ(single_result.size(), 1U);
  700. EXPECT_EQ(single_result[0], "application/json");
  701. // Wildcard types
  702. std::vector<std::string> wildcard_result;
  703. EXPECT_TRUE(detail::parse_accept_header(
  704. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  705. EXPECT_EQ(wildcard_result.size(), 3U);
  706. EXPECT_EQ(wildcard_result[0], "application/json");
  707. EXPECT_EQ(wildcard_result[1], "text/*");
  708. EXPECT_EQ(wildcard_result[2], "*/*");
  709. }
  710. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  711. // Common browser Accept header
  712. std::vector<std::string> browser_result;
  713. EXPECT_TRUE(
  714. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  715. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  716. browser_result));
  717. EXPECT_EQ(browser_result.size(), 6U);
  718. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  719. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  720. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  721. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  722. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  723. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  724. // API client header
  725. std::vector<std::string> api_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  728. api_result));
  729. EXPECT_EQ(api_result.size(), 3U);
  730. EXPECT_EQ(api_result[0], "application/json");
  731. EXPECT_EQ(api_result[1], "application/xml");
  732. EXPECT_EQ(api_result[2], "text/plain");
  733. }
  734. TEST(ParseAcceptHeaderTest, SpecialCases) {
  735. // Quality value with 3 decimal places
  736. std::vector<std::string> decimal_result;
  737. EXPECT_TRUE(detail::parse_accept_header(
  738. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  739. EXPECT_EQ(decimal_result.size(), 2U);
  740. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  741. EXPECT_EQ(decimal_result[1], "text/html");
  742. // Zero quality (should still be included but with lowest priority)
  743. std::vector<std::string> zero_q_result;
  744. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  745. zero_q_result));
  746. EXPECT_EQ(zero_q_result.size(), 2U);
  747. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  748. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  749. // No spaces around commas
  750. std::vector<std::string> no_space_result;
  751. EXPECT_TRUE(detail::parse_accept_header(
  752. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  753. no_space_result));
  754. EXPECT_EQ(no_space_result.size(), 3U);
  755. EXPECT_EQ(no_space_result[0], "text/html");
  756. EXPECT_EQ(no_space_result[1], "application/json");
  757. EXPECT_EQ(no_space_result[2], "text/plain");
  758. }
  759. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  760. // Quality values always use '.' as the decimal separator, so parsing must
  761. // not depend on the process locale. An embedding application may have
  762. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  763. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  764. std::string saved = cur ? cur : "C";
  765. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  766. "fr_FR.UTF-8"};
  767. bool switched = false;
  768. for (const auto loc : comma_locales) {
  769. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  770. std::localeconv()->decimal_point[0] == ',') {
  771. switched = true;
  772. break;
  773. }
  774. }
  775. if (!switched) {
  776. std::setlocale(LC_NUMERIC, saved.c_str());
  777. GTEST_SKIP() << "no comma-decimal locale available on this host";
  778. }
  779. // The higher-weighted type appears later in the list, so a correct parse
  780. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  781. // sensitive parse reads both weights as 0 and leaves the original order.
  782. std::vector<std::string> result;
  783. EXPECT_TRUE(detail::parse_accept_header(
  784. "application/json;q=0.1,text/html;q=0.9", result));
  785. ASSERT_EQ(result.size(), 2U);
  786. EXPECT_EQ(result[0], "text/html");
  787. EXPECT_EQ(result[1], "application/json");
  788. std::setlocale(LC_NUMERIC, saved.c_str());
  789. }
  790. TEST(ParseAcceptHeaderTest, InvalidCases) {
  791. std::vector<std::string> result;
  792. // Invalid quality value (> 1.0)
  793. EXPECT_FALSE(
  794. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  795. // Invalid quality value (< 0.0)
  796. EXPECT_FALSE(
  797. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  798. // Invalid quality value (not a number)
  799. EXPECT_FALSE(detail::parse_accept_header(
  800. "text/html;q=invalid,application/json", result));
  801. // Empty quality value
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=,application/json", result));
  804. // Invalid media type format (no slash and not wildcard)
  805. EXPECT_FALSE(
  806. detail::parse_accept_header("invalidtype,application/json", result));
  807. // Empty media type
  808. result.clear();
  809. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  810. // Only commas
  811. result.clear();
  812. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  813. // Valid cases should still work
  814. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  815. EXPECT_EQ(result.size(), 1U);
  816. EXPECT_EQ(result[0], "*/*");
  817. EXPECT_TRUE(detail::parse_accept_header("*", result));
  818. EXPECT_EQ(result.size(), 1U);
  819. EXPECT_EQ(result[0], "*");
  820. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "text/*");
  823. }
  824. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  825. Server svr;
  826. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  827. EXPECT_EQ(req.accept_content_types.size(), 3U);
  828. EXPECT_EQ(req.accept_content_types[0], "application/json");
  829. EXPECT_EQ(req.accept_content_types[1], "text/html");
  830. EXPECT_EQ(req.accept_content_types[2], "*/*");
  831. res.set_content("ok", "text/plain");
  832. });
  833. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  834. EXPECT_TRUE(false);
  835. res.set_content("bad request", "text/plain");
  836. });
  837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  838. auto se = detail::scope_exit([&] {
  839. svr.stop();
  840. listen_thread.join();
  841. ASSERT_FALSE(svr.is_running());
  842. });
  843. svr.wait_until_ready();
  844. Client cli("localhost", PORT);
  845. {
  846. auto res = cli.Get(
  847. "/accept_ok",
  848. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  849. ASSERT_TRUE(res);
  850. EXPECT_EQ(StatusCode::OK_200, res->status);
  851. }
  852. {
  853. auto res = cli.Get("/accept_bad_request",
  854. Headers{{"Accept", "text/html;q=abc,application/json"}});
  855. ASSERT_TRUE(res);
  856. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  857. }
  858. }
  859. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  860. Server svr;
  861. svr.Get("/", [](const Request & /*req*/, Response &res) {
  862. res.set_content("ok", "text/plain");
  863. });
  864. std::atomic<int> start_count{0};
  865. std::atomic<bool> running_when_called{false};
  866. svr.set_start_handler([&]() {
  867. running_when_called = svr.is_running();
  868. start_count++;
  869. });
  870. auto port = svr.bind_to_any_port(HOST);
  871. std::thread t([&]() { svr.listen_after_bind(); });
  872. auto se = detail::scope_exit([&] {
  873. svr.stop();
  874. t.join();
  875. ASSERT_FALSE(svr.is_running());
  876. });
  877. svr.wait_until_ready();
  878. // A successful request proves the accept loop is running, which the start
  879. // handler precedes; so by now the handler must have run exactly once.
  880. Client cli(HOST, port);
  881. cli.set_connection_timeout(std::chrono::seconds(5));
  882. auto res = cli.Get("/");
  883. ASSERT_TRUE(res);
  884. EXPECT_EQ(StatusCode::OK_200, res->status);
  885. EXPECT_EQ(1, start_count.load());
  886. EXPECT_TRUE(running_when_called.load());
  887. }
  888. TEST(DivideTest, DivideStringTests) {
  889. auto divide = [](const std::string &str, char d) {
  890. std::string lhs;
  891. std::string rhs;
  892. detail::divide(str, d,
  893. [&](const char *lhs_data, std::size_t lhs_size,
  894. const char *rhs_data, std::size_t rhs_size) {
  895. lhs.assign(lhs_data, lhs_size);
  896. rhs.assign(rhs_data, rhs_size);
  897. });
  898. return std::make_pair(std::move(lhs), std::move(rhs));
  899. };
  900. {
  901. const auto res = divide("", '=');
  902. EXPECT_EQ(res.first, "");
  903. EXPECT_EQ(res.second, "");
  904. }
  905. {
  906. const auto res = divide("=", '=');
  907. EXPECT_EQ(res.first, "");
  908. EXPECT_EQ(res.second, "");
  909. }
  910. {
  911. const auto res = divide(" ", '=');
  912. EXPECT_EQ(res.first, " ");
  913. EXPECT_EQ(res.second, "");
  914. }
  915. {
  916. const auto res = divide("a", '=');
  917. EXPECT_EQ(res.first, "a");
  918. EXPECT_EQ(res.second, "");
  919. }
  920. {
  921. const auto res = divide("a=", '=');
  922. EXPECT_EQ(res.first, "a");
  923. EXPECT_EQ(res.second, "");
  924. }
  925. {
  926. const auto res = divide("=b", '=');
  927. EXPECT_EQ(res.first, "");
  928. EXPECT_EQ(res.second, "b");
  929. }
  930. {
  931. const auto res = divide("a=b", '=');
  932. EXPECT_EQ(res.first, "a");
  933. EXPECT_EQ(res.second, "b");
  934. }
  935. {
  936. const auto res = divide("a=b=", '=');
  937. EXPECT_EQ(res.first, "a");
  938. EXPECT_EQ(res.second, "b=");
  939. }
  940. {
  941. const auto res = divide("a=b=c", '=');
  942. EXPECT_EQ(res.first, "a");
  943. EXPECT_EQ(res.second, "b=c");
  944. }
  945. }
  946. TEST(SplitTest, ParseQueryString) {
  947. string s = "key1=val1&key2=val2&key3=val3";
  948. Params dic;
  949. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  950. [&](const char *b, const char *e) {
  951. string key, val;
  952. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  953. if (key.empty()) {
  954. key.assign(b2, e2);
  955. } else {
  956. val.assign(b2, e2);
  957. }
  958. });
  959. dic.emplace(key, val);
  960. });
  961. EXPECT_EQ("val1", dic.find("key1")->second);
  962. EXPECT_EQ("val2", dic.find("key2")->second);
  963. EXPECT_EQ("val3", dic.find("key3")->second);
  964. }
  965. TEST(SplitTest, ParseInvalidQueryTests) {
  966. {
  967. string s = " ";
  968. Params dict;
  969. detail::parse_query_text(s, dict);
  970. EXPECT_TRUE(dict.empty());
  971. }
  972. {
  973. string s = " = =";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. }
  979. TEST(ParseQueryTest, ParseQueryString) {
  980. {
  981. std::string s = "key1=val1&key2=val2&key3=val3";
  982. Params dic;
  983. detail::parse_query_text(s, dic);
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. {
  989. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("", dic.find("key1")->second);
  993. EXPECT_EQ("val1", dic.find("key2")->second);
  994. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  995. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  996. }
  997. }
  998. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  999. Params dic;
  1000. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1001. dic.emplace("key1", "val1");
  1002. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1003. dic.emplace("key2", "val2");
  1004. dic.emplace("key3", "val3");
  1005. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1006. }
  1007. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1008. string content_type = "multipart/form-data; boundary=something";
  1009. string boundary;
  1010. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1011. EXPECT_TRUE(ret);
  1012. EXPECT_EQ(boundary, "something");
  1013. }
  1014. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1015. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1016. string boundary;
  1017. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1018. EXPECT_TRUE(ret);
  1019. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1020. }
  1021. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1022. string content_type =
  1023. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1036. }
  1037. TEST(GetHeaderValueTest, DefaultValue) {
  1038. Headers headers = {{"Dummy", "Dummy"}};
  1039. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1040. EXPECT_STREQ("text/plain", val);
  1041. }
  1042. TEST(GetHeaderValueTest, DefaultValueInt) {
  1043. Headers headers = {{"Dummy", "Dummy"}};
  1044. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1045. EXPECT_EQ(100ull, val);
  1046. }
  1047. TEST(GetHeaderValueTest, RegularValue) {
  1048. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1049. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1050. EXPECT_STREQ("text/html", val);
  1051. }
  1052. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1053. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1054. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1055. EXPECT_STREQ("text/html", val);
  1056. }
  1057. TEST(GetHeaderValueTest, SetContent) {
  1058. Response res;
  1059. res.set_content("html", "text/html");
  1060. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1061. res.set_content("text", "text/plain");
  1062. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1063. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1064. }
  1065. TEST(GetHeaderValueTest, RegularValueInt) {
  1066. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1067. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1068. EXPECT_EQ(100ull, val);
  1069. }
  1070. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1071. Headers headers = {{"Content-Length", "x"}};
  1072. auto is_invalid_value = false;
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1074. is_invalid_value);
  1075. EXPECT_EQ(0ull, val);
  1076. EXPECT_TRUE(is_invalid_value);
  1077. }
  1078. TEST(GetHeaderValueTest, Range) {
  1079. {
  1080. Headers headers = {make_range_header({{1, -1}})};
  1081. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1082. EXPECT_STREQ("bytes=1-", val);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{-1, 1}})};
  1086. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1087. EXPECT_STREQ("bytes=-1", val);
  1088. }
  1089. {
  1090. Headers headers = {make_range_header({{1, 10}})};
  1091. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1092. EXPECT_STREQ("bytes=1-10", val);
  1093. }
  1094. {
  1095. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1096. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1097. EXPECT_STREQ("bytes=1-10, 100-", val);
  1098. }
  1099. {
  1100. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1101. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1102. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1103. }
  1104. {
  1105. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1106. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1107. EXPECT_STREQ("bytes=0-0, -1", val);
  1108. }
  1109. }
  1110. TEST(ParseHeaderValueTest, Range) {
  1111. {
  1112. Ranges ranges;
  1113. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1114. EXPECT_TRUE(ret);
  1115. EXPECT_EQ(1u, ranges.size());
  1116. EXPECT_EQ(1u, ranges[0].first);
  1117. EXPECT_EQ(-1, ranges[0].second);
  1118. }
  1119. {
  1120. Ranges ranges;
  1121. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1122. EXPECT_TRUE(ret);
  1123. EXPECT_EQ(1u, ranges.size());
  1124. EXPECT_EQ(-1, ranges[0].first);
  1125. EXPECT_EQ(1u, ranges[0].second);
  1126. }
  1127. {
  1128. Ranges ranges;
  1129. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1130. EXPECT_TRUE(ret);
  1131. EXPECT_EQ(1u, ranges.size());
  1132. EXPECT_EQ(1u, ranges[0].first);
  1133. EXPECT_EQ(10u, ranges[0].second);
  1134. }
  1135. {
  1136. Ranges ranges;
  1137. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1138. EXPECT_FALSE(ret);
  1139. }
  1140. {
  1141. Ranges ranges;
  1142. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1143. EXPECT_TRUE(ret);
  1144. EXPECT_EQ(2u, ranges.size());
  1145. EXPECT_EQ(1u, ranges[0].first);
  1146. EXPECT_EQ(10u, ranges[0].second);
  1147. EXPECT_EQ(100u, ranges[1].first);
  1148. EXPECT_EQ(-1, ranges[1].second);
  1149. }
  1150. {
  1151. Ranges ranges;
  1152. auto ret =
  1153. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1154. EXPECT_TRUE(ret);
  1155. EXPECT_EQ(3u, ranges.size());
  1156. EXPECT_EQ(1u, ranges[0].first);
  1157. EXPECT_EQ(10u, ranges[0].second);
  1158. EXPECT_EQ(100u, ranges[1].first);
  1159. EXPECT_EQ(200u, ranges[1].second);
  1160. EXPECT_EQ(300u, ranges[2].first);
  1161. EXPECT_EQ(400u, ranges[2].second);
  1162. }
  1163. {
  1164. Ranges ranges;
  1165. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1166. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1167. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1168. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1169. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1170. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1171. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1172. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1173. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1174. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1175. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1176. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1177. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1178. EXPECT_TRUE(ranges.empty());
  1179. }
  1180. }
  1181. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1182. Request req;
  1183. req.set_header("Accept-Encoding", "gzip");
  1184. Response res;
  1185. res.set_header("Content-Type", "text/plain");
  1186. auto ret = detail::encoding_type(req, res);
  1187. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1188. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1189. #else
  1190. EXPECT_TRUE(ret == detail::EncodingType::None);
  1191. #endif
  1192. }
  1193. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1194. Request req;
  1195. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1196. Response res;
  1197. res.set_header("Content-Type", "text/plain");
  1198. auto ret = detail::encoding_type(req, res);
  1199. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1200. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1201. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1202. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1203. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1204. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1205. #else
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. #endif
  1208. }
  1209. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1210. Request req;
  1211. req.set_header("Accept-Encoding",
  1212. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1213. Response res;
  1214. res.set_header("Content-Type", "text/plain");
  1215. auto ret = detail::encoding_type(req, res);
  1216. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1217. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1218. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1219. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1220. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1221. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1222. #else
  1223. EXPECT_TRUE(ret == detail::EncodingType::None);
  1224. #endif
  1225. }
  1226. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1227. // All supported encodings rejected with q=0 should return None
  1228. Request req;
  1229. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1230. Response res;
  1231. res.set_header("Content-Type", "text/plain");
  1232. auto ret = detail::encoding_type(req, res);
  1233. EXPECT_TRUE(ret == detail::EncodingType::None);
  1234. }
  1235. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1236. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1237. Request req;
  1238. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1239. Response res;
  1240. res.set_header("Content-Type", "text/plain");
  1241. auto ret = detail::encoding_type(req, res);
  1242. EXPECT_TRUE(ret == detail::EncodingType::None);
  1243. }
  1244. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1245. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1246. Request req;
  1247. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1248. Response res;
  1249. res.set_header("Content-Type", "text/plain");
  1250. auto ret = detail::encoding_type(req, res);
  1251. EXPECT_TRUE(ret == detail::EncodingType::None);
  1252. }
  1253. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1254. // RFC 7231: Accept-Encoding values are case-insensitive
  1255. Request req;
  1256. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1257. Response res;
  1258. res.set_header("Content-Type", "text/plain");
  1259. auto ret = detail::encoding_type(req, res);
  1260. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1261. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1262. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1263. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1264. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1265. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1266. #else
  1267. EXPECT_TRUE(ret == detail::EncodingType::None);
  1268. #endif
  1269. }
  1270. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1271. // q value should determine priority, not hardcoded order
  1272. Request req;
  1273. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1274. Response res;
  1275. res.set_header("Content-Type", "text/plain");
  1276. auto ret = detail::encoding_type(req, res);
  1277. // gzip has highest q=1.0, so it should be selected even though
  1278. // br and zstd are also supported
  1279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1280. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1281. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1282. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1283. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1284. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1285. #else
  1286. EXPECT_TRUE(ret == detail::EncodingType::None);
  1287. #endif
  1288. }
  1289. TEST(BufferStreamTest, read) {
  1290. detail::BufferStream strm1;
  1291. Stream &strm = strm1;
  1292. EXPECT_EQ(5, strm.write("hello"));
  1293. char buf[512];
  1294. EXPECT_EQ(2, strm.read(buf, 2));
  1295. EXPECT_EQ('h', buf[0]);
  1296. EXPECT_EQ('e', buf[1]);
  1297. EXPECT_EQ(2, strm.read(buf, 2));
  1298. EXPECT_EQ('l', buf[0]);
  1299. EXPECT_EQ('l', buf[1]);
  1300. EXPECT_EQ(1, strm.read(buf, 1));
  1301. EXPECT_EQ('o', buf[0]);
  1302. EXPECT_EQ(0, strm.read(buf, 1));
  1303. }
  1304. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1305. auto host = "www.httpwatch.com";
  1306. auto ip = hosted_at(host);
  1307. EXPECT_EQ("23.96.13.243", ip);
  1308. std::vector<std::string> addrs;
  1309. hosted_at(host, addrs);
  1310. EXPECT_EQ(1u, addrs.size());
  1311. }
  1312. #if 0 // It depends on each test environment...
  1313. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1314. auto host = "www.youtube.com";
  1315. std::vector<std::string> addrs;
  1316. hosted_at(host, addrs);
  1317. EXPECT_EQ(20u, addrs.size());
  1318. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1319. EXPECT_TRUE(it != addrs.end());
  1320. }
  1321. #endif
  1322. class ChunkedEncodingTest : public ::testing::Test {
  1323. protected:
  1324. ChunkedEncodingTest()
  1325. : cli_(HOST, PORT)
  1326. #ifdef CPPHTTPLIB_SSL_ENABLED
  1327. ,
  1328. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1329. #endif
  1330. {
  1331. cli_.set_connection_timeout(2);
  1332. #ifdef CPPHTTPLIB_SSL_ENABLED
  1333. cli_.enable_server_certificate_verification(false);
  1334. #endif
  1335. }
  1336. virtual void SetUp() {
  1337. read_file("./image.jpg", image_data_);
  1338. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. svr_.Get(
  1342. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1343. res.set_chunked_content_provider(
  1344. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1345. size_t remaining = image_data_.size() - offset;
  1346. if (remaining == 0) {
  1347. sink.done();
  1348. } else {
  1349. constexpr size_t CHUNK_SIZE = 1024;
  1350. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1351. sink.write(&image_data_[offset], send_size);
  1352. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1353. }
  1354. return true;
  1355. });
  1356. });
  1357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1358. svr_.wait_until_ready();
  1359. }
  1360. virtual void TearDown() {
  1361. svr_.stop();
  1362. if (!request_threads_.empty()) {
  1363. std::this_thread::sleep_for(std::chrono::seconds(1));
  1364. for (auto &t : request_threads_) {
  1365. t.join();
  1366. }
  1367. }
  1368. t_.join();
  1369. }
  1370. #ifdef CPPHTTPLIB_SSL_ENABLED
  1371. SSLClient cli_;
  1372. SSLServer svr_;
  1373. #else
  1374. Client cli_;
  1375. Server svr_;
  1376. #endif
  1377. thread t_;
  1378. std::vector<thread> request_threads_;
  1379. std::string image_data_;
  1380. };
  1381. TEST_F(ChunkedEncodingTest, NormalGet) {
  1382. auto res = cli_.Get("/chunked");
  1383. ASSERT_TRUE(res);
  1384. std::string out;
  1385. read_file("./image.jpg", out);
  1386. EXPECT_EQ(StatusCode::OK_200, res->status);
  1387. EXPECT_EQ(out, res->body);
  1388. }
  1389. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1390. std::string body;
  1391. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1392. body.append(data, data_length);
  1393. return true;
  1394. });
  1395. ASSERT_TRUE(res);
  1396. std::string out;
  1397. read_file("./image.jpg", out);
  1398. EXPECT_EQ(StatusCode::OK_200, res->status);
  1399. EXPECT_EQ(out, body);
  1400. }
  1401. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1402. std::string body;
  1403. auto res = cli_.Get(
  1404. "/chunked",
  1405. [&](const Response &response) {
  1406. EXPECT_EQ(StatusCode::OK_200, response.status);
  1407. return true;
  1408. },
  1409. [&](const char *data, size_t data_length) {
  1410. body.append(data, data_length);
  1411. return true;
  1412. });
  1413. ASSERT_TRUE(res);
  1414. std::string out;
  1415. read_file("./image.jpg", out);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. EXPECT_EQ(out, body);
  1418. }
  1419. TEST(RangeTest, FromHTTPBin_Online) {
  1420. auto host = "httpbingo.org";
  1421. auto path = std::string{"/range/32"};
  1422. #ifdef CPPHTTPLIB_SSL_ENABLED
  1423. auto port = 443;
  1424. SSLClient cli(host, port);
  1425. #else
  1426. auto port = 80;
  1427. Client cli(host, port);
  1428. #endif
  1429. cli.set_connection_timeout(5);
  1430. {
  1431. auto res = cli.Get(path);
  1432. ASSERT_TRUE(res);
  1433. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1434. EXPECT_EQ(StatusCode::OK_200, res->status);
  1435. }
  1436. {
  1437. Headers headers = {make_range_header({{1, -1}})};
  1438. auto res = cli.Get(path, headers);
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1442. }
  1443. {
  1444. Headers headers = {make_range_header({{1, 10}})};
  1445. auto res = cli.Get(path, headers);
  1446. ASSERT_TRUE(res);
  1447. EXPECT_EQ("bcdefghijk", res->body);
  1448. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1449. }
  1450. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1451. // entire resource, while the original httpbin returned 200. Both are
  1452. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1453. {
  1454. Headers headers = {make_range_header({{0, 31}})};
  1455. auto res = cli.Get(path, headers);
  1456. ASSERT_TRUE(res);
  1457. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1458. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1459. res->status == StatusCode::PartialContent_206);
  1460. }
  1461. {
  1462. Headers headers = {make_range_header({{0, -1}})};
  1463. auto res = cli.Get(path, headers);
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1466. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1467. res->status == StatusCode::PartialContent_206);
  1468. }
  1469. // go-httpbin returns 206 with clamped range for over-range requests,
  1470. // while the original httpbin returned 416. Both behaviors are observed
  1471. // in real servers, so we only verify the request succeeds.
  1472. {
  1473. Headers headers = {make_range_header({{0, 32}})};
  1474. auto res = cli.Get(path, headers);
  1475. ASSERT_TRUE(res);
  1476. }
  1477. }
  1478. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1479. auto host = "unresolvableaddress.local";
  1480. auto path = std::string{"/"};
  1481. #ifdef CPPHTTPLIB_SSL_ENABLED
  1482. auto port = 443;
  1483. SSLClient cli(host, port);
  1484. #else
  1485. auto port = 80;
  1486. Client cli(host, port);
  1487. #endif
  1488. cli.set_connection_timeout(1);
  1489. {
  1490. auto res = cli.Get(path);
  1491. ASSERT_FALSE(res);
  1492. }
  1493. std::this_thread::sleep_for(std::chrono::seconds(8));
  1494. }
  1495. #if defined(__linux__) && defined(__GLIBC__) && \
  1496. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1497. // Forward declaration: in split builds split.py strips `inline` and moves the
  1498. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1499. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1500. // against the symbol in both header-only and split builds.
  1501. namespace httplib {
  1502. namespace detail {
  1503. int getaddrinfo_with_timeout(const char *node, const char *service,
  1504. const struct addrinfo *hints,
  1505. struct addrinfo **res, time_t timeout_sec);
  1506. } // namespace detail
  1507. } // namespace httplib
  1508. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1509. //
  1510. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1511. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1512. // gai_suspend() call hits the connection timeout the function calls
  1513. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1514. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1515. // still alive and still references the now-destroyed stack frame.
  1516. //
  1517. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1518. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1519. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1520. // and runs them in a container.
  1521. namespace {
  1522. bool should_run_issue_2431_tests() {
  1523. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1524. return v && *v && std::string(v) != "0";
  1525. }
  1526. std::string unique_unresolvable_host(int n) {
  1527. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1528. // glibc still asks the configured nameserver — which is exactly the path
  1529. // we want to exercise. A unique label per call avoids the resolver cache.
  1530. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1531. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1532. std::to_string(n) + ".invalid";
  1533. }
  1534. } // namespace
  1535. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1536. if (!should_run_issue_2431_tests()) {
  1537. GTEST_SKIP()
  1538. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1539. }
  1540. for (int i = 0; i < 8; ++i) {
  1541. struct addrinfo hints;
  1542. memset(&hints, 0, sizeof(hints));
  1543. hints.ai_family = AF_UNSPEC;
  1544. hints.ai_socktype = SOCK_STREAM;
  1545. auto host = unique_unresolvable_host(i);
  1546. struct addrinfo *result = nullptr;
  1547. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1548. &result, /*timeout_sec=*/1);
  1549. if (rc == 0 && result) { freeaddrinfo(result); }
  1550. }
  1551. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1552. // stack region they still believe holds their gaicb.
  1553. std::this_thread::sleep_for(std::chrono::seconds(3));
  1554. }
  1555. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1556. if (!should_run_issue_2431_tests()) {
  1557. GTEST_SKIP()
  1558. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1559. }
  1560. std::atomic<bool> stop{false};
  1561. std::vector<std::thread> threads;
  1562. for (int t = 0; t < 8; ++t) {
  1563. threads.emplace_back([t, &stop] {
  1564. int i = 0;
  1565. while (!stop.load(std::memory_order_relaxed)) {
  1566. struct addrinfo hints;
  1567. memset(&hints, 0, sizeof(hints));
  1568. hints.ai_family = AF_UNSPEC;
  1569. hints.ai_socktype = SOCK_STREAM;
  1570. auto host = unique_unresolvable_host(t * 100000 + i++);
  1571. struct addrinfo *result = nullptr;
  1572. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1573. &result, /*timeout_sec=*/1);
  1574. if (rc == 0 && result) { freeaddrinfo(result); }
  1575. }
  1576. });
  1577. }
  1578. std::this_thread::sleep_for(std::chrono::seconds(8));
  1579. stop.store(true, std::memory_order_relaxed);
  1580. for (auto &th : threads) {
  1581. th.join();
  1582. }
  1583. std::this_thread::sleep_for(std::chrono::seconds(3));
  1584. }
  1585. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1586. if (!should_run_issue_2431_tests()) {
  1587. GTEST_SKIP()
  1588. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1589. }
  1590. std::atomic<bool> stop{false};
  1591. std::vector<std::thread> threads;
  1592. for (int t = 0; t < 8; ++t) {
  1593. threads.emplace_back([t, &stop] {
  1594. int i = 0;
  1595. while (!stop.load(std::memory_order_relaxed)) {
  1596. auto host = unique_unresolvable_host(t * 100000 + i++);
  1597. Client cli(host, 80);
  1598. cli.set_connection_timeout(1, 0);
  1599. cli.set_read_timeout(1, 0);
  1600. cli.set_write_timeout(1, 0);
  1601. (void)cli.Get("/");
  1602. }
  1603. });
  1604. }
  1605. std::this_thread::sleep_for(std::chrono::seconds(8));
  1606. stop.store(true, std::memory_order_relaxed);
  1607. for (auto &th : threads) {
  1608. th.join();
  1609. }
  1610. std::this_thread::sleep_for(std::chrono::seconds(3));
  1611. }
  1612. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1613. TEST(ConnectionErrorTest, InvalidHost) {
  1614. auto host = "-abcde.com";
  1615. #ifdef CPPHTTPLIB_SSL_ENABLED
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. #else
  1619. auto port = 80;
  1620. Client cli(host, port);
  1621. #endif
  1622. cli.set_connection_timeout(std::chrono::seconds(2));
  1623. auto res = cli.Get("/");
  1624. ASSERT_TRUE(!res);
  1625. EXPECT_EQ(Error::Connection, res.error());
  1626. }
  1627. TEST(ConnectionErrorTest, InvalidHost2) {
  1628. auto host = "httpcan.org/";
  1629. #ifdef CPPHTTPLIB_SSL_ENABLED
  1630. SSLClient cli(host);
  1631. #else
  1632. Client cli(host);
  1633. #endif
  1634. cli.set_connection_timeout(std::chrono::seconds(2));
  1635. auto res = cli.Get("/");
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Connection, res.error());
  1638. }
  1639. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1640. auto host = "httpcan.org/";
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. SSLClient cli(host);
  1643. #else
  1644. Client cli(host);
  1645. #endif
  1646. cli.set_connection_timeout(std::chrono::seconds(2));
  1647. auto res = cli.Get("/");
  1648. ASSERT_TRUE(!res);
  1649. stringstream s;
  1650. s << "error code: " << res.error();
  1651. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1652. }
  1653. TEST(ConnectionErrorTest, InvalidPort) {
  1654. auto host = "localhost";
  1655. auto port = 44380;
  1656. #ifdef CPPHTTPLIB_SSL_ENABLED
  1657. SSLClient cli(host, port);
  1658. #else
  1659. Client cli(host, port);
  1660. #endif
  1661. cli.set_connection_timeout(std::chrono::seconds(2));
  1662. auto res = cli.Get("/");
  1663. ASSERT_TRUE(!res);
  1664. EXPECT_TRUE(Error::Connection == res.error() ||
  1665. Error::ConnectionTimeout == res.error());
  1666. }
  1667. TEST(ConnectionErrorTest, Timeout_Online) {
  1668. auto host = "google.com";
  1669. #ifdef CPPHTTPLIB_SSL_ENABLED
  1670. auto port = 44380;
  1671. SSLClient cli(host, port);
  1672. #else
  1673. auto port = 8080;
  1674. Client cli(host, port);
  1675. #endif
  1676. cli.set_connection_timeout(std::chrono::seconds(2));
  1677. // only probe one address type so that the error reason
  1678. // correlates to the timed-out IPv4, not the unsupported
  1679. // IPv6 connection attempt
  1680. cli.set_address_family(AF_INET);
  1681. auto res = cli.Get("/");
  1682. ASSERT_TRUE(!res);
  1683. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1684. }
  1685. TEST(CancelTest, NoCancel_Online) {
  1686. auto host = "httpbingo.org";
  1687. auto path = std::string{"/range/32"};
  1688. #ifdef CPPHTTPLIB_SSL_ENABLED
  1689. auto port = 443;
  1690. SSLClient cli(host, port);
  1691. #else
  1692. auto port = 80;
  1693. Client cli(host, port);
  1694. #endif
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1699. EXPECT_EQ(StatusCode::OK_200, res->status);
  1700. }
  1701. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1702. // Use /bytes with a large payload so that the DownloadProgress callback
  1703. // (which only fires for Content-Length responses) is invoked before the
  1704. // entire body is received, giving cancellation a chance to fire.
  1705. auto host = "httpbingo.org";
  1706. auto path = std::string{"/bytes/524288"};
  1707. #ifdef CPPHTTPLIB_SSL_ENABLED
  1708. auto port = 443;
  1709. SSLClient cli(host, port);
  1710. #else
  1711. auto port = 80;
  1712. Client cli(host, port);
  1713. #endif
  1714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. ASSERT_TRUE(!res);
  1717. EXPECT_EQ(Error::Canceled, res.error());
  1718. }
  1719. TEST(CancelTest, WithCancelLargePayload_Online) {
  1720. auto host = "httpbingo.org";
  1721. auto path = std::string{"/bytes/524288"};
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. auto port = 443;
  1724. SSLClient cli(host, port);
  1725. #else
  1726. auto port = 80;
  1727. Client cli(host, port);
  1728. #endif
  1729. cli.set_connection_timeout(std::chrono::seconds(5));
  1730. uint32_t count = 0;
  1731. auto res =
  1732. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1733. ASSERT_TRUE(!res);
  1734. EXPECT_EQ(Error::Canceled, res.error());
  1735. }
  1736. TEST(CancelTest, NoCancelPost) {
  1737. Server svr;
  1738. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1739. res.set_content("Hello World!", "text/plain");
  1740. });
  1741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1742. auto se = detail::scope_exit([&] {
  1743. svr.stop();
  1744. thread.join();
  1745. ASSERT_FALSE(svr.is_running());
  1746. });
  1747. svr.wait_until_ready();
  1748. Client cli(HOST, PORT);
  1749. cli.set_connection_timeout(std::chrono::seconds(5));
  1750. auto res =
  1751. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1752. "application/json", [](uint64_t, uint64_t) { return true; });
  1753. ASSERT_TRUE(res);
  1754. EXPECT_EQ("Hello World!", res->body);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1758. Server svr;
  1759. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1760. res.set_content("Hello World!", "text/plain");
  1761. });
  1762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1763. auto se = detail::scope_exit([&] {
  1764. svr.stop();
  1765. thread.join();
  1766. ASSERT_FALSE(svr.is_running());
  1767. });
  1768. svr.wait_until_ready();
  1769. Client cli(HOST, PORT);
  1770. cli.set_connection_timeout(std::chrono::seconds(5));
  1771. auto res =
  1772. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1773. "application/json", [](uint64_t, uint64_t) { return false; });
  1774. ASSERT_TRUE(!res);
  1775. EXPECT_EQ(Error::Canceled, res.error());
  1776. }
  1777. TEST(CancelTest, WithCancelLargePayloadPost) {
  1778. Server svr;
  1779. svr.set_payload_max_length(200 * 1024 * 1024);
  1780. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1781. res.set_content(LARGE_DATA, "text/plain");
  1782. });
  1783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1784. auto se = detail::scope_exit([&] {
  1785. svr.stop();
  1786. thread.join();
  1787. ASSERT_FALSE(svr.is_running());
  1788. });
  1789. svr.wait_until_ready();
  1790. Client cli(HOST, PORT);
  1791. cli.set_payload_max_length(200 * 1024 * 1024);
  1792. cli.set_connection_timeout(std::chrono::seconds(5));
  1793. auto res =
  1794. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1795. "application/json", [](uint64_t, uint64_t) { return false; });
  1796. ASSERT_TRUE(!res);
  1797. EXPECT_EQ(Error::Canceled, res.error());
  1798. }
  1799. TEST(CancelTest, NoCancelPut) {
  1800. Server svr;
  1801. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1802. res.set_content("Hello World!", "text/plain");
  1803. });
  1804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1805. auto se = detail::scope_exit([&] {
  1806. svr.stop();
  1807. thread.join();
  1808. ASSERT_FALSE(svr.is_running());
  1809. });
  1810. svr.wait_until_ready();
  1811. Client cli(HOST, PORT);
  1812. cli.set_connection_timeout(std::chrono::seconds(5));
  1813. auto res =
  1814. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1815. "application/json", [](uint64_t, uint64_t) { return true; });
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ("Hello World!", res->body);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. }
  1820. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1821. Server svr;
  1822. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1823. res.set_content("Hello World!", "text/plain");
  1824. });
  1825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1826. auto se = detail::scope_exit([&] {
  1827. svr.stop();
  1828. thread.join();
  1829. ASSERT_FALSE(svr.is_running());
  1830. });
  1831. svr.wait_until_ready();
  1832. Client cli(HOST, PORT);
  1833. cli.set_connection_timeout(std::chrono::seconds(5));
  1834. auto res =
  1835. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1836. "application/json", [](uint64_t, uint64_t) { return false; });
  1837. ASSERT_TRUE(!res);
  1838. EXPECT_EQ(Error::Canceled, res.error());
  1839. }
  1840. TEST(CancelTest, WithCancelLargePayloadPut) {
  1841. Server svr;
  1842. svr.set_payload_max_length(200 * 1024 * 1024);
  1843. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1844. res.set_content(LARGE_DATA, "text/plain");
  1845. });
  1846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1847. auto se = detail::scope_exit([&] {
  1848. svr.stop();
  1849. thread.join();
  1850. ASSERT_FALSE(svr.is_running());
  1851. });
  1852. svr.wait_until_ready();
  1853. Client cli(HOST, PORT);
  1854. cli.set_payload_max_length(200 * 1024 * 1024);
  1855. cli.set_connection_timeout(std::chrono::seconds(5));
  1856. auto res =
  1857. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1858. "application/json", [](uint64_t, uint64_t) { return false; });
  1859. ASSERT_TRUE(!res);
  1860. EXPECT_EQ(Error::Canceled, res.error());
  1861. }
  1862. TEST(CancelTest, NoCancelPatch) {
  1863. Server svr;
  1864. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1865. res.set_content("Hello World!", "text/plain");
  1866. });
  1867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1868. auto se = detail::scope_exit([&] {
  1869. svr.stop();
  1870. thread.join();
  1871. ASSERT_FALSE(svr.is_running());
  1872. });
  1873. svr.wait_until_ready();
  1874. Client cli(HOST, PORT);
  1875. cli.set_connection_timeout(std::chrono::seconds(5));
  1876. auto res =
  1877. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1878. "application/json", [](uint64_t, uint64_t) { return true; });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ("Hello World!", res->body);
  1881. EXPECT_EQ(StatusCode::OK_200, res->status);
  1882. }
  1883. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1884. Server svr;
  1885. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1886. res.set_content("Hello World!", "text/plain");
  1887. });
  1888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1889. auto se = detail::scope_exit([&] {
  1890. svr.stop();
  1891. thread.join();
  1892. ASSERT_FALSE(svr.is_running());
  1893. });
  1894. svr.wait_until_ready();
  1895. Client cli(HOST, PORT);
  1896. cli.set_connection_timeout(std::chrono::seconds(5));
  1897. auto res =
  1898. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1899. "application/json", [](uint64_t, uint64_t) { return false; });
  1900. ASSERT_TRUE(!res);
  1901. EXPECT_EQ(Error::Canceled, res.error());
  1902. }
  1903. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1904. Server svr;
  1905. svr.set_payload_max_length(200 * 1024 * 1024);
  1906. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1907. res.set_content(LARGE_DATA, "text/plain");
  1908. });
  1909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1910. auto se = detail::scope_exit([&] {
  1911. svr.stop();
  1912. thread.join();
  1913. ASSERT_FALSE(svr.is_running());
  1914. });
  1915. svr.wait_until_ready();
  1916. Client cli(HOST, PORT);
  1917. cli.set_payload_max_length(200 * 1024 * 1024);
  1918. cli.set_connection_timeout(std::chrono::seconds(5));
  1919. auto res =
  1920. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1921. "application/json", [](uint64_t, uint64_t) { return false; });
  1922. ASSERT_TRUE(!res);
  1923. EXPECT_EQ(Error::Canceled, res.error());
  1924. }
  1925. TEST(CancelTest, NoCancelDelete) {
  1926. Server svr;
  1927. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1928. res.set_content("Hello World!", "text/plain");
  1929. });
  1930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1931. auto se = detail::scope_exit([&] {
  1932. svr.stop();
  1933. thread.join();
  1934. ASSERT_FALSE(svr.is_running());
  1935. });
  1936. svr.wait_until_ready();
  1937. Client cli(HOST, PORT);
  1938. cli.set_connection_timeout(std::chrono::seconds(5));
  1939. auto res =
  1940. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1941. "application/json", [](uint64_t, uint64_t) { return true; });
  1942. ASSERT_TRUE(res);
  1943. EXPECT_EQ("Hello World!", res->body);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. }
  1946. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1947. Server svr;
  1948. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1949. res.set_content("Hello World!", "text/plain");
  1950. });
  1951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1952. auto se = detail::scope_exit([&] {
  1953. svr.stop();
  1954. thread.join();
  1955. ASSERT_FALSE(svr.is_running());
  1956. });
  1957. svr.wait_until_ready();
  1958. Client cli(HOST, PORT);
  1959. cli.set_connection_timeout(std::chrono::seconds(5));
  1960. auto res =
  1961. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1962. "application/json", [](uint64_t, uint64_t) { return false; });
  1963. ASSERT_TRUE(!res);
  1964. EXPECT_EQ(Error::Canceled, res.error());
  1965. }
  1966. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1967. Server svr;
  1968. svr.set_payload_max_length(200 * 1024 * 1024);
  1969. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1970. res.set_content(LARGE_DATA, "text/plain");
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. Client cli(HOST, PORT);
  1980. cli.set_payload_max_length(200 * 1024 * 1024);
  1981. cli.set_connection_timeout(std::chrono::seconds(5));
  1982. auto res =
  1983. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1984. "application/json", [](uint64_t, uint64_t) { return false; });
  1985. ASSERT_TRUE(!res);
  1986. EXPECT_EQ(Error::Canceled, res.error());
  1987. }
  1988. static std::string remove_whitespace(const std::string &input) {
  1989. std::string output;
  1990. output.reserve(input.size());
  1991. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1992. [](unsigned char c) { return !std::isspace(c); });
  1993. return output;
  1994. }
  1995. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1996. auto host = "httpbingo.org";
  1997. auto path = std::string{"/basic-auth/hello/world"};
  1998. #ifdef CPPHTTPLIB_SSL_ENABLED
  1999. auto port = 443;
  2000. SSLClient cli(host, port);
  2001. #else
  2002. auto port = 80;
  2003. Client cli(host, port);
  2004. #endif
  2005. {
  2006. auto res = cli.Get(path);
  2007. ASSERT_TRUE(res);
  2008. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2009. }
  2010. {
  2011. auto res = cli.Get(
  2012. path, Headers{make_basic_authentication_header("hello", "world")});
  2013. ASSERT_TRUE(res);
  2014. auto body = remove_whitespace(res->body);
  2015. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2016. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2017. EXPECT_EQ(StatusCode::OK_200, res->status);
  2018. }
  2019. {
  2020. cli.set_basic_auth("hello", "world");
  2021. auto res = cli.Get(path);
  2022. ASSERT_TRUE(res);
  2023. auto body = remove_whitespace(res->body);
  2024. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2025. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. {
  2029. cli.set_basic_auth("hello", "bad");
  2030. auto res = cli.Get(path);
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2033. }
  2034. {
  2035. cli.set_basic_auth("bad", "world");
  2036. auto res = cli.Get(path);
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2039. }
  2040. }
  2041. #ifdef CPPHTTPLIB_SSL_ENABLED
  2042. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2043. auto host = "httpbingo.org";
  2044. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2045. auto paths = std::vector<std::string>{
  2046. "/digest-auth/auth/hello/world/MD5",
  2047. "/digest-auth/auth/hello/world/SHA-256",
  2048. };
  2049. auto port = 443;
  2050. SSLClient cli(host, port);
  2051. {
  2052. auto res = cli.Get(unauth_path);
  2053. ASSERT_TRUE(res);
  2054. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2055. }
  2056. {
  2057. cli.set_digest_auth("hello", "world");
  2058. for (const auto &path : paths) {
  2059. auto res = cli.Get(path.c_str());
  2060. ASSERT_TRUE(res);
  2061. auto body = remove_whitespace(res->body);
  2062. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2063. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2064. EXPECT_EQ(StatusCode::OK_200, res->status);
  2065. }
  2066. cli.set_digest_auth("hello", "bad");
  2067. for (const auto &path : paths) {
  2068. auto res = cli.Get(path.c_str());
  2069. ASSERT_TRUE(res);
  2070. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2071. }
  2072. }
  2073. }
  2074. #endif
  2075. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2076. auto host = "google.com";
  2077. auto another_host = "example.com";
  2078. auto wrong_ip = "0.0.0.0";
  2079. #ifdef CPPHTTPLIB_SSL_ENABLED
  2080. SSLClient cli(host);
  2081. #else
  2082. Client cli(host);
  2083. #endif
  2084. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2085. auto res = cli.Get("/");
  2086. ASSERT_TRUE(res);
  2087. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2088. }
  2089. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2090. auto host = "google.com";
  2091. auto wrong_ip = "0.0.0.0";
  2092. #ifdef CPPHTTPLIB_SSL_ENABLED
  2093. SSLClient cli(host);
  2094. #else
  2095. Client cli(host);
  2096. #endif
  2097. cli.set_hostname_addr_map({{host, wrong_ip}});
  2098. auto res = cli.Get("/");
  2099. ASSERT_TRUE(!res);
  2100. EXPECT_EQ(Error::Connection, res.error());
  2101. }
  2102. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2103. auto host = "httpbingo.org";
  2104. auto path = std::string{"/absolute-redirect/3"};
  2105. #ifdef CPPHTTPLIB_SSL_ENABLED
  2106. SSLClient cli(host);
  2107. #else
  2108. Client cli(host);
  2109. #endif
  2110. cli.set_follow_location(true);
  2111. auto res = cli.Get(path);
  2112. ASSERT_TRUE(res);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. }
  2115. TEST(RedirectTest, Redirect_Online) {
  2116. auto host = "httpbingo.org";
  2117. auto path = std::string{"/redirect/3"};
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. SSLClient cli(host);
  2120. #else
  2121. Client cli(host);
  2122. #endif
  2123. cli.set_follow_location(true);
  2124. auto res = cli.Get(path);
  2125. ASSERT_TRUE(res);
  2126. EXPECT_EQ(StatusCode::OK_200, res->status);
  2127. }
  2128. TEST(RelativeRedirectTest, Redirect_Online) {
  2129. auto host = "httpbingo.org";
  2130. auto path = std::string{"/relative-redirect/3"};
  2131. #ifdef CPPHTTPLIB_SSL_ENABLED
  2132. SSLClient cli(host);
  2133. #else
  2134. Client cli(host);
  2135. #endif
  2136. cli.set_follow_location(true);
  2137. auto res = cli.Get(path);
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. }
  2141. TEST(TooManyRedirectTest, Redirect_Online) {
  2142. auto host = "httpbingo.org";
  2143. auto path = std::string{"/redirect/21"};
  2144. #ifdef CPPHTTPLIB_SSL_ENABLED
  2145. SSLClient cli(host);
  2146. #else
  2147. Client cli(host);
  2148. #endif
  2149. cli.set_follow_location(true);
  2150. auto res = cli.Get(path);
  2151. ASSERT_TRUE(!res);
  2152. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2153. }
  2154. #ifdef CPPHTTPLIB_SSL_ENABLED
  2155. TEST(YahooRedirectTest, Redirect_Online) {
  2156. Client cli("yahoo.com");
  2157. auto res = cli.Get("/");
  2158. ASSERT_TRUE(res);
  2159. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2160. cli.set_follow_location(true);
  2161. res = cli.Get("/");
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(StatusCode::OK_200, res->status);
  2164. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2165. }
  2166. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2167. #define REDIR_HOST "httpbingo.org"
  2168. #define REDIR_PATH "/redirect-to"
  2169. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2170. SSLClient cli(REDIR_HOST);
  2171. cli.set_follow_location(true);
  2172. auto res =
  2173. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. }
  2177. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2178. SSLClient cli(REDIR_HOST);
  2179. cli.set_follow_location(true);
  2180. Params params;
  2181. params.emplace("url", "http://example.com");
  2182. params.emplace("status_code", "302");
  2183. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2184. ASSERT_TRUE(res);
  2185. EXPECT_EQ(StatusCode::OK_200, res->status);
  2186. }
  2187. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2188. SSLClient cli(REDIR_HOST);
  2189. cli.set_follow_location(true);
  2190. Params params;
  2191. params.emplace("url", "http://example.com");
  2192. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2193. ASSERT_TRUE(res);
  2194. EXPECT_EQ(StatusCode::OK_200, res->status);
  2195. }
  2196. TEST(UrlWithSpace, Redirect_Online) {
  2197. SSLClient cli("edge.forgecdn.net");
  2198. cli.set_follow_location(true);
  2199. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2200. ASSERT_TRUE(res);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2203. }
  2204. #endif
  2205. #if !defined(_WIN32) && !defined(_WIN64)
  2206. TEST(ReceiveSignals, Signal) {
  2207. auto setupSignalHandlers = []() {
  2208. struct sigaction act;
  2209. sigemptyset(&act.sa_mask);
  2210. act.sa_flags = SA_SIGINFO;
  2211. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2212. switch (sig) {
  2213. case SIGINT:
  2214. default: break;
  2215. }
  2216. };
  2217. ::sigaction(SIGINT, &act, nullptr);
  2218. };
  2219. Server svr;
  2220. int port = 0;
  2221. auto thread = std::thread([&]() {
  2222. setupSignalHandlers();
  2223. port = svr.bind_to_any_port(HOST);
  2224. svr.listen_after_bind();
  2225. });
  2226. auto se = detail::scope_exit([&] {
  2227. svr.stop();
  2228. thread.join();
  2229. ASSERT_FALSE(svr.is_running());
  2230. });
  2231. svr.wait_until_ready();
  2232. ASSERT_TRUE(svr.is_running());
  2233. pthread_kill(thread.native_handle(), SIGINT);
  2234. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2235. ASSERT_TRUE(svr.is_running());
  2236. }
  2237. #endif
  2238. TEST(RedirectToDifferentPort, Redirect) {
  2239. Server svr1;
  2240. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2241. res.set_content("Hello World!", "text/plain");
  2242. });
  2243. int svr1_port = 0;
  2244. auto thread1 = std::thread([&]() {
  2245. svr1_port = svr1.bind_to_any_port(HOST);
  2246. svr1.listen_after_bind();
  2247. });
  2248. Server svr2;
  2249. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2250. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2251. });
  2252. int svr2_port = 0;
  2253. auto thread2 = std::thread([&]() {
  2254. svr2_port = svr2.bind_to_any_port(HOST);
  2255. svr2.listen_after_bind();
  2256. });
  2257. auto se = detail::scope_exit([&] {
  2258. svr2.stop();
  2259. thread2.join();
  2260. svr1.stop();
  2261. thread1.join();
  2262. ASSERT_FALSE(svr2.is_running());
  2263. ASSERT_FALSE(svr1.is_running());
  2264. });
  2265. svr1.wait_until_ready();
  2266. svr2.wait_until_ready();
  2267. Client cli("localhost", svr2_port);
  2268. cli.set_follow_location(true);
  2269. auto res = cli.Get("/2");
  2270. ASSERT_TRUE(res);
  2271. EXPECT_EQ(StatusCode::OK_200, res->status);
  2272. EXPECT_EQ("Hello World!", res->body);
  2273. }
  2274. static void
  2275. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2276. Server svr1;
  2277. std::string captured_authorization;
  2278. svr1.Get("/target", [&](const Request &req, Response &res) {
  2279. captured_authorization = req.get_header_value("Authorization");
  2280. res.set_content("OK", "text/plain");
  2281. });
  2282. int svr1_port = 0;
  2283. auto thread1 = std::thread([&]() {
  2284. svr1_port = svr1.bind_to_any_port(HOST);
  2285. svr1.listen_after_bind();
  2286. });
  2287. Server svr2;
  2288. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2289. res.set_redirect(
  2290. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2291. });
  2292. int svr2_port = 0;
  2293. auto thread2 = std::thread([&]() {
  2294. svr2_port = svr2.bind_to_any_port(HOST);
  2295. svr2.listen_after_bind();
  2296. });
  2297. auto se = detail::scope_exit([&] {
  2298. svr2.stop();
  2299. thread2.join();
  2300. svr1.stop();
  2301. thread1.join();
  2302. ASSERT_FALSE(svr2.is_running());
  2303. ASSERT_FALSE(svr1.is_running());
  2304. });
  2305. svr1.wait_until_ready();
  2306. svr2.wait_until_ready();
  2307. Client cli("localhost", svr2_port);
  2308. cli.set_follow_location(true);
  2309. set_auth(cli);
  2310. auto res = cli.Get("/redir");
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ(StatusCode::OK_200, res->status);
  2313. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2314. EXPECT_TRUE(captured_authorization.empty());
  2315. }
  2316. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2317. TestDoNotForwardCredentialsOnRedirect(
  2318. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2319. }
  2320. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2321. TestDoNotForwardCredentialsOnRedirect(
  2322. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2323. }
  2324. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2325. Server svr1;
  2326. std::string captured_cookie;
  2327. bool target_hit = false;
  2328. svr1.Get("/target", [&](const Request &req, Response &res) {
  2329. captured_cookie = req.get_header_value("Cookie");
  2330. target_hit = true;
  2331. res.set_content("OK", "text/plain");
  2332. });
  2333. int svr1_port = 0;
  2334. auto thread1 = std::thread([&]() {
  2335. svr1_port = svr1.bind_to_any_port(HOST);
  2336. svr1.listen_after_bind();
  2337. });
  2338. Server svr2;
  2339. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2340. res.set_redirect(
  2341. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2342. });
  2343. int svr2_port = 0;
  2344. auto thread2 = std::thread([&]() {
  2345. svr2_port = svr2.bind_to_any_port(HOST);
  2346. svr2.listen_after_bind();
  2347. });
  2348. auto se = detail::scope_exit([&] {
  2349. svr2.stop();
  2350. thread2.join();
  2351. svr1.stop();
  2352. thread1.join();
  2353. ASSERT_FALSE(svr2.is_running());
  2354. ASSERT_FALSE(svr1.is_running());
  2355. });
  2356. svr1.wait_until_ready();
  2357. svr2.wait_until_ready();
  2358. Client cli("localhost", svr2_port);
  2359. cli.set_follow_location(true);
  2360. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2361. auto res = cli.Get("/redir", headers);
  2362. ASSERT_TRUE(res);
  2363. EXPECT_EQ(StatusCode::OK_200, res->status);
  2364. EXPECT_TRUE(target_hit);
  2365. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2366. EXPECT_TRUE(captured_cookie.empty());
  2367. }
  2368. TEST(RedirectToSamePort, ForwardCookie) {
  2369. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2370. // header so that ordinary session flows keep working.
  2371. Server svr;
  2372. std::string captured_cookie;
  2373. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2374. res.set_redirect("/target", 302);
  2375. });
  2376. svr.Get("/target", [&](const Request &req, Response &res) {
  2377. captured_cookie = req.get_header_value("Cookie");
  2378. res.set_content("OK", "text/plain");
  2379. });
  2380. auto port = svr.bind_to_any_port(HOST);
  2381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2382. auto se = detail::scope_exit([&] {
  2383. svr.stop();
  2384. thread.join();
  2385. ASSERT_FALSE(svr.is_running());
  2386. });
  2387. svr.wait_until_ready();
  2388. Client cli(HOST, port);
  2389. cli.set_follow_location(true);
  2390. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2391. auto res = cli.Get("/redir", headers);
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(StatusCode::OK_200, res->status);
  2394. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2395. }
  2396. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2397. Server svr;
  2398. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2399. // Port number that overflows int — should not crash
  2400. res.set_redirect("http://localhost:99999999999999999999/target");
  2401. });
  2402. auto port = svr.bind_to_any_port(HOST);
  2403. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2404. auto se = detail::scope_exit([&] {
  2405. svr.stop();
  2406. thread.join();
  2407. ASSERT_FALSE(svr.is_running());
  2408. });
  2409. svr.wait_until_ready();
  2410. Client cli(HOST, port);
  2411. cli.set_follow_location(true);
  2412. auto res = cli.Get("/redir");
  2413. // Should fail gracefully, not crash (no valid response due to bad port)
  2414. EXPECT_FALSE(res);
  2415. }
  2416. TEST(RedirectFromPageWithContent, Redirect) {
  2417. Server svr;
  2418. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2419. res.set_content("___", "text/plain");
  2420. res.set_redirect("/2");
  2421. });
  2422. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2423. res.set_content("Hello World!", "text/plain");
  2424. });
  2425. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2426. auto se = detail::scope_exit([&] {
  2427. svr.stop();
  2428. th.join();
  2429. ASSERT_FALSE(svr.is_running());
  2430. });
  2431. svr.wait_until_ready();
  2432. {
  2433. Client cli("localhost", PORT);
  2434. cli.set_follow_location(true);
  2435. std::string body;
  2436. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2437. body.append(data, data_length);
  2438. return true;
  2439. });
  2440. ASSERT_TRUE(res);
  2441. EXPECT_EQ(StatusCode::OK_200, res->status);
  2442. EXPECT_EQ("Hello World!", body);
  2443. }
  2444. {
  2445. Client cli("localhost", PORT);
  2446. std::string body;
  2447. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2448. body.append(data, data_length);
  2449. return true;
  2450. });
  2451. ASSERT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::Found_302, res->status);
  2453. EXPECT_EQ("___", body);
  2454. }
  2455. }
  2456. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2457. Server svr;
  2458. auto port_str = std::to_string(PORT);
  2459. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2460. auto expected_host = "[::1]:" + port_str;
  2461. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2462. res.set_content("___", "text/plain");
  2463. // res.set_redirect("/2");
  2464. res.set_redirect(redirect_url);
  2465. });
  2466. svr.Get("/2", [&](const Request &req, Response &res) {
  2467. auto host_header = req.headers.find("Host");
  2468. ASSERT_TRUE(host_header != req.headers.end());
  2469. EXPECT_EQ(expected_host, host_header->second);
  2470. res.set_content("Hello World!", "text/plain");
  2471. });
  2472. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. th.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2479. // actually starts anything, so the condition !svr.is_running() will
  2480. // always remain true, and the loop never stops.
  2481. // This basically counts how many milliseconds have passed since the
  2482. // call to svr.listen(), and if after 5 seconds nothing started yet
  2483. // aborts the test.
  2484. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2485. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2486. ASSERT_LT(milliseconds, 5000U);
  2487. }
  2488. {
  2489. Client cli("::1", PORT);
  2490. cli.set_follow_location(true);
  2491. std::string body;
  2492. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2493. body.append(data, data_length);
  2494. return true;
  2495. });
  2496. ASSERT_TRUE(res);
  2497. EXPECT_EQ(StatusCode::OK_200, res->status);
  2498. EXPECT_EQ("Hello World!", body);
  2499. }
  2500. {
  2501. Client cli("::1", PORT);
  2502. std::string body;
  2503. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2504. body.append(data, data_length);
  2505. return true;
  2506. });
  2507. ASSERT_TRUE(res);
  2508. EXPECT_EQ(StatusCode::Found_302, res->status);
  2509. EXPECT_EQ("___", body);
  2510. }
  2511. }
  2512. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2513. Server svr;
  2514. svr.Get("/foo", [](const Request &req, Response &res) {
  2515. auto a = req.params.find("a");
  2516. if (a != req.params.end()) {
  2517. res.set_content((*a).second, "text/plain");
  2518. res.status = StatusCode::OK_200;
  2519. } else {
  2520. res.status = StatusCode::BadRequest_400;
  2521. }
  2522. });
  2523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2524. auto se = detail::scope_exit([&] {
  2525. svr.stop();
  2526. thread.join();
  2527. ASSERT_FALSE(svr.is_running());
  2528. });
  2529. svr.wait_until_ready();
  2530. {
  2531. Client cli(HOST, PORT);
  2532. cli.set_path_encode(false);
  2533. auto res = cli.Get("/foo?a=explicitly+encoded");
  2534. ASSERT_TRUE(res);
  2535. EXPECT_EQ(StatusCode::OK_200, res->status);
  2536. // This expects it back with a space, as the `+` won't have been
  2537. // url-encoded, and server-side the params get decoded turning `+`
  2538. // into spaces.
  2539. EXPECT_EQ("explicitly encoded", res->body);
  2540. }
  2541. }
  2542. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2543. // When path encoding is disabled the client must transmit the supplied
  2544. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2545. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2546. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2547. // than a space (0x20). Assert on the raw wire target to catch this.
  2548. Server svr;
  2549. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2550. svr.Get("/foo", [&](const Request &req, Response &res) {
  2551. EXPECT_EQ(expected_target, req.target);
  2552. res.status = StatusCode::OK_200;
  2553. });
  2554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2555. auto se = detail::scope_exit([&] {
  2556. svr.stop();
  2557. thread.join();
  2558. ASSERT_FALSE(svr.is_running());
  2559. });
  2560. svr.wait_until_ready();
  2561. {
  2562. Client cli(HOST, PORT);
  2563. cli.set_path_encode(false);
  2564. auto res = cli.Get(expected_target.c_str());
  2565. ASSERT_TRUE(res);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. }
  2569. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2570. Server svr;
  2571. svr.Get("/", [](const Request &req, Response &) {
  2572. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2573. });
  2574. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2575. auto se = detail::scope_exit([&] {
  2576. svr.stop();
  2577. thread.join();
  2578. ASSERT_FALSE(svr.is_running());
  2579. });
  2580. svr.wait_until_ready();
  2581. {
  2582. Client cli(HOST, PORT);
  2583. cli.set_path_encode(false);
  2584. auto res = cli.Get("/?something=%0A");
  2585. ASSERT_TRUE(res);
  2586. EXPECT_EQ(StatusCode::OK_200, res->status);
  2587. }
  2588. }
  2589. TEST(BindServerTest, BindDualStack) {
  2590. Server svr;
  2591. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2592. res.set_content("Hello World!", "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. {
  2602. Client cli("127.0.0.1", PORT);
  2603. auto res = cli.Get("/1");
  2604. ASSERT_TRUE(res);
  2605. EXPECT_EQ(StatusCode::OK_200, res->status);
  2606. EXPECT_EQ("Hello World!", res->body);
  2607. }
  2608. {
  2609. Client cli("::1", PORT);
  2610. auto res = cli.Get("/1");
  2611. ASSERT_TRUE(res);
  2612. EXPECT_EQ(StatusCode::OK_200, res->status);
  2613. EXPECT_EQ("Hello World!", res->body);
  2614. }
  2615. }
  2616. TEST(BindServerTest, BindAndListenSeparately) {
  2617. Server svr;
  2618. int port = svr.bind_to_any_port("0.0.0.0");
  2619. ASSERT_TRUE(svr.is_valid());
  2620. ASSERT_TRUE(port > 0);
  2621. svr.stop();
  2622. }
  2623. #ifdef CPPHTTPLIB_SSL_ENABLED
  2624. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2626. CLIENT_CA_CERT_DIR);
  2627. int port = svr.bind_to_any_port("0.0.0.0");
  2628. ASSERT_TRUE(svr.is_valid());
  2629. ASSERT_TRUE(port > 0);
  2630. svr.stop();
  2631. }
  2632. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2633. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2634. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2635. int port = svr.bind_to_any_port("0.0.0.0");
  2636. ASSERT_TRUE(svr.is_valid());
  2637. ASSERT_TRUE(port > 0);
  2638. svr.stop();
  2639. }
  2640. TEST(BindServerTest, UpdateCertsPem) {
  2641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2642. int port = svr.bind_to_any_port("0.0.0.0");
  2643. ASSERT_TRUE(svr.is_valid());
  2644. ASSERT_TRUE(port > 0);
  2645. // Read PEM files
  2646. std::string cert_pem, key_pem, ca_pem;
  2647. read_file(SERVER_CERT_FILE, cert_pem);
  2648. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2649. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2650. // Update server certificates using PEM API
  2651. ASSERT_TRUE(
  2652. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2653. ASSERT_TRUE(svr.is_valid());
  2654. svr.stop();
  2655. }
  2656. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2657. // Start server with client CA (enables client auth)
  2658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2659. ASSERT_TRUE(svr.is_valid());
  2660. bool handler_called = false;
  2661. svr.Get("/test", [&](const Request &req, Response &res) {
  2662. handler_called = true;
  2663. // Verify client certificate is present
  2664. auto cert = req.peer_cert();
  2665. EXPECT_TRUE(static_cast<bool>(cert));
  2666. res.set_content("ok", "text/plain");
  2667. });
  2668. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2669. auto se = detail::scope_exit([&] {
  2670. svr.stop();
  2671. t.join();
  2672. ASSERT_FALSE(svr.is_running());
  2673. });
  2674. svr.wait_until_ready();
  2675. // Read PEM files
  2676. std::string cert_pem, key_pem, ca_pem;
  2677. read_file(SERVER_CERT_FILE, cert_pem);
  2678. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2679. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2680. // Update server certificates and client CA using PEM API while server running
  2681. ASSERT_TRUE(
  2682. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2683. // Connect with client certificate
  2684. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2685. cli.enable_server_certificate_verification(false);
  2686. cli.set_connection_timeout(30);
  2687. auto res = cli.Get("/test");
  2688. ASSERT_TRUE(res);
  2689. ASSERT_EQ(StatusCode::OK_200, res->status);
  2690. ASSERT_TRUE(handler_called);
  2691. EXPECT_EQ("ok", res->body);
  2692. }
  2693. #endif
  2694. TEST(ErrorHandlerTest, ContentLength) {
  2695. Server svr;
  2696. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2697. res.status = StatusCode::OK_200;
  2698. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2699. "text/html"); // <= Content-Length still 13
  2700. });
  2701. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2702. res.set_content("Hello World!\n", "text/plain");
  2703. res.status = 524;
  2704. });
  2705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2706. auto se = detail::scope_exit([&] {
  2707. svr.stop();
  2708. thread.join();
  2709. ASSERT_FALSE(svr.is_running());
  2710. });
  2711. svr.wait_until_ready();
  2712. {
  2713. Client cli(HOST, PORT);
  2714. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2715. ASSERT_TRUE(res);
  2716. EXPECT_EQ(StatusCode::OK_200, res->status);
  2717. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2718. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2719. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2720. }
  2721. }
  2722. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2723. TEST(ExceptionTest, WithoutExceptionHandler) {
  2724. Server svr;
  2725. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2726. throw std::runtime_error("exception...");
  2727. });
  2728. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2729. throw std::runtime_error("exception\r\n...");
  2730. });
  2731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2732. auto se = detail::scope_exit([&] {
  2733. svr.stop();
  2734. listen_thread.join();
  2735. ASSERT_FALSE(svr.is_running());
  2736. });
  2737. svr.wait_until_ready();
  2738. Client cli("localhost", PORT);
  2739. {
  2740. auto res = cli.Get("/exception");
  2741. ASSERT_TRUE(res);
  2742. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2743. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2744. }
  2745. {
  2746. auto res = cli.Get("/unknown");
  2747. ASSERT_TRUE(res);
  2748. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2749. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2750. }
  2751. }
  2752. TEST(ExceptionTest, WithExceptionHandler) {
  2753. Server svr;
  2754. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2755. std::exception_ptr ep) {
  2756. EXPECT_FALSE(ep == nullptr);
  2757. try {
  2758. std::rethrow_exception(ep);
  2759. } catch (std::exception &e) {
  2760. EXPECT_EQ("abc", std::string(e.what()));
  2761. } catch (...) {}
  2762. res.status = StatusCode::InternalServerError_500;
  2763. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2764. "text/html"); // <= Content-Length still 13 at this point
  2765. });
  2766. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!\n", "text/plain");
  2768. throw std::runtime_error("abc");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. for (size_t i = 0; i < 10; i++) {
  2778. Client cli(HOST, PORT);
  2779. for (size_t j = 0; j < 100; j++) {
  2780. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2781. ASSERT_TRUE(res);
  2782. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2783. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2784. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2785. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2786. }
  2787. cli.set_keep_alive(true);
  2788. for (size_t j = 0; j < 100; j++) {
  2789. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2790. ASSERT_TRUE(res);
  2791. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2792. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2793. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2794. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2795. }
  2796. }
  2797. }
  2798. TEST(ExceptionTest, AndErrorHandler) {
  2799. Server svr;
  2800. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2801. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2802. });
  2803. svr.set_exception_handler(
  2804. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2805. EXPECT_FALSE(ep == nullptr);
  2806. try {
  2807. std::rethrow_exception(ep);
  2808. } catch (std::exception &e) {
  2809. res.set_content(e.what(), "text/html");
  2810. } catch (...) {}
  2811. res.status = StatusCode::InternalServerError_500;
  2812. });
  2813. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2814. throw std::runtime_error("EXCEPTION");
  2815. });
  2816. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2817. res.set_content("ERROR", "text/html");
  2818. res.status = StatusCode::InternalServerError_500;
  2819. });
  2820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2821. auto se = detail::scope_exit([&] {
  2822. svr.stop();
  2823. thread.join();
  2824. ASSERT_FALSE(svr.is_running());
  2825. });
  2826. svr.wait_until_ready();
  2827. Client cli(HOST, PORT);
  2828. {
  2829. auto res = cli.Get("/exception");
  2830. ASSERT_TRUE(res);
  2831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2832. EXPECT_EQ("EXCEPTION", res->body);
  2833. }
  2834. {
  2835. auto res = cli.Get("/error");
  2836. ASSERT_TRUE(res);
  2837. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2838. EXPECT_EQ("ERROR", res->body);
  2839. }
  2840. {
  2841. auto res = cli.Get("/invalid");
  2842. ASSERT_TRUE(res);
  2843. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2844. EXPECT_EQ("NOT_FOUND", res->body);
  2845. }
  2846. }
  2847. #endif
  2848. TEST(NoContentTest, ContentLength) {
  2849. Server svr;
  2850. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2851. res.status = StatusCode::NoContent_204;
  2852. });
  2853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2854. auto se = detail::scope_exit([&] {
  2855. svr.stop();
  2856. thread.join();
  2857. ASSERT_FALSE(svr.is_running());
  2858. });
  2859. svr.wait_until_ready();
  2860. {
  2861. Client cli(HOST, PORT);
  2862. auto res = cli.Get("/hi");
  2863. ASSERT_TRUE(res);
  2864. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2865. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2866. }
  2867. }
  2868. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2869. #ifdef CPPHTTPLIB_SSL_ENABLED
  2870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2871. ASSERT_TRUE(svr.is_valid());
  2872. #else
  2873. Server svr;
  2874. #endif
  2875. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2876. if (req.path == "/routing_handler") {
  2877. res.set_header("PRE_ROUTING", "on");
  2878. res.set_content("Routing Handler", "text/plain");
  2879. return httplib::Server::HandlerResponse::Handled;
  2880. }
  2881. return httplib::Server::HandlerResponse::Unhandled;
  2882. });
  2883. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2884. res.set_content("Error", "text/html");
  2885. });
  2886. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2887. if (req.path == "/routing_handler") {
  2888. res.set_header("POST_ROUTING", "on");
  2889. }
  2890. });
  2891. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2892. res.set_content("Hello World!\n", "text/plain");
  2893. });
  2894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2895. auto se = detail::scope_exit([&] {
  2896. svr.stop();
  2897. thread.join();
  2898. ASSERT_FALSE(svr.is_running());
  2899. });
  2900. svr.wait_until_ready();
  2901. {
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. SSLClient cli(HOST, PORT);
  2904. cli.enable_server_certificate_verification(false);
  2905. #else
  2906. Client cli(HOST, PORT);
  2907. #endif
  2908. auto res = cli.Get("/routing_handler");
  2909. ASSERT_TRUE(res);
  2910. EXPECT_EQ(StatusCode::OK_200, res->status);
  2911. EXPECT_EQ("Routing Handler", res->body);
  2912. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2913. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2914. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2915. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2916. }
  2917. {
  2918. #ifdef CPPHTTPLIB_SSL_ENABLED
  2919. SSLClient cli(HOST, PORT);
  2920. cli.enable_server_certificate_verification(false);
  2921. #else
  2922. Client cli(HOST, PORT);
  2923. #endif
  2924. auto res = cli.Get("/hi");
  2925. ASSERT_TRUE(res);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. EXPECT_EQ("Hello World!\n", res->body);
  2928. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2929. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2930. }
  2931. {
  2932. #ifdef CPPHTTPLIB_SSL_ENABLED
  2933. SSLClient cli(HOST, PORT);
  2934. cli.enable_server_certificate_verification(false);
  2935. #else
  2936. Client cli(HOST, PORT);
  2937. #endif
  2938. auto res = cli.Get("/aaa");
  2939. ASSERT_TRUE(res);
  2940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2941. EXPECT_EQ("Error", res->body);
  2942. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2943. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2944. }
  2945. }
  2946. TEST(RequestHandlerTest, PreRequestHandler) {
  2947. auto route_path = "/user/:user";
  2948. Server svr;
  2949. svr.Get("/hi", [](const Request &, Response &res) {
  2950. res.set_content("hi", "text/plain");
  2951. });
  2952. svr.Get(route_path, [](const Request &req, Response &res) {
  2953. res.set_content(req.path_params.at("user"), "text/plain");
  2954. });
  2955. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2956. if (req.matched_route == route_path) {
  2957. auto user = req.path_params.at("user");
  2958. if (user != "john") {
  2959. res.status = StatusCode::Forbidden_403;
  2960. res.set_content("error", "text/html");
  2961. return Server::HandlerResponse::Handled;
  2962. }
  2963. }
  2964. return Server::HandlerResponse::Unhandled;
  2965. });
  2966. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2967. auto se = detail::scope_exit([&] {
  2968. svr.stop();
  2969. thread.join();
  2970. ASSERT_FALSE(svr.is_running());
  2971. });
  2972. svr.wait_until_ready();
  2973. Client cli(HOST, PORT);
  2974. {
  2975. auto res = cli.Get("/hi");
  2976. ASSERT_TRUE(res);
  2977. EXPECT_EQ(StatusCode::OK_200, res->status);
  2978. EXPECT_EQ("hi", res->body);
  2979. }
  2980. {
  2981. auto res = cli.Get("/user/john");
  2982. ASSERT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("john", res->body);
  2985. }
  2986. {
  2987. auto res = cli.Get("/user/invalid-user");
  2988. ASSERT_TRUE(res);
  2989. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2990. EXPECT_EQ("error", res->body);
  2991. }
  2992. }
  2993. // The pre-request handler must run before the request body is read, so a
  2994. // rejected request never forces the server to buffer a (potentially large)
  2995. // body. Here the posted body is larger than the payload limit: if the body
  2996. // were read first the server would answer 413, but because the pre-request
  2997. // handler runs first it answers 403 and the body is never read.
  2998. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2999. Server svr;
  3000. svr.set_payload_max_length(8);
  3001. auto handler_ran = false;
  3002. svr.Post("/reject", [&](const Request &req, Response &res) {
  3003. handler_ran = true;
  3004. res.set_content(req.body, "text/plain");
  3005. });
  3006. svr.Post("/accept", [](const Request &req, Response &res) {
  3007. res.set_content(req.body, "text/plain");
  3008. });
  3009. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3010. if (req.matched_route == "/reject") {
  3011. res.status = StatusCode::Forbidden_403;
  3012. res.set_content("denied", "text/plain");
  3013. return Server::HandlerResponse::Handled;
  3014. }
  3015. return Server::HandlerResponse::Unhandled;
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. Client cli(HOST, PORT);
  3025. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3026. // rejects with 403 before the body is read, so 413 is never reached.
  3027. {
  3028. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3029. ASSERT_TRUE(res);
  3030. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3031. EXPECT_EQ("denied", res->body);
  3032. EXPECT_FALSE(handler_ran);
  3033. }
  3034. // An approved route still reads the body and enforces the payload limit.
  3035. {
  3036. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3037. ASSERT_TRUE(res);
  3038. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3039. }
  3040. }
  3041. TEST(UserDataTest, BasicOperations) {
  3042. httplib::UserData ud;
  3043. // Initially empty
  3044. EXPECT_FALSE(ud.has("key"));
  3045. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3046. // set and get
  3047. ud.set("key", 42);
  3048. EXPECT_TRUE(ud.has("key"));
  3049. auto *p = ud.get<int>("key");
  3050. ASSERT_NE(nullptr, p);
  3051. EXPECT_EQ(42, *p);
  3052. // Type mismatch → nullptr
  3053. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3054. // Overwrite with different type
  3055. ud.set("key", std::string("hello"));
  3056. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3057. auto *s = ud.get<std::string>("key");
  3058. ASSERT_NE(nullptr, s);
  3059. EXPECT_EQ("hello", *s);
  3060. // erase
  3061. ud.erase("key");
  3062. EXPECT_FALSE(ud.has("key"));
  3063. // clear
  3064. ud.set("a", 1);
  3065. ud.set("b", 2);
  3066. ud.clear();
  3067. EXPECT_FALSE(ud.has("a"));
  3068. EXPECT_FALSE(ud.has("b"));
  3069. }
  3070. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3071. struct AuthCtx {
  3072. std::string user_id;
  3073. };
  3074. Server svr;
  3075. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3076. res.user_data.set("auth", AuthCtx{"alice"});
  3077. return Server::HandlerResponse::Unhandled;
  3078. });
  3079. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3080. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3081. ASSERT_NE(nullptr, ctx);
  3082. res.set_content("Hello " + ctx->user_id, "text/plain");
  3083. });
  3084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3085. auto se = detail::scope_exit([&] {
  3086. svr.stop();
  3087. thread.join();
  3088. ASSERT_FALSE(svr.is_running());
  3089. });
  3090. svr.wait_until_ready();
  3091. Client cli(HOST, PORT);
  3092. auto res = cli.Get("/me");
  3093. ASSERT_TRUE(res);
  3094. EXPECT_EQ(StatusCode::OK_200, res->status);
  3095. EXPECT_EQ("Hello alice", res->body);
  3096. }
  3097. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3098. struct RoleCtx {
  3099. std::string role;
  3100. };
  3101. Server svr;
  3102. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3103. res.user_data.set("role", RoleCtx{"admin"});
  3104. return Server::HandlerResponse::Unhandled;
  3105. });
  3106. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3107. auto *ctx = res.user_data.get<RoleCtx>("role");
  3108. ASSERT_NE(nullptr, ctx);
  3109. res.set_content(ctx->role, "text/plain");
  3110. });
  3111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3112. auto se = detail::scope_exit([&] {
  3113. svr.stop();
  3114. thread.join();
  3115. ASSERT_FALSE(svr.is_running());
  3116. });
  3117. svr.wait_until_ready();
  3118. Client cli(HOST, PORT);
  3119. auto res = cli.Get("/role");
  3120. ASSERT_TRUE(res);
  3121. EXPECT_EQ(StatusCode::OK_200, res->status);
  3122. EXPECT_EQ("admin", res->body);
  3123. }
  3124. TEST(InvalidFormatTest, StatusCode) {
  3125. Server svr;
  3126. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3127. res.set_content("Hello World!\n", "text/plain");
  3128. res.status = 9999; // Status should be a three-digit code...
  3129. });
  3130. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3131. auto se = detail::scope_exit([&] {
  3132. svr.stop();
  3133. thread.join();
  3134. ASSERT_FALSE(svr.is_running());
  3135. });
  3136. svr.wait_until_ready();
  3137. {
  3138. Client cli(HOST, PORT);
  3139. auto res = cli.Get("/hi");
  3140. ASSERT_FALSE(res);
  3141. }
  3142. }
  3143. TEST(URLFragmentTest, WithFragment) {
  3144. Server svr;
  3145. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3146. EXPECT_TRUE(req.target == "/hi");
  3147. });
  3148. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. {
  3156. Client cli(HOST, PORT);
  3157. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3158. EXPECT_TRUE(res);
  3159. EXPECT_EQ(StatusCode::OK_200, res->status);
  3160. res = cli.Get("/hi%23key1=val1=key2=val2");
  3161. EXPECT_TRUE(res);
  3162. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3163. }
  3164. }
  3165. TEST(HeaderWriter, SetHeaderWriter) {
  3166. Server svr;
  3167. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3168. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3169. return detail::write_headers(strm, hdrs);
  3170. });
  3171. svr.Get("/hi", [](const Request &req, Response &res) {
  3172. auto it = req.headers.find("CustomClientHeader");
  3173. EXPECT_TRUE(it != req.headers.end());
  3174. EXPECT_EQ(it->second, "CustomClientValue");
  3175. res.set_content("Hello World!\n", "text/plain");
  3176. });
  3177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3178. auto se = detail::scope_exit([&] {
  3179. svr.stop();
  3180. thread.join();
  3181. ASSERT_FALSE(svr.is_running());
  3182. });
  3183. svr.wait_until_ready();
  3184. {
  3185. Client cli(HOST, PORT);
  3186. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3187. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3188. return detail::write_headers(strm, hdrs);
  3189. });
  3190. auto res = cli.Get("/hi");
  3191. EXPECT_TRUE(res);
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. auto it = res->headers.find("CustomServerHeader");
  3194. EXPECT_TRUE(it != res->headers.end());
  3195. EXPECT_EQ(it->second, "CustomServerValue");
  3196. }
  3197. }
  3198. class ServerTest : public ::testing::Test {
  3199. protected:
  3200. ServerTest()
  3201. : cli_(HOST, PORT)
  3202. #ifdef CPPHTTPLIB_SSL_ENABLED
  3203. ,
  3204. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3205. #endif
  3206. {
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. cli_.enable_server_certificate_verification(false);
  3209. #endif
  3210. // Allow LARGE_DATA (100MB) responses
  3211. cli_.set_payload_max_length(200 * 1024 * 1024);
  3212. }
  3213. virtual void SetUp() {
  3214. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3215. svr_.set_payload_max_length(200 * 1024 * 1024);
  3216. svr_.set_mount_point("/", "./www");
  3217. svr_.set_mount_point("/mount", "./www2");
  3218. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3219. svr_.Get("/hi",
  3220. [&](const Request & /*req*/, Response &res) {
  3221. res.set_content("Hello World!", "text/plain");
  3222. })
  3223. .Get("/file_content",
  3224. [&](const Request & /*req*/, Response &res) {
  3225. res.set_file_content("./www/dir/test.html");
  3226. })
  3227. .Get("/file_content_with_content_type",
  3228. [&](const Request & /*req*/, Response &res) {
  3229. res.set_file_content("./www/file", "text/plain");
  3230. })
  3231. .Get("/invalid_file_content",
  3232. [&](const Request & /*req*/, Response &res) {
  3233. res.set_file_content("./www/dir/invalid_file_path");
  3234. })
  3235. .Get("/http_response_splitting",
  3236. [&](const Request & /*req*/, Response &res) {
  3237. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3238. EXPECT_EQ(0U, res.headers.size());
  3239. EXPECT_FALSE(res.has_header("a"));
  3240. res.set_header("a", "1\nSet-Cookie: a=1");
  3241. EXPECT_EQ(0U, res.headers.size());
  3242. EXPECT_FALSE(res.has_header("a"));
  3243. res.set_header("a", "1\rSet-Cookie: a=1");
  3244. EXPECT_EQ(0U, res.headers.size());
  3245. EXPECT_FALSE(res.has_header("a"));
  3246. res.set_header("a\r\nb", "0");
  3247. EXPECT_EQ(0U, res.headers.size());
  3248. EXPECT_FALSE(res.has_header("a"));
  3249. res.set_header("a\rb", "0");
  3250. EXPECT_EQ(0U, res.headers.size());
  3251. EXPECT_FALSE(res.has_header("a"));
  3252. res.set_header("a\nb", "0");
  3253. EXPECT_EQ(0U, res.headers.size());
  3254. EXPECT_FALSE(res.has_header("a"));
  3255. res.set_redirect("1\r\nSet-Cookie: a=1");
  3256. EXPECT_EQ(0U, res.headers.size());
  3257. EXPECT_FALSE(res.has_header("Location"));
  3258. })
  3259. .Get("/slow",
  3260. [&](const Request & /*req*/, Response &res) {
  3261. std::this_thread::sleep_for(std::chrono::seconds(4));
  3262. res.set_content("slow", "text/plain");
  3263. })
  3264. #if 0
  3265. .Post("/slowpost",
  3266. [&](const Request & /*req*/, Response &res) {
  3267. std::this_thread::sleep_for(std::chrono::seconds(2));
  3268. res.set_content("slow", "text/plain");
  3269. })
  3270. #endif
  3271. .Get("/remote_addr",
  3272. [&](const Request &req, Response &res) {
  3273. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3274. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3275. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3276. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3277. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3278. #endif
  3279. res.set_content(req.remote_addr, "text/plain");
  3280. })
  3281. .Get("/local_addr",
  3282. [&](const Request &req, Response &res) {
  3283. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3284. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3285. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3286. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3287. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3288. #endif
  3289. auto local_addr = req.local_addr;
  3290. auto local_port = std::to_string(req.local_port);
  3291. res.set_content(local_addr.append(":").append(local_port),
  3292. "text/plain");
  3293. })
  3294. .Get("/endwith%",
  3295. [&](const Request & /*req*/, Response &res) {
  3296. res.set_content("Hello World!", "text/plain");
  3297. })
  3298. .Get("/a\\+\\+b",
  3299. [&](const Request &req, Response &res) {
  3300. ASSERT_TRUE(req.has_param("a +b"));
  3301. auto val = req.get_param_value("a +b");
  3302. res.set_content(val, "text/plain");
  3303. })
  3304. .Get("/", [&](const Request & /*req*/,
  3305. Response &res) { res.set_redirect("/hi"); })
  3306. .Post("/1",
  3307. [](const Request & /*req*/, Response &res) {
  3308. res.set_redirect("/2", StatusCode::SeeOther_303);
  3309. })
  3310. .Get("/2",
  3311. [](const Request & /*req*/, Response &res) {
  3312. res.set_content("redirected.", "text/plain");
  3313. res.status = StatusCode::OK_200;
  3314. })
  3315. .Post("/person",
  3316. [&](const Request &req, Response &res) {
  3317. if (req.has_param("name") && req.has_param("note")) {
  3318. persons_[req.get_param_value("name")] =
  3319. req.get_param_value("note");
  3320. } else {
  3321. res.status = StatusCode::BadRequest_400;
  3322. }
  3323. })
  3324. .Put("/person",
  3325. [&](const Request &req, Response &res) {
  3326. if (req.has_param("name") && req.has_param("note")) {
  3327. persons_[req.get_param_value("name")] =
  3328. req.get_param_value("note");
  3329. } else {
  3330. res.status = StatusCode::BadRequest_400;
  3331. }
  3332. })
  3333. .Get("/person/(.*)",
  3334. [&](const Request &req, Response &res) {
  3335. string name = req.matches[1];
  3336. if (persons_.find(name) != persons_.end()) {
  3337. auto note = persons_[name];
  3338. res.set_content(note, "text/plain");
  3339. } else {
  3340. res.status = StatusCode::NotFound_404;
  3341. }
  3342. })
  3343. .Delete("/person",
  3344. [&](const Request &req, Response &res) {
  3345. if (req.has_param("name")) {
  3346. string name = req.get_param_value("name");
  3347. if (persons_.find(name) != persons_.end()) {
  3348. persons_.erase(name);
  3349. res.set_content("DELETED", "text/plain");
  3350. } else {
  3351. res.status = StatusCode::NotFound_404;
  3352. }
  3353. } else {
  3354. res.status = StatusCode::BadRequest_400;
  3355. }
  3356. })
  3357. .Post("/x-www-form-urlencoded-json",
  3358. [&](const Request &req, Response &res) {
  3359. auto json = req.get_param_value("json");
  3360. ASSERT_EQ(JSON_DATA, json);
  3361. res.set_content(json, "appliation/json");
  3362. res.status = StatusCode::OK_200;
  3363. })
  3364. .Get("/streamed-chunked",
  3365. [&](const Request & /*req*/, Response &res) {
  3366. res.set_chunked_content_provider(
  3367. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3368. sink.os << "123";
  3369. sink.os << "456";
  3370. sink.os << "789";
  3371. sink.done();
  3372. return true;
  3373. });
  3374. })
  3375. .Get("/streamed-chunked-with-prohibited-trailer",
  3376. [&](const Request & /*req*/, Response &res) {
  3377. auto i = new int(0);
  3378. // Declare both a prohibited trailer (Content-Length) and an
  3379. // allowed one
  3380. res.set_header("Trailer", "Content-Length, X-Allowed");
  3381. res.set_chunked_content_provider(
  3382. "text/plain",
  3383. [i](size_t /*offset*/, DataSink &sink) {
  3384. switch (*i) {
  3385. case 0: sink.os << "123"; break;
  3386. case 1: sink.os << "456"; break;
  3387. case 2: sink.os << "789"; break;
  3388. case 3: {
  3389. sink.done_with_trailer(
  3390. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3391. } break;
  3392. }
  3393. (*i)++;
  3394. return true;
  3395. },
  3396. [i](bool success) {
  3397. EXPECT_TRUE(success);
  3398. delete i;
  3399. });
  3400. })
  3401. .Get("/streamed-chunked2",
  3402. [&](const Request & /*req*/, Response &res) {
  3403. auto i = new int(0);
  3404. res.set_chunked_content_provider(
  3405. "text/plain",
  3406. [i](size_t /*offset*/, DataSink &sink) {
  3407. switch (*i) {
  3408. case 0: sink.os << "123"; break;
  3409. case 1: sink.os << "456"; break;
  3410. case 2: sink.os << "789"; break;
  3411. case 3: sink.done(); break;
  3412. }
  3413. (*i)++;
  3414. return true;
  3415. },
  3416. [i](bool success) {
  3417. EXPECT_TRUE(success);
  3418. delete i;
  3419. });
  3420. })
  3421. .Get("/streamed-chunked-with-trailer",
  3422. [&](const Request & /*req*/, Response &res) {
  3423. auto i = new int(0);
  3424. res.set_header("Trailer", "Dummy1, Dummy2");
  3425. res.set_chunked_content_provider(
  3426. "text/plain",
  3427. [i](size_t /*offset*/, DataSink &sink) {
  3428. switch (*i) {
  3429. case 0: sink.os << "123"; break;
  3430. case 1: sink.os << "456"; break;
  3431. case 2: sink.os << "789"; break;
  3432. case 3: {
  3433. sink.done_with_trailer(
  3434. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3435. } break;
  3436. }
  3437. (*i)++;
  3438. return true;
  3439. },
  3440. [i](bool success) {
  3441. EXPECT_TRUE(success);
  3442. delete i;
  3443. });
  3444. })
  3445. .Get("/streamed",
  3446. [&](const Request & /*req*/, Response &res) {
  3447. res.set_content_provider(
  3448. 6, "text/plain",
  3449. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3450. sink.os << (offset < 3 ? "a" : "b");
  3451. return true;
  3452. });
  3453. })
  3454. .Get("/streamed-without-length",
  3455. [&](const Request & /*req*/, Response &res) {
  3456. auto data = new std::string("abcdefg");
  3457. res.set_content_provider(
  3458. "text/plain",
  3459. [data](size_t offset, DataSink &sink) {
  3460. if (offset < data->size()) {
  3461. sink.os << data->substr(offset);
  3462. }
  3463. sink.done();
  3464. return true;
  3465. },
  3466. [data](bool success) {
  3467. EXPECT_TRUE(success);
  3468. delete data;
  3469. });
  3470. })
  3471. .Get("/streamed-with-range",
  3472. [&](const Request &req, Response &res) {
  3473. auto data = new std::string("abcdefg");
  3474. res.set_content_provider(
  3475. data->size(), "text/plain",
  3476. [data](size_t offset, size_t length, DataSink &sink) {
  3477. size_t DATA_CHUNK_SIZE = 4;
  3478. const auto &d = *data;
  3479. auto out_len =
  3480. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3481. auto ret =
  3482. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3483. EXPECT_TRUE(ret);
  3484. return true;
  3485. },
  3486. [data, &req](bool success) {
  3487. EXPECT_EQ(success, !req.has_param("error"));
  3488. delete data;
  3489. });
  3490. })
  3491. .Get("/streamed-cancel",
  3492. [&](const Request & /*req*/, Response &res) {
  3493. res.set_content_provider(
  3494. size_t(-1), "text/plain",
  3495. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3496. sink.os << "data_chunk";
  3497. return true;
  3498. });
  3499. })
  3500. .Get("/regex-with-delimiter",
  3501. [&](const Request &req, Response & /*res*/) {
  3502. ASSERT_TRUE(req.has_param("key"));
  3503. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3504. })
  3505. .Get("/with-range",
  3506. [&](const Request & /*req*/, Response &res) {
  3507. res.set_content("abcdefg", "text/plain");
  3508. })
  3509. .Get("/test-start-time",
  3510. [&](const Request &req, Response & /*res*/) {
  3511. EXPECT_NE(req.start_time_,
  3512. std::chrono::steady_clock::time_point::min());
  3513. })
  3514. .Get("/with-range-customized-response",
  3515. [&](const Request & /*req*/, Response &res) {
  3516. res.status = StatusCode::BadRequest_400;
  3517. res.set_content(JSON_DATA, "application/json");
  3518. })
  3519. .Post("/chunked",
  3520. [&](const Request &req, Response & /*res*/) {
  3521. EXPECT_EQ(req.body, "dechunked post body");
  3522. })
  3523. .Post("/large-chunked",
  3524. [&](const Request &req, Response & /*res*/) {
  3525. std::string expected(6 * 30 * 1024u, 'a');
  3526. EXPECT_EQ(req.body, expected);
  3527. })
  3528. .Post("/multipart",
  3529. [&](const Request &req, Response & /*res*/) {
  3530. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3531. req.form.get_field_count("text2") +
  3532. req.form.get_field_count("file3") +
  3533. req.form.get_field_count("file4"));
  3534. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3535. req.form.get_file_count("file2"));
  3536. ASSERT_TRUE(!req.form.has_file("???"));
  3537. ASSERT_TRUE(!req.form.has_field("???"));
  3538. ASSERT_TRUE(req.body.empty());
  3539. {
  3540. const auto &text = req.form.get_field("text1");
  3541. EXPECT_EQ("text default", text);
  3542. }
  3543. {
  3544. const auto &text = req.form.get_field("text2");
  3545. EXPECT_EQ("aωb", text);
  3546. }
  3547. {
  3548. const auto &file = req.form.get_file("file1");
  3549. EXPECT_EQ("hello.txt", file.filename);
  3550. EXPECT_EQ("text/plain", file.content_type);
  3551. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3552. }
  3553. {
  3554. const auto &file = req.form.get_file("file2");
  3555. EXPECT_EQ("world.json", file.filename);
  3556. EXPECT_EQ("application/json", file.content_type);
  3557. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3558. }
  3559. {
  3560. const auto &text = req.form.get_field("file3");
  3561. EXPECT_EQ(0u, text.size());
  3562. }
  3563. {
  3564. const auto &text = req.form.get_field("file4");
  3565. EXPECT_EQ(0u, text.size());
  3566. }
  3567. })
  3568. .Post("/multipart/multi_file_values",
  3569. [&](const Request &req, Response & /*res*/) {
  3570. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3571. req.form.get_field_count("multi_text1"));
  3572. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3573. ASSERT_TRUE(!req.form.has_file("???"));
  3574. ASSERT_TRUE(!req.form.has_field("???"));
  3575. ASSERT_TRUE(req.body.empty());
  3576. {
  3577. const auto &text = req.form.get_field("text");
  3578. EXPECT_EQ("default text", text);
  3579. }
  3580. {
  3581. const auto &text1_values = req.form.get_fields("multi_text1");
  3582. EXPECT_EQ(2u, text1_values.size());
  3583. EXPECT_EQ("aaaaa", text1_values[0]);
  3584. EXPECT_EQ("bbbbb", text1_values[1]);
  3585. }
  3586. {
  3587. const auto &file1_values = req.form.get_files("multi_file1");
  3588. EXPECT_EQ(2u, file1_values.size());
  3589. auto file1 = file1_values[0];
  3590. EXPECT_EQ(file1.filename, "hello.txt");
  3591. EXPECT_EQ(file1.content_type, "text/plain");
  3592. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3593. auto file2 = file1_values[1];
  3594. EXPECT_EQ(file2.filename, "world.json");
  3595. EXPECT_EQ(file2.content_type, "application/json");
  3596. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3597. }
  3598. })
  3599. .Post("/empty",
  3600. [&](const Request &req, Response &res) {
  3601. EXPECT_EQ(req.body, "");
  3602. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3603. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3604. res.set_content("empty", "text/plain");
  3605. })
  3606. .Post("/empty-no-content-type",
  3607. [&](const Request &req, Response &res) {
  3608. EXPECT_EQ(req.body, "");
  3609. EXPECT_FALSE(req.has_header("Content-Type"));
  3610. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3611. res.set_content("empty-no-content-type", "text/plain");
  3612. })
  3613. .Post("/path-only",
  3614. [&](const Request &req, Response &res) {
  3615. EXPECT_EQ(req.body, "");
  3616. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3617. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3618. res.set_content("path-only", "text/plain");
  3619. })
  3620. .Post("/path-headers-only",
  3621. [&](const Request &req, Response &res) {
  3622. EXPECT_EQ(req.body, "");
  3623. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3624. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3625. EXPECT_EQ("world", req.get_header_value("hello"));
  3626. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3627. res.set_content("path-headers-only", "text/plain");
  3628. })
  3629. .Post("/post-large",
  3630. [&](const Request &req, Response &res) {
  3631. EXPECT_EQ(req.body, LARGE_DATA);
  3632. res.set_content(req.body, "text/plain");
  3633. })
  3634. .Post("/post-loopback",
  3635. [&](const Request &, Response &res,
  3636. ContentReader const &content_reader) {
  3637. std::string body;
  3638. content_reader([&](const char *data, size_t data_length) {
  3639. body.append(data, data_length);
  3640. return true;
  3641. });
  3642. res.set_content(body, "text/plain");
  3643. })
  3644. .Put("/put-loopback",
  3645. [&](const Request &, Response &res,
  3646. ContentReader const &content_reader) {
  3647. std::string body;
  3648. content_reader([&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. res.set_content(body, "text/plain");
  3653. })
  3654. .Patch("/patch-loopback",
  3655. [&](const Request &, Response &res,
  3656. ContentReader const &content_reader) {
  3657. std::string body;
  3658. content_reader([&](const char *data, size_t data_length) {
  3659. body.append(data, data_length);
  3660. return true;
  3661. });
  3662. res.set_content(body, "text/plain");
  3663. })
  3664. .Put("/empty-no-content-type",
  3665. [&](const Request &req, Response &res) {
  3666. EXPECT_EQ(req.body, "");
  3667. EXPECT_FALSE(req.has_header("Content-Type"));
  3668. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3669. res.set_content("empty-no-content-type", "text/plain");
  3670. })
  3671. .Put("/put",
  3672. [&](const Request &req, Response &res) {
  3673. EXPECT_EQ(req.body, "PUT");
  3674. res.set_content(req.body, "text/plain");
  3675. })
  3676. .Put("/put-large",
  3677. [&](const Request &req, Response &res) {
  3678. EXPECT_EQ(req.body, LARGE_DATA);
  3679. res.set_content(req.body, "text/plain");
  3680. })
  3681. .Patch("/patch",
  3682. [&](const Request &req, Response &res) {
  3683. EXPECT_EQ(req.body, "PATCH");
  3684. res.set_content(req.body, "text/plain");
  3685. })
  3686. .Delete("/delete",
  3687. [&](const Request & /*req*/, Response &res) {
  3688. res.set_content("DELETE", "text/plain");
  3689. })
  3690. .Delete("/delete-body",
  3691. [&](const Request &req, Response &res) {
  3692. EXPECT_EQ(req.body, "content");
  3693. res.set_content(req.body, "text/plain");
  3694. })
  3695. .Options(R"(\*)",
  3696. [&](const Request & /*req*/, Response &res) {
  3697. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3698. })
  3699. .Get("/request-target",
  3700. [&](const Request &req, Response & /*res*/) {
  3701. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3702. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3703. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3704. })
  3705. .Get("/long-query-value",
  3706. [&](const Request &req, Response & /*res*/) {
  3707. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3708. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3709. })
  3710. .Get("/too-long-query-value",
  3711. [&](const Request &req, Response & /*res*/) {
  3712. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3713. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3714. })
  3715. .Get("/array-param",
  3716. [&](const Request &req, Response & /*res*/) {
  3717. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3718. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3719. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3720. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3721. })
  3722. .Get("/array-param-values",
  3723. [&](const Request &req, Response & /*res*/) {
  3724. auto values = req.get_param_values("array");
  3725. EXPECT_EQ(3u, values.size());
  3726. EXPECT_EQ("value1", values[0]);
  3727. EXPECT_EQ("value2", values[1]);
  3728. EXPECT_EQ("value3", values[2]);
  3729. auto empty = req.get_param_values("nonexistent");
  3730. EXPECT_TRUE(empty.empty());
  3731. })
  3732. .Post("/validate-no-multiple-headers",
  3733. [&](const Request &req, Response & /*res*/) {
  3734. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3735. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3736. })
  3737. .Post("/content_receiver",
  3738. [&](const Request &req, Response &res,
  3739. const ContentReader &content_reader) {
  3740. if (req.is_multipart_form_data()) {
  3741. std::vector<FormData> items;
  3742. content_reader(
  3743. [&](const FormData &file) {
  3744. items.push_back(file);
  3745. return true;
  3746. },
  3747. [&](const char *data, size_t data_length) {
  3748. items.back().content.append(data, data_length);
  3749. return true;
  3750. });
  3751. EXPECT_EQ(5u, items.size());
  3752. {
  3753. const auto &file = get_file_value(items, "text1");
  3754. EXPECT_TRUE(file.filename.empty());
  3755. EXPECT_EQ("text default", file.content);
  3756. }
  3757. {
  3758. const auto &file = get_file_value(items, "text2");
  3759. EXPECT_TRUE(file.filename.empty());
  3760. EXPECT_EQ("aωb", file.content);
  3761. }
  3762. {
  3763. const auto &file = get_file_value(items, "file1");
  3764. EXPECT_EQ("hello.txt", file.filename);
  3765. EXPECT_EQ("text/plain", file.content_type);
  3766. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3767. }
  3768. {
  3769. const auto &file = get_file_value(items, "file2");
  3770. EXPECT_EQ("world.json", file.filename);
  3771. EXPECT_EQ("application/json", file.content_type);
  3772. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3773. }
  3774. {
  3775. const auto &file = get_file_value(items, "file3");
  3776. EXPECT_TRUE(file.filename.empty());
  3777. EXPECT_EQ("application/octet-stream", file.content_type);
  3778. EXPECT_EQ(0u, file.content.size());
  3779. }
  3780. } else {
  3781. std::string body;
  3782. content_reader([&](const char *data, size_t data_length) {
  3783. EXPECT_EQ(7U, data_length);
  3784. body.append(data, data_length);
  3785. return true;
  3786. });
  3787. EXPECT_EQ(body, "content");
  3788. res.set_content(body, "text/plain");
  3789. }
  3790. })
  3791. .Put("/content_receiver",
  3792. [&](const Request & /*req*/, Response &res,
  3793. const ContentReader &content_reader) {
  3794. std::string body;
  3795. content_reader([&](const char *data, size_t data_length) {
  3796. body.append(data, data_length);
  3797. return true;
  3798. });
  3799. EXPECT_EQ(body, "content");
  3800. res.set_content(body, "text/plain");
  3801. })
  3802. .Patch("/content_receiver",
  3803. [&](const Request & /*req*/, Response &res,
  3804. const ContentReader &content_reader) {
  3805. std::string body;
  3806. content_reader([&](const char *data, size_t data_length) {
  3807. body.append(data, data_length);
  3808. return true;
  3809. });
  3810. EXPECT_EQ(body, "content");
  3811. res.set_content(body, "text/plain");
  3812. })
  3813. .Post("/query-string-and-body",
  3814. [&](const Request &req, Response & /*res*/) {
  3815. ASSERT_TRUE(req.has_param("key"));
  3816. EXPECT_EQ(req.get_param_value("key"), "value");
  3817. EXPECT_EQ(req.body, "content");
  3818. })
  3819. .Get("/last-request",
  3820. [&](const Request &req, Response & /*res*/) {
  3821. EXPECT_EQ("close", req.get_header_value("Connection"));
  3822. })
  3823. .Get(R"(/redirect/(\d+))",
  3824. [&](const Request &req, Response &res) {
  3825. auto num = std::stoi(req.matches[1]) + 1;
  3826. std::string url = "/redirect/" + std::to_string(num);
  3827. res.set_redirect(url);
  3828. })
  3829. .Post("/binary",
  3830. [&](const Request &req, Response &res) {
  3831. EXPECT_EQ(4U, req.body.size());
  3832. EXPECT_EQ("application/octet-stream",
  3833. req.get_header_value("Content-Type"));
  3834. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3835. res.set_content(req.body, "application/octet-stream");
  3836. })
  3837. .Put("/binary",
  3838. [&](const Request &req, Response &res) {
  3839. EXPECT_EQ(4U, req.body.size());
  3840. EXPECT_EQ("application/octet-stream",
  3841. req.get_header_value("Content-Type"));
  3842. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3843. res.set_content(req.body, "application/octet-stream");
  3844. })
  3845. .Patch("/binary",
  3846. [&](const Request &req, Response &res) {
  3847. EXPECT_EQ(4U, req.body.size());
  3848. EXPECT_EQ("application/octet-stream",
  3849. req.get_header_value("Content-Type"));
  3850. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3851. res.set_content(req.body, "application/octet-stream");
  3852. })
  3853. .Delete("/binary",
  3854. [&](const Request &req, Response &res) {
  3855. EXPECT_EQ(4U, req.body.size());
  3856. EXPECT_EQ("application/octet-stream",
  3857. req.get_header_value("Content-Type"));
  3858. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3859. res.set_content(req.body, "application/octet-stream");
  3860. })
  3861. .Get("/issue1772",
  3862. [&](const Request & /*req*/, Response &res) {
  3863. res.status = 401;
  3864. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3865. })
  3866. .Delete("/issue609",
  3867. [](const httplib::Request &, httplib::Response &res,
  3868. const httplib::ContentReader &) {
  3869. res.set_content("ok", "text/plain");
  3870. })
  3871. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3872. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3873. .Get("/compress",
  3874. [&](const Request & /*req*/, Response &res) {
  3875. res.set_content(
  3876. "12345678901234567890123456789012345678901234567890123456789"
  3877. "01234567890123456789012345678901234567890",
  3878. "text/plain");
  3879. })
  3880. .Get("/compress-with-charset",
  3881. [&](const Request & /*req*/, Response &res) {
  3882. res.set_content(
  3883. "12345678901234567890123456789012345678901234567890123456789"
  3884. "01234567890123456789012345678901234567890",
  3885. "application/json; charset=utf-8");
  3886. })
  3887. .Get("/nocompress",
  3888. [&](const Request & /*req*/, Response &res) {
  3889. res.set_content(
  3890. "12345678901234567890123456789012345678901234567890123456789"
  3891. "01234567890123456789012345678901234567890",
  3892. "application/octet-stream");
  3893. })
  3894. .Post("/compress-multipart",
  3895. [&](const Request &req, Response & /*res*/) {
  3896. EXPECT_EQ(2u, req.form.fields.size());
  3897. ASSERT_TRUE(!req.form.has_field("???"));
  3898. {
  3899. const auto &text = req.form.get_field("key1");
  3900. EXPECT_EQ("test", text);
  3901. }
  3902. {
  3903. const auto &text = req.form.get_field("key2");
  3904. EXPECT_EQ("--abcdefg123", text);
  3905. }
  3906. })
  3907. #endif
  3908. ;
  3909. persons_["john"] = "programmer";
  3910. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3911. svr_.wait_until_ready();
  3912. }
  3913. virtual void TearDown() {
  3914. svr_.stop();
  3915. if (!request_threads_.empty()) {
  3916. std::this_thread::sleep_for(std::chrono::seconds(1));
  3917. for (auto &t : request_threads_) {
  3918. t.join();
  3919. }
  3920. }
  3921. t_.join();
  3922. }
  3923. map<string, string> persons_;
  3924. #ifdef CPPHTTPLIB_SSL_ENABLED
  3925. SSLClient cli_;
  3926. SSLServer svr_;
  3927. #else
  3928. Client cli_;
  3929. Server svr_;
  3930. #endif
  3931. thread t_;
  3932. std::vector<thread> request_threads_;
  3933. };
  3934. TEST_F(ServerTest, GetMethod200) {
  3935. auto res = cli_.Get("/hi");
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ("HTTP/1.1", res->version);
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("OK", res->reason);
  3940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3941. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3942. EXPECT_EQ("Hello World!", res->body);
  3943. }
  3944. TEST_F(ServerTest, GetEmptyFile) {
  3945. auto res = cli_.Get("/empty_file");
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3949. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3950. EXPECT_EQ("", res->body);
  3951. }
  3952. TEST_F(ServerTest, GetFileContent) {
  3953. auto res = cli_.Get("/file_content");
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ(StatusCode::OK_200, res->status);
  3956. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3957. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3958. EXPECT_EQ("test.html", res->body);
  3959. }
  3960. TEST_F(ServerTest, GetFileContentWithRange) {
  3961. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3962. ASSERT_TRUE(res);
  3963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3964. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3965. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3966. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3967. EXPECT_EQ("est", res->body);
  3968. }
  3969. TEST_F(ServerTest, GetFileContentWithContentType) {
  3970. auto res = cli_.Get("/file_content_with_content_type");
  3971. ASSERT_TRUE(res);
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3974. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3975. EXPECT_EQ("file\n", res->body);
  3976. }
  3977. TEST_F(ServerTest, GetInvalidFileContent) {
  3978. auto res = cli_.Get("/invalid_file_content");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3981. }
  3982. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3983. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ("HTTP/1.1", res->version);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3988. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3989. EXPECT_EQ("Hello World!", res->body);
  3990. }
  3991. TEST_F(ServerTest, GetMethod302) {
  3992. auto res = cli_.Get("/");
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::Found_302, res->status);
  3995. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3996. }
  3997. TEST_F(ServerTest, GetMethod302Redirect) {
  3998. cli_.set_follow_location(true);
  3999. auto res = cli_.Get("/");
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. EXPECT_EQ("Hello World!", res->body);
  4003. EXPECT_EQ("/hi", res->location);
  4004. }
  4005. TEST_F(ServerTest, GetMethod404) {
  4006. auto res = cli_.Get("/invalid");
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4009. }
  4010. TEST_F(ServerTest, HeadMethod200) {
  4011. auto res = cli_.Head("/hi");
  4012. ASSERT_TRUE(res);
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4015. EXPECT_TRUE(res->body.empty());
  4016. }
  4017. TEST_F(ServerTest, HeadMethod200Static) {
  4018. auto res = cli_.Head("/mount/dir/index.html");
  4019. ASSERT_TRUE(res);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4022. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4023. EXPECT_TRUE(res->body.empty());
  4024. }
  4025. TEST_F(ServerTest, HeadMethod404) {
  4026. auto res = cli_.Head("/invalid");
  4027. ASSERT_TRUE(res);
  4028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4029. EXPECT_TRUE(res->body.empty());
  4030. }
  4031. TEST_F(ServerTest, GetMethodPersonJohn) {
  4032. auto res = cli_.Get("/person/john");
  4033. ASSERT_TRUE(res);
  4034. EXPECT_EQ(StatusCode::OK_200, res->status);
  4035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4036. EXPECT_EQ("programmer", res->body);
  4037. }
  4038. TEST_F(ServerTest, PostMethod1) {
  4039. auto res = cli_.Get("/person/john1");
  4040. ASSERT_TRUE(res);
  4041. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4042. res = cli_.Post("/person", "name=john1&note=coder",
  4043. "application/x-www-form-urlencoded");
  4044. ASSERT_TRUE(res);
  4045. ASSERT_EQ(StatusCode::OK_200, res->status);
  4046. res = cli_.Get("/person/john1");
  4047. ASSERT_TRUE(res);
  4048. ASSERT_EQ(StatusCode::OK_200, res->status);
  4049. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4050. ASSERT_EQ("coder", res->body);
  4051. }
  4052. TEST_F(ServerTest, PostMethod2) {
  4053. auto res = cli_.Get("/person/john2");
  4054. ASSERT_TRUE(res);
  4055. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4056. Params params;
  4057. params.emplace("name", "john2");
  4058. params.emplace("note", "coder");
  4059. res = cli_.Post("/person", params);
  4060. ASSERT_TRUE(res);
  4061. ASSERT_EQ(StatusCode::OK_200, res->status);
  4062. res = cli_.Get("/person/john2");
  4063. ASSERT_TRUE(res);
  4064. ASSERT_EQ(StatusCode::OK_200, res->status);
  4065. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4066. ASSERT_EQ("coder", res->body);
  4067. }
  4068. TEST_F(ServerTest, PutMethod3) {
  4069. auto res = cli_.Get("/person/john3");
  4070. ASSERT_TRUE(res);
  4071. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4072. Params params;
  4073. params.emplace("name", "john3");
  4074. params.emplace("note", "coder");
  4075. res = cli_.Put("/person", params);
  4076. ASSERT_TRUE(res);
  4077. ASSERT_EQ(StatusCode::OK_200, res->status);
  4078. res = cli_.Get("/person/john3");
  4079. ASSERT_TRUE(res);
  4080. ASSERT_EQ(StatusCode::OK_200, res->status);
  4081. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4082. ASSERT_EQ("coder", res->body);
  4083. }
  4084. TEST_F(ServerTest, DeleteMethod1) {
  4085. auto res = cli_.Get("/person/john4");
  4086. ASSERT_TRUE(res);
  4087. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4088. Params params;
  4089. params.emplace("name", "john4");
  4090. params.emplace("note", "coder");
  4091. res = cli_.Post("/person", params);
  4092. ASSERT_TRUE(res);
  4093. ASSERT_EQ(StatusCode::OK_200, res->status);
  4094. res = cli_.Get("/person/john4");
  4095. ASSERT_TRUE(res);
  4096. ASSERT_EQ(StatusCode::OK_200, res->status);
  4097. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4098. ASSERT_EQ("coder", res->body);
  4099. Params delete_params;
  4100. delete_params.emplace("name", "john4");
  4101. res = cli_.Delete("/person", delete_params);
  4102. ASSERT_TRUE(res);
  4103. ASSERT_EQ(StatusCode::OK_200, res->status);
  4104. ASSERT_EQ("DELETED", res->body);
  4105. res = cli_.Get("/person/john4");
  4106. ASSERT_TRUE(res);
  4107. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4108. }
  4109. TEST_F(ServerTest, DeleteMethod2) {
  4110. auto res = cli_.Get("/person/john5");
  4111. ASSERT_TRUE(res);
  4112. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4113. Params params;
  4114. params.emplace("name", "john5");
  4115. params.emplace("note", "developer");
  4116. res = cli_.Post("/person", params);
  4117. ASSERT_TRUE(res);
  4118. ASSERT_EQ(StatusCode::OK_200, res->status);
  4119. res = cli_.Get("/person/john5");
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4123. ASSERT_EQ("developer", res->body);
  4124. Params delete_params;
  4125. delete_params.emplace("name", "john5");
  4126. Headers headers;
  4127. headers.emplace("Custom-Header", "test-value");
  4128. res = cli_.Delete("/person", headers, delete_params);
  4129. ASSERT_TRUE(res);
  4130. ASSERT_EQ(StatusCode::OK_200, res->status);
  4131. ASSERT_EQ("DELETED", res->body);
  4132. res = cli_.Get("/person/john5");
  4133. ASSERT_TRUE(res);
  4134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4135. }
  4136. TEST_F(ServerTest, DeleteMethod3) {
  4137. auto res = cli_.Get("/person/john6");
  4138. ASSERT_TRUE(res);
  4139. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4140. Params params;
  4141. params.emplace("name", "john6");
  4142. params.emplace("note", "tester");
  4143. res = cli_.Post("/person", params);
  4144. ASSERT_TRUE(res);
  4145. ASSERT_EQ(StatusCode::OK_200, res->status);
  4146. res = cli_.Get("/person/john6");
  4147. ASSERT_TRUE(res);
  4148. ASSERT_EQ(StatusCode::OK_200, res->status);
  4149. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4150. ASSERT_EQ("tester", res->body);
  4151. Params delete_params;
  4152. delete_params.emplace("name", "john6");
  4153. Headers headers;
  4154. headers.emplace("Custom-Header", "test-value");
  4155. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4156. ASSERT_TRUE(res);
  4157. ASSERT_EQ(StatusCode::OK_200, res->status);
  4158. ASSERT_EQ("DELETED", res->body);
  4159. res = cli_.Get("/person/john6");
  4160. ASSERT_TRUE(res);
  4161. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4162. }
  4163. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4164. Params params;
  4165. params.emplace("json", JSON_DATA);
  4166. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4167. ASSERT_TRUE(res);
  4168. ASSERT_EQ(StatusCode::OK_200, res->status);
  4169. ASSERT_EQ(JSON_DATA, res->body);
  4170. }
  4171. TEST_F(ServerTest, PostEmptyContent) {
  4172. auto res = cli_.Post("/empty", "", "text/plain");
  4173. ASSERT_TRUE(res);
  4174. ASSERT_EQ(StatusCode::OK_200, res->status);
  4175. ASSERT_EQ("empty", res->body);
  4176. }
  4177. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4178. auto res = cli_.Post("/empty-no-content-type");
  4179. ASSERT_TRUE(res);
  4180. ASSERT_EQ(StatusCode::OK_200, res->status);
  4181. ASSERT_EQ("empty-no-content-type", res->body);
  4182. }
  4183. TEST_F(ServerTest, PostPathOnly) {
  4184. auto res = cli_.Post("/path-only");
  4185. ASSERT_TRUE(res);
  4186. ASSERT_EQ(StatusCode::OK_200, res->status);
  4187. ASSERT_EQ("path-only", res->body);
  4188. }
  4189. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4190. auto res = cli_.Post("/path-headers-only",
  4191. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4192. ASSERT_TRUE(res);
  4193. ASSERT_EQ(StatusCode::OK_200, res->status);
  4194. ASSERT_EQ("path-headers-only", res->body);
  4195. }
  4196. TEST_F(ServerTest, PostLarge) {
  4197. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4198. ASSERT_TRUE(res);
  4199. ASSERT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ(LARGE_DATA, res->body);
  4201. }
  4202. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4203. auto res = cli_.Put("/empty-no-content-type");
  4204. ASSERT_TRUE(res);
  4205. ASSERT_EQ(StatusCode::OK_200, res->status);
  4206. ASSERT_EQ("empty-no-content-type", res->body);
  4207. }
  4208. TEST_F(ServerTest, GetMethodDir) {
  4209. auto res = cli_.Get("/dir/");
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4213. auto body = R"(<html>
  4214. <head>
  4215. </head>
  4216. <body>
  4217. <a href="/dir/test.html">Test</a>
  4218. <a href="/hi">hi</a>
  4219. </body>
  4220. </html>
  4221. )";
  4222. EXPECT_EQ(body, res->body);
  4223. }
  4224. TEST_F(ServerTest, GetMethodDirTest) {
  4225. auto res = cli_.Get("/dir/test.html");
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4229. EXPECT_EQ("test.html", res->body);
  4230. }
  4231. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4232. auto res = cli_.Get("/dir/../dir/test.html");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::OK_200, res->status);
  4235. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4236. EXPECT_EQ("test.html", res->body);
  4237. }
  4238. TEST_F(ServerTest, GetMethodInvalidPath) {
  4239. auto res = cli_.Get("/dir/../test.html");
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4242. }
  4243. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4244. auto res = cli_.Get("/../www/dir/test.html");
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4247. }
  4248. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4249. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4252. }
  4253. TEST_F(ServerTest, GetMethodDirMountTest) {
  4254. auto res = cli_.Get("/mount/dir/test.html");
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::OK_200, res->status);
  4257. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4258. EXPECT_EQ("test.html", res->body);
  4259. }
  4260. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4261. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4265. EXPECT_EQ("test.html", res->body);
  4266. }
  4267. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4268. auto res = cli_.Get("/mount/dir/../test.html");
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4271. }
  4272. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4273. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. }
  4277. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4278. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4281. }
  4282. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4283. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4284. ASSERT_TRUE(res);
  4285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4286. }
  4287. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4288. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. TEST_F(ServerTest, PostMethod303) {
  4293. auto res = cli_.Post("/1", "body", "text/plain");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4296. EXPECT_EQ("/2", res->get_header_value("Location"));
  4297. }
  4298. TEST_F(ServerTest, PostMethod303Redirect) {
  4299. cli_.set_follow_location(true);
  4300. auto res = cli_.Post("/1", "body", "text/plain");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("redirected.", res->body);
  4304. EXPECT_EQ("/2", res->location);
  4305. }
  4306. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4307. auto res = cli_.Get("/dir/test.abcde");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4311. EXPECT_EQ("abcde", res->body);
  4312. }
  4313. TEST_F(ServerTest, StaticFileRange) {
  4314. auto res =
  4315. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4316. ASSERT_TRUE(res);
  4317. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4318. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4319. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4320. EXPECT_EQ(true, res->has_header("Content-Range"));
  4321. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4322. EXPECT_EQ(std::string("cd"), res->body);
  4323. }
  4324. TEST_F(ServerTest, StaticFileRanges) {
  4325. auto res = cli_.Get("/dir/test.abcde",
  4326. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4329. EXPECT_TRUE(
  4330. res->get_header_value("Content-Type")
  4331. .find(
  4332. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4333. 0);
  4334. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4335. }
  4336. TEST_F(ServerTest, StaticFileRangeHead) {
  4337. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4340. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4341. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4342. EXPECT_EQ(true, res->has_header("Content-Range"));
  4343. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4344. }
  4345. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4346. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4350. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4351. EXPECT_EQ(true, res->has_header("Content-Range"));
  4352. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4353. res->get_header_value("Content-Range"));
  4354. EXPECT_EQ("LAST\n", res->body);
  4355. }
  4356. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4357. auto res =
  4358. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4362. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4363. EXPECT_EQ(true, res->has_header("Content-Range"));
  4364. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4365. }
  4366. TEST_F(ServerTest, StaticFileBigFile) {
  4367. auto res = cli_.Get("/dir/1MB.txt");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4371. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4372. }
  4373. TEST_F(ServerTest, InvalidBaseDirMount) {
  4374. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4375. }
  4376. TEST_F(ServerTest, Binary) {
  4377. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4378. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4379. "application/octet-stream");
  4380. ASSERT_TRUE(res);
  4381. ASSERT_EQ(StatusCode::OK_200, res->status);
  4382. ASSERT_EQ(4U, res->body.size());
  4383. res = cli_.Put("/binary", binary.data(), binary.size(),
  4384. "application/octet-stream");
  4385. ASSERT_TRUE(res);
  4386. ASSERT_EQ(StatusCode::OK_200, res->status);
  4387. ASSERT_EQ(4U, res->body.size());
  4388. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4389. "application/octet-stream");
  4390. ASSERT_TRUE(res);
  4391. ASSERT_EQ(StatusCode::OK_200, res->status);
  4392. ASSERT_EQ(4U, res->body.size());
  4393. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4394. "application/octet-stream");
  4395. ASSERT_TRUE(res);
  4396. ASSERT_EQ(StatusCode::OK_200, res->status);
  4397. ASSERT_EQ(4U, res->body.size());
  4398. }
  4399. TEST_F(ServerTest, BinaryString) {
  4400. auto binary = std::string("\x00\x01\x02\x03", 4);
  4401. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4402. ASSERT_TRUE(res);
  4403. ASSERT_EQ(StatusCode::OK_200, res->status);
  4404. ASSERT_EQ(4U, res->body.size());
  4405. res = cli_.Put("/binary", binary, "application/octet-stream");
  4406. ASSERT_TRUE(res);
  4407. ASSERT_EQ(StatusCode::OK_200, res->status);
  4408. ASSERT_EQ(4U, res->body.size());
  4409. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4410. ASSERT_TRUE(res);
  4411. ASSERT_EQ(StatusCode::OK_200, res->status);
  4412. ASSERT_EQ(4U, res->body.size());
  4413. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4414. ASSERT_TRUE(res);
  4415. ASSERT_EQ(StatusCode::OK_200, res->status);
  4416. ASSERT_EQ(4U, res->body.size());
  4417. }
  4418. TEST_F(ServerTest, EmptyRequest) {
  4419. auto res = cli_.Get("");
  4420. ASSERT_TRUE(!res);
  4421. EXPECT_EQ(Error::Connection, res.error());
  4422. }
  4423. TEST_F(ServerTest, LongRequest) {
  4424. std::string request;
  4425. for (size_t i = 0; i < 545; i++) {
  4426. request += "/TooLongRequest";
  4427. }
  4428. request += "OK";
  4429. auto res = cli_.Get(request.c_str());
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4432. }
  4433. TEST_F(ServerTest, TooLongRequest) {
  4434. std::string request;
  4435. for (size_t i = 0; i < 546; i++) {
  4436. request += "/TooLongRequest";
  4437. }
  4438. request += "_NG";
  4439. auto start = std::chrono::high_resolution_clock::now();
  4440. cli_.set_keep_alive(true);
  4441. auto res = cli_.Get(request.c_str());
  4442. auto end = std::chrono::high_resolution_clock::now();
  4443. auto elapsed =
  4444. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4445. .count();
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4448. EXPECT_LE(elapsed, 1000);
  4449. EXPECT_EQ("close", res->get_header_value("Connection"));
  4450. EXPECT_FALSE(cli_.is_socket_open());
  4451. }
  4452. TEST_F(ServerTest, AlmostTooLongRequest) {
  4453. // test for #2046 - URI length check shouldn't include other content on req
  4454. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4455. // leading /, space, HTTP/1.1)
  4456. std::string request =
  4457. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4458. auto res = cli_.Get(request.c_str());
  4459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4460. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4461. }
  4462. TEST_F(ServerTest, LongHeader) {
  4463. Request req;
  4464. req.method = "GET";
  4465. req.path = "/hi";
  4466. std::string host_and_port;
  4467. host_and_port += HOST;
  4468. host_and_port += ":";
  4469. host_and_port += std::to_string(PORT);
  4470. req.headers.emplace("Host", host_and_port.c_str());
  4471. req.headers.emplace("Accept", "*/*");
  4472. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4473. req.headers.emplace(
  4474. "Header-Name",
  4475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4484. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@");
  4504. auto res = std::make_shared<Response>();
  4505. auto error = Error::Success;
  4506. auto ret = cli_.send(req, *res, error);
  4507. ASSERT_TRUE(ret);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. }
  4510. TEST_F(ServerTest, LongQueryValue) {
  4511. auto start = std::chrono::high_resolution_clock::now();
  4512. cli_.set_keep_alive(true);
  4513. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4514. auto end = std::chrono::high_resolution_clock::now();
  4515. auto elapsed =
  4516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4517. .count();
  4518. ASSERT_TRUE(res);
  4519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4520. EXPECT_LE(elapsed, 1000);
  4521. EXPECT_EQ("close", res->get_header_value("Connection"));
  4522. EXPECT_FALSE(cli_.is_socket_open());
  4523. }
  4524. TEST_F(ServerTest, TooLongQueryValue) {
  4525. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4526. ASSERT_FALSE(res);
  4527. EXPECT_EQ(Error::Read, res.error());
  4528. }
  4529. TEST_F(ServerTest, TooLongHeader) {
  4530. Request req;
  4531. req.method = "GET";
  4532. req.path = "/hi";
  4533. std::string host_and_port;
  4534. host_and_port += HOST;
  4535. host_and_port += ":";
  4536. host_and_port += std::to_string(PORT);
  4537. req.headers.emplace("Host", host_and_port.c_str());
  4538. req.headers.emplace("Accept", "*/*");
  4539. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4540. req.headers.emplace(
  4541. "Header-Name",
  4542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@");
  4571. auto res = std::make_shared<Response>();
  4572. auto error = Error::Success;
  4573. auto ret = cli_.send(req, *res, error);
  4574. ASSERT_TRUE(ret);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST_F(ServerTest, HeaderCountAtLimit) {
  4578. // Test with headers just under the 100 limit
  4579. httplib::Headers headers;
  4580. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4581. // This should keep us just under the 100 header limit
  4582. for (int i = 0; i < 95; i++) {
  4583. std::string name = "X-Test-Header-" + std::to_string(i);
  4584. std::string value = "value" + std::to_string(i);
  4585. headers.emplace(name, value);
  4586. }
  4587. // This should work fine as we're under the limit
  4588. auto res = cli_.Get("/hi", headers);
  4589. EXPECT_TRUE(res);
  4590. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4591. }
  4592. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4593. // Test with many headers to exceed the 100 limit
  4594. httplib::Headers headers;
  4595. // Add 150 headers to definitely exceed the 100 limit
  4596. for (int i = 0; i < 150; i++) {
  4597. std::string name = "X-Test-Header-" + std::to_string(i);
  4598. std::string value = "value" + std::to_string(i);
  4599. headers.emplace(name, value);
  4600. }
  4601. // This should fail due to exceeding header count limit
  4602. cli_.set_keep_alive(true);
  4603. auto res = cli_.Get("/hi", headers);
  4604. // The server should respond with 400 Bad Request
  4605. ASSERT_TRUE(res);
  4606. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4607. EXPECT_EQ("close", res->get_header_value("Connection"));
  4608. EXPECT_FALSE(cli_.is_socket_open());
  4609. }
  4610. TEST_F(ServerTest, PercentEncoding) {
  4611. auto res = cli_.Get("/e%6edwith%");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. }
  4615. TEST_F(ServerTest, PercentEncodingUnicode) {
  4616. auto res = cli_.Get("/e%u006edwith%");
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::OK_200, res->status);
  4619. }
  4620. TEST_F(ServerTest, InvalidPercentEncoding) {
  4621. auto res = cli_.Get("/%endwith%");
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4624. }
  4625. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4626. auto res = cli_.Get("/%uendwith%");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4629. }
  4630. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4631. auto res = cli_.Get("/hello?aaa=bbb%");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4634. }
  4635. TEST_F(ServerTest, PlusSignEncoding) {
  4636. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4637. ASSERT_TRUE(res);
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("a +b", res->body);
  4640. }
  4641. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4642. // This test simulates a potential DoS attack using many headers
  4643. // to verify our security fix prevents memory exhaustion
  4644. httplib::Headers attack_headers;
  4645. // Attempt to add many headers like an attacker would (200 headers to far
  4646. // exceed limit)
  4647. for (int i = 0; i < 200; i++) {
  4648. std::string name = "X-Attack-Header-" + std::to_string(i);
  4649. std::string value = "attack_payload_" + std::to_string(i);
  4650. attack_headers.emplace(name, value);
  4651. }
  4652. // Try to POST with excessive headers
  4653. cli_.set_keep_alive(true);
  4654. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4655. // Should either fail or return 400 Bad Request due to security limit
  4656. if (res) {
  4657. // If we get a response, it should be 400 Bad Request
  4658. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4659. EXPECT_EQ("close", res->get_header_value("Connection"));
  4660. }
  4661. EXPECT_FALSE(cli_.is_socket_open());
  4662. }
  4663. TEST_F(ServerTest, MultipartFormData) {
  4664. UploadFormDataItems items = {
  4665. {"text1", "text default", "", ""},
  4666. {"text2", "aωb", "", ""},
  4667. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4668. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4669. {"file3", "", "", "application/octet-stream"},
  4670. {"file4", "", "", " application/json tmp-string "}};
  4671. auto res = cli_.Post("/multipart", items);
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. }
  4675. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4676. UploadFormDataItems items = {
  4677. {"text", "default text", "", ""},
  4678. {"multi_text1", "aaaaa", "", ""},
  4679. {"multi_text1", "bbbbb", "", ""},
  4680. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4681. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4682. "application/json"},
  4683. };
  4684. auto res = cli_.Post("/multipart/multi_file_values", items);
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::OK_200, res->status);
  4687. }
  4688. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4689. auto res = cli_.Get("/hi");
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4693. EXPECT_EQ("Hello World!", res->body);
  4694. }
  4695. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4696. Request req;
  4697. req.method = "POST";
  4698. req.path = "/chunked";
  4699. std::string host_and_port;
  4700. host_and_port += HOST;
  4701. host_and_port += ":";
  4702. host_and_port += std::to_string(PORT);
  4703. req.headers.emplace("Host", host_and_port.c_str());
  4704. req.headers.emplace("Accept", "*/*");
  4705. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4706. req.headers.emplace("Content-Type", "text/plain");
  4707. req.headers.emplace("Content-Length", "0");
  4708. req.headers.emplace(
  4709. "Transfer-Encoding",
  4710. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4711. // Client does not chunk, so make a chunked body manually.
  4712. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4713. auto res = std::make_shared<Response>();
  4714. auto error = Error::Success;
  4715. auto ret = cli_.send(req, *res, error);
  4716. ASSERT_TRUE(ret);
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. }
  4719. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4720. // rather than treat them as valid lengths.
  4721. template <typename ClientT>
  4722. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4723. Request req;
  4724. req.method = "POST";
  4725. req.path = "/chunked";
  4726. std::string host_and_port;
  4727. host_and_port += HOST;
  4728. host_and_port += ":";
  4729. host_and_port += std::to_string(PORT);
  4730. req.headers.emplace("Host", host_and_port.c_str());
  4731. req.headers.emplace("Content-Length", "0");
  4732. req.headers.emplace("Transfer-Encoding", "chunked");
  4733. req.body = body;
  4734. auto res = std::make_shared<Response>();
  4735. auto error = Error::Success;
  4736. ASSERT_TRUE(cli.send(req, *res, error));
  4737. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4738. }
  4739. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4740. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4741. }
  4742. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4743. expect_chunked_body_rejected(
  4744. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4745. }
  4746. TEST_F(ServerTest, GetStreamed2) {
  4747. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4750. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4751. EXPECT_EQ(true, res->has_header("Content-Range"));
  4752. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4753. EXPECT_EQ(std::string("ab"), res->body);
  4754. }
  4755. TEST_F(ServerTest, GetStreamed) {
  4756. auto res = cli_.Get("/streamed");
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::OK_200, res->status);
  4759. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4760. EXPECT_EQ(std::string("aaabbb"), res->body);
  4761. }
  4762. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4763. auto res = cli_.Get("/streamed-without-length",
  4764. Headers{make_range_header({{0, -1}})});
  4765. ASSERT_TRUE(res);
  4766. EXPECT_EQ(StatusCode::OK_200, res->status);
  4767. EXPECT_EQ(false, res->has_header("Content-Length"));
  4768. EXPECT_EQ(false, res->has_header("Content-Range"));
  4769. EXPECT_EQ(std::string("abcdefg"), res->body);
  4770. }
  4771. TEST_F(ServerTest, GetStreamedWithRange1) {
  4772. auto res =
  4773. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4774. ASSERT_TRUE(res);
  4775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4776. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4777. EXPECT_EQ(true, res->has_header("Content-Range"));
  4778. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4779. EXPECT_EQ(std::string("def"), res->body);
  4780. }
  4781. TEST_F(ServerTest, GetStreamedWithRange2) {
  4782. auto res =
  4783. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4786. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4787. EXPECT_EQ(true, res->has_header("Content-Range"));
  4788. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4789. EXPECT_EQ(std::string("bcdefg"), res->body);
  4790. }
  4791. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4792. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4793. ASSERT_TRUE(res);
  4794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4795. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4796. EXPECT_EQ(true, res->has_header("Content-Range"));
  4797. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4798. EXPECT_EQ(std::string("efg"), res->body);
  4799. }
  4800. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4801. auto res =
  4802. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4803. ASSERT_TRUE(res);
  4804. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4805. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4806. EXPECT_EQ(false, res->has_header("Content-Range"));
  4807. EXPECT_EQ(0U, res->body.size());
  4808. }
  4809. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4810. auto res =
  4811. cli_.Get("/streamed-with-range",
  4812. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4813. "92233720368547758079223372036854775807"}});
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4816. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4817. EXPECT_EQ(false, res->has_header("Content-Range"));
  4818. EXPECT_EQ(0U, res->body.size());
  4819. }
  4820. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4821. auto res = cli_.Get(
  4822. "/with-range",
  4823. Headers{{"Range",
  4824. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4825. {"Accept-Encoding", ""}});
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4828. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4829. EXPECT_EQ(true, res->has_header("Content-Range"));
  4830. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4831. EXPECT_EQ(std::string("abcdefg"), res->body);
  4832. }
  4833. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4834. auto res = cli_.Get("/with-range", Headers{
  4835. {"Range", "bytes=0-"},
  4836. {"Accept-Encoding", ""},
  4837. });
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4840. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4841. EXPECT_EQ(true, res->has_header("Content-Range"));
  4842. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4843. EXPECT_EQ(std::string("abcdefg"), res->body);
  4844. }
  4845. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4846. auto res = cli_.Get("/streamed-with-range",
  4847. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4848. ASSERT_TRUE(res);
  4849. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4850. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4851. EXPECT_EQ(false, res->has_header("Content-Range"));
  4852. EXPECT_EQ(267U, res->body.size());
  4853. // Check that both range contents are present
  4854. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4855. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4856. // Check that Content-Range headers are present for both ranges
  4857. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4858. std::string::npos);
  4859. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4860. std::string::npos);
  4861. }
  4862. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4863. Ranges ranges;
  4864. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4865. ranges.emplace_back(0, -1);
  4866. }
  4867. auto res = cli_.Get("/streamed-with-range?error",
  4868. Headers{{make_range_header(ranges)}});
  4869. ASSERT_TRUE(res);
  4870. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4871. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4872. EXPECT_EQ(false, res->has_header("Content-Range"));
  4873. EXPECT_EQ(0U, res->body.size());
  4874. }
  4875. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4876. auto res = cli_.Get("/streamed-with-range",
  4877. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4880. EXPECT_EQ(5U, res->body.size());
  4881. // Check that overlapping ranges are coalesced into a single range
  4882. EXPECT_EQ("bcdef", res->body);
  4883. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4884. // Should be single range, not multipart
  4885. EXPECT_TRUE(res->has_header("Content-Range"));
  4886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4887. }
  4888. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4889. auto res = cli_.Get("/streamed-with-range",
  4890. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4891. ASSERT_TRUE(res);
  4892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4893. EXPECT_EQ(268U, res->body.size());
  4894. // Check that both range contents are present
  4895. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4896. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4897. // Check that Content-Range headers are present for both ranges
  4898. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4899. std::string::npos);
  4900. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4901. std::string::npos);
  4902. }
  4903. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4904. auto res = cli_.Get("/streamed-with-range",
  4905. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4908. EXPECT_EQ(269U, res->body.size());
  4909. // Check that both duplicate range contents are present
  4910. size_t first_abc = res->body.find("abc\r\n");
  4911. EXPECT_TRUE(first_abc != std::string::npos);
  4912. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4913. EXPECT_TRUE(second_abc != std::string::npos);
  4914. // Check that Content-Range headers are present for both ranges
  4915. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4916. EXPECT_TRUE(first_range != std::string::npos);
  4917. size_t second_range =
  4918. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4919. EXPECT_TRUE(second_range != std::string::npos);
  4920. }
  4921. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4922. auto res =
  4923. cli_.Get("/streamed-with-range?error",
  4924. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4925. ASSERT_TRUE(res);
  4926. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4927. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4928. EXPECT_EQ(false, res->has_header("Content-Range"));
  4929. EXPECT_EQ(0U, res->body.size());
  4930. }
  4931. TEST_F(ServerTest, GetStreamedEndless) {
  4932. uint64_t offset = 0;
  4933. auto res = cli_.Get("/streamed-cancel",
  4934. [&](const char * /*data*/, uint64_t data_length) {
  4935. if (offset < 100) {
  4936. offset += data_length;
  4937. return true;
  4938. }
  4939. return false;
  4940. });
  4941. ASSERT_TRUE(!res);
  4942. EXPECT_EQ(Error::Canceled, res.error());
  4943. }
  4944. TEST_F(ServerTest, ClientStop) {
  4945. std::atomic_size_t count{4};
  4946. std::vector<std::thread> threads;
  4947. for (auto i = count.load(); i != 0; --i) {
  4948. threads.emplace_back([&]() {
  4949. auto res = cli_.Get("/streamed-cancel",
  4950. [&](const char *, uint64_t) { return true; });
  4951. --count;
  4952. ASSERT_TRUE(!res);
  4953. EXPECT_TRUE(res.error() == Error::Canceled ||
  4954. res.error() == Error::Read || res.error() == Error::Write);
  4955. });
  4956. }
  4957. std::this_thread::sleep_for(std::chrono::seconds(2));
  4958. while (count != 0) {
  4959. cli_.stop();
  4960. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4961. }
  4962. for (auto &t : threads) {
  4963. t.join();
  4964. }
  4965. }
  4966. TEST_F(ServerTest, GetWithRange1) {
  4967. auto res = cli_.Get("/with-range", Headers{
  4968. make_range_header({{3, 5}}),
  4969. {"Accept-Encoding", ""},
  4970. });
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4973. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4974. EXPECT_EQ(true, res->has_header("Content-Range"));
  4975. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4976. EXPECT_EQ(std::string("def"), res->body);
  4977. }
  4978. TEST_F(ServerTest, GetWithRange2) {
  4979. auto res = cli_.Get("/with-range", Headers{
  4980. make_range_header({{1, -1}}),
  4981. {"Accept-Encoding", ""},
  4982. });
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4985. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4986. EXPECT_EQ(true, res->has_header("Content-Range"));
  4987. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4988. EXPECT_EQ(std::string("bcdefg"), res->body);
  4989. }
  4990. TEST_F(ServerTest, GetWithRange3) {
  4991. auto res = cli_.Get("/with-range", Headers{
  4992. make_range_header({{0, 0}}),
  4993. {"Accept-Encoding", ""},
  4994. });
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4997. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(true, res->has_header("Content-Range"));
  4999. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5000. EXPECT_EQ(std::string("a"), res->body);
  5001. }
  5002. TEST_F(ServerTest, GetWithRange4) {
  5003. auto res = cli_.Get("/with-range", Headers{
  5004. make_range_header({{-1, 2}}),
  5005. {"Accept-Encoding", ""},
  5006. });
  5007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5009. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ(true, res->has_header("Content-Range"));
  5011. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5012. EXPECT_EQ(std::string("fg"), res->body);
  5013. }
  5014. TEST_F(ServerTest, GetWithRange5) {
  5015. auto res = cli_.Get("/with-range", Headers{
  5016. make_range_header({{0, 5}}),
  5017. {"Accept-Encoding", ""},
  5018. });
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5021. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5022. EXPECT_EQ(true, res->has_header("Content-Range"));
  5023. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5024. EXPECT_EQ(std::string("abcdef"), res->body);
  5025. }
  5026. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5027. auto res =
  5028. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5029. ASSERT_TRUE(res);
  5030. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5031. }
  5032. TEST_F(ServerTest, GetWithRangeMultipart) {
  5033. auto res =
  5034. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5035. ASSERT_TRUE(res);
  5036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5037. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5038. EXPECT_EQ(false, res->has_header("Content-Range"));
  5039. EXPECT_EQ(267U, res->body.size());
  5040. }
  5041. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5042. auto res = cli_.Get("/with-range",
  5043. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5044. ASSERT_TRUE(res);
  5045. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5046. }
  5047. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5048. auto res = cli_.Get("/with-range-customized-response",
  5049. Headers{{make_range_header({{1, 2}})}});
  5050. ASSERT_TRUE(res);
  5051. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5052. EXPECT_EQ(true, res->has_header("Content-Length"));
  5053. EXPECT_EQ(false, res->has_header("Content-Range"));
  5054. EXPECT_EQ(JSON_DATA, res->body);
  5055. }
  5056. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5057. auto res = cli_.Get("/with-range-customized-response",
  5058. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5059. ASSERT_TRUE(res);
  5060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5061. EXPECT_EQ(true, res->has_header("Content-Length"));
  5062. EXPECT_EQ(false, res->has_header("Content-Range"));
  5063. EXPECT_EQ(JSON_DATA, res->body);
  5064. }
  5065. TEST_F(ServerTest, Issue1772) {
  5066. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5069. }
  5070. TEST_F(ServerTest, Issue609) {
  5071. auto res = cli_.Delete("/issue609");
  5072. ASSERT_TRUE(res);
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ(std::string("ok"), res->body);
  5075. }
  5076. TEST_F(ServerTest, GetStreamedChunked) {
  5077. auto res = cli_.Get("/streamed-chunked");
  5078. ASSERT_TRUE(res);
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. EXPECT_EQ(std::string("123456789"), res->body);
  5081. }
  5082. TEST_F(ServerTest, GetStreamedChunked2) {
  5083. auto res = cli_.Get("/streamed-chunked2");
  5084. ASSERT_TRUE(res);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ(std::string("123456789"), res->body);
  5087. }
  5088. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5089. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ(std::string("123456789"), res->body);
  5093. EXPECT_TRUE(res->has_header("Trailer"));
  5094. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5095. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5096. // Trailers are now stored separately from headers (security fix)
  5097. EXPECT_EQ(2U, res->trailers.size());
  5098. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5099. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5100. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5101. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5102. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5103. // Verify trailers are NOT in headers (security verification)
  5104. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5105. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5106. }
  5107. TEST_F(ServerTest, LargeChunkedPost) {
  5108. Request req;
  5109. req.method = "POST";
  5110. req.path = "/large-chunked";
  5111. std::string host_and_port;
  5112. host_and_port += HOST;
  5113. host_and_port += ":";
  5114. host_and_port += std::to_string(PORT);
  5115. req.headers.emplace("Host", host_and_port.c_str());
  5116. req.headers.emplace("Accept", "*/*");
  5117. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5118. req.headers.emplace("Content-Type", "text/plain");
  5119. req.headers.emplace("Content-Length", "0");
  5120. req.headers.emplace("Transfer-Encoding", "chunked");
  5121. std::string long_string(30 * 1024u, 'a');
  5122. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5123. // Attempt to make a large enough post to exceed OS buffers, to test that
  5124. // the server handles short reads if the full chunk data isn't available.
  5125. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5126. auto res = std::make_shared<Response>();
  5127. auto error = Error::Success;
  5128. auto ret = cli_.send(req, *res, error);
  5129. ASSERT_TRUE(ret);
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. }
  5132. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5133. auto res = cli_.Get("/remote_addr");
  5134. ASSERT_TRUE(res);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5137. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5138. }
  5139. TEST_F(ServerTest, GetMethodLocalAddr) {
  5140. auto res = cli_.Get("/local_addr");
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5144. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5145. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5146. }
  5147. TEST_F(ServerTest, HTTPResponseSplitting) {
  5148. auto res = cli_.Get("/http_response_splitting");
  5149. ASSERT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. }
  5152. TEST_F(ServerTest, SlowRequest) {
  5153. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5154. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5155. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5156. }
  5157. #if 0
  5158. TEST_F(ServerTest, SlowPost) {
  5159. char buffer[64 * 1024];
  5160. memset(buffer, 0x42, sizeof(buffer));
  5161. auto res = cli_.Post(
  5162. "/slowpost", 64 * 1024 * 1024,
  5163. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5164. auto ret = sink.write(buffer, sizeof(buffer));
  5165. EXPECT_TRUE(ret);
  5166. return true;
  5167. },
  5168. "text/plain");
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. }
  5172. TEST_F(ServerTest, SlowPostFail) {
  5173. char buffer[64 * 1024];
  5174. memset(buffer, 0x42, sizeof(buffer));
  5175. cli_.set_write_timeout(std::chrono::seconds(0));
  5176. auto res = cli_.Post(
  5177. "/slowpost", 64 * 1024 * 1024,
  5178. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5179. sink.write(buffer, sizeof(buffer));
  5180. return true;
  5181. },
  5182. "text/plain");
  5183. ASSERT_TRUE(!res);
  5184. EXPECT_EQ(Error::Write, res.error());
  5185. }
  5186. #endif
  5187. TEST_F(ServerTest, Put) {
  5188. auto res = cli_.Put("/put", "PUT", "text/plain");
  5189. ASSERT_TRUE(res);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. EXPECT_EQ("PUT", res->body);
  5192. }
  5193. TEST_F(ServerTest, PutWithContentProvider) {
  5194. auto res = cli_.Put(
  5195. "/put", 3,
  5196. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5197. sink.os << "PUT";
  5198. return true;
  5199. },
  5200. "text/plain");
  5201. ASSERT_TRUE(res);
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. EXPECT_EQ("PUT", res->body);
  5204. }
  5205. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5206. auto res = cli_.Post(
  5207. "/post", 42,
  5208. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5209. return false;
  5210. },
  5211. "text/plain");
  5212. ASSERT_TRUE(!res);
  5213. EXPECT_EQ(Error::Canceled, res.error());
  5214. }
  5215. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5216. auto res = cli_.Put(
  5217. "/put",
  5218. [](size_t /*offset*/, DataSink &sink) {
  5219. sink.os << "PUT";
  5220. sink.done();
  5221. return true;
  5222. },
  5223. "text/plain");
  5224. ASSERT_TRUE(res);
  5225. EXPECT_EQ(StatusCode::OK_200, res->status);
  5226. EXPECT_EQ("PUT", res->body);
  5227. }
  5228. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5229. auto res = cli_.Post(
  5230. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5231. "text/plain");
  5232. ASSERT_TRUE(!res);
  5233. EXPECT_EQ(Error::Canceled, res.error());
  5234. }
  5235. TEST_F(ServerTest, PostLoopBack) {
  5236. std::string body;
  5237. auto res = cli_.Post(
  5238. "/post-loopback", 9,
  5239. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5240. EXPECT_EQ(9u, length);
  5241. sink.write("123", 3);
  5242. sink.write("456", 3);
  5243. sink.write("789", 3);
  5244. return true;
  5245. },
  5246. "text/plain",
  5247. [&body](const char *data, size_t data_length) {
  5248. body.append(data, data_length);
  5249. return true;
  5250. });
  5251. ASSERT_TRUE(res);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("123456789", body);
  5254. }
  5255. TEST_F(ServerTest, PutLoopBack) {
  5256. std::string body;
  5257. auto res = cli_.Put(
  5258. "/put-loopback", 9,
  5259. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5260. EXPECT_EQ(9u, length);
  5261. sink.write("123", 3);
  5262. sink.write("456", 3);
  5263. sink.write("789", 3);
  5264. return true;
  5265. },
  5266. "text/plain",
  5267. [&body](const char *data, size_t data_length) {
  5268. body.append(data, data_length);
  5269. return true;
  5270. });
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(StatusCode::OK_200, res->status);
  5273. EXPECT_EQ("123456789", body);
  5274. }
  5275. TEST_F(ServerTest, PatchLoopBack) {
  5276. std::string body;
  5277. auto res = cli_.Patch(
  5278. "/patch-loopback", 9,
  5279. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5280. EXPECT_EQ(9u, length);
  5281. sink.write("123", 3);
  5282. sink.write("456", 3);
  5283. sink.write("789", 3);
  5284. return true;
  5285. },
  5286. "text/plain",
  5287. [&body](const char *data, size_t data_length) {
  5288. body.append(data, data_length);
  5289. return true;
  5290. });
  5291. ASSERT_TRUE(res);
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. EXPECT_EQ("123456789", body);
  5294. }
  5295. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5296. std::string body;
  5297. auto res = cli_.Post(
  5298. "/post-loopback",
  5299. [](size_t /*offset*/, DataSink &sink) {
  5300. sink.write("123", 3);
  5301. sink.write("456", 3);
  5302. sink.write("789", 3);
  5303. sink.done();
  5304. return true;
  5305. },
  5306. "text/plain",
  5307. [&body](const char *data, size_t data_length) {
  5308. body.append(data, data_length);
  5309. return true;
  5310. });
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. EXPECT_EQ("123456789", body);
  5314. }
  5315. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5316. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5317. cli_.set_compress(true);
  5318. auto res = cli_.Put(
  5319. "/put", 3,
  5320. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5321. sink.os << "PUT";
  5322. return true;
  5323. },
  5324. "text/plain");
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. EXPECT_EQ("PUT", res->body);
  5328. }
  5329. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5330. cli_.set_compress(true);
  5331. auto res = cli_.Post(
  5332. "/post", 42,
  5333. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5334. return false;
  5335. },
  5336. "text/plain");
  5337. ASSERT_TRUE(!res);
  5338. EXPECT_EQ(Error::Canceled, res.error());
  5339. }
  5340. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5341. cli_.set_compress(true);
  5342. auto res = cli_.Put(
  5343. "/put",
  5344. [](size_t /*offset*/, DataSink &sink) {
  5345. sink.os << "PUT";
  5346. sink.done();
  5347. return true;
  5348. },
  5349. "text/plain");
  5350. ASSERT_TRUE(res);
  5351. EXPECT_EQ(StatusCode::OK_200, res->status);
  5352. EXPECT_EQ("PUT", res->body);
  5353. }
  5354. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5355. cli_.set_compress(true);
  5356. auto res = cli_.Post(
  5357. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5358. "text/plain");
  5359. ASSERT_TRUE(!res);
  5360. EXPECT_EQ(Error::Canceled, res.error());
  5361. }
  5362. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5363. cli_.set_compress(true);
  5364. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5365. ASSERT_TRUE(res);
  5366. EXPECT_EQ(StatusCode::OK_200, res->status);
  5367. EXPECT_EQ(LARGE_DATA, res->body);
  5368. }
  5369. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5370. #ifdef CPPHTTPLIB_SSL_ENABLED
  5371. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5372. Client cli(s.c_str());
  5373. cli.enable_server_certificate_verification(false);
  5374. #else
  5375. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5376. Client cli(s.c_str());
  5377. #endif
  5378. cli.set_compress(true);
  5379. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5380. ASSERT_TRUE(res);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ(LARGE_DATA, res->body);
  5383. // The compressed size should be less than a 10th of the original. May vary
  5384. // depending on the zlib library.
  5385. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5386. static_cast<uint64_t>(10 * 1024 * 1024));
  5387. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5388. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5389. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5390. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5391. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5392. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5393. #endif
  5394. }
  5395. TEST_F(ServerTest, PutContentWithDeflate) {
  5396. cli_.set_compress(false);
  5397. Headers headers;
  5398. headers.emplace("Content-Encoding", "deflate");
  5399. // PUT in deflate format:
  5400. auto res = cli_.Put("/put", headers,
  5401. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5402. ASSERT_TRUE(res);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("PUT", res->body);
  5405. }
  5406. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5407. Headers headers;
  5408. headers.emplace("Accept-Encoding", "gzip, deflate");
  5409. auto res = cli_.Get("/streamed-chunked", headers);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. EXPECT_EQ(std::string("123456789"), res->body);
  5413. }
  5414. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5415. Headers headers;
  5416. headers.emplace("Accept-Encoding", "gzip, deflate");
  5417. auto res = cli_.Get("/streamed-chunked2", headers);
  5418. ASSERT_TRUE(res);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. EXPECT_EQ(std::string("123456789"), res->body);
  5421. }
  5422. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5423. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. }
  5427. TEST(GzipDecompressor, ChunkedDecompression) {
  5428. std::string data;
  5429. for (size_t i = 0; i < 32 * 1024; ++i) {
  5430. data.push_back(static_cast<char>('a' + i % 26));
  5431. }
  5432. std::string compressed_data;
  5433. {
  5434. httplib::detail::gzip_compressor compressor;
  5435. bool result = compressor.compress(
  5436. data.data(), data.size(),
  5437. /*last=*/true,
  5438. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5439. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5440. compressed_data_size);
  5441. return true;
  5442. });
  5443. ASSERT_TRUE(result);
  5444. }
  5445. std::string decompressed_data;
  5446. {
  5447. httplib::detail::gzip_decompressor decompressor;
  5448. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5449. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5450. size_t chunk_size = 130;
  5451. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5452. chunk_begin += chunk_size) {
  5453. size_t current_chunk_size =
  5454. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5455. bool result = decompressor.decompress(
  5456. compressed_data.data() + chunk_begin, current_chunk_size,
  5457. [&](const char *decompressed_data_chunk,
  5458. size_t decompressed_data_chunk_size) {
  5459. decompressed_data.insert(decompressed_data.size(),
  5460. decompressed_data_chunk,
  5461. decompressed_data_chunk_size);
  5462. return true;
  5463. });
  5464. ASSERT_TRUE(result);
  5465. }
  5466. }
  5467. ASSERT_EQ(data, decompressed_data);
  5468. }
  5469. TEST(GzipDecompressor, DeflateDecompression) {
  5470. std::string original_text = "Raw deflate without gzip";
  5471. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5472. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5473. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5474. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5475. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5476. std::string decompressed_data;
  5477. {
  5478. httplib::detail::gzip_decompressor decompressor;
  5479. bool result = decompressor.decompress(
  5480. compressed_data.data(), compressed_data.size(),
  5481. [&](const char *decompressed_data_chunk,
  5482. size_t decompressed_data_chunk_size) {
  5483. decompressed_data.insert(decompressed_data.size(),
  5484. decompressed_data_chunk,
  5485. decompressed_data_chunk_size);
  5486. return true;
  5487. });
  5488. ASSERT_TRUE(result);
  5489. }
  5490. ASSERT_EQ(original_text, decompressed_data);
  5491. }
  5492. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5493. std::string original_text = "Raw deflate without gzip";
  5494. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5495. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5496. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5497. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5498. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5499. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5500. std::string decompressed_data;
  5501. {
  5502. httplib::detail::gzip_decompressor decompressor;
  5503. bool result = decompressor.decompress(
  5504. compressed_data.data(), compressed_data.size(),
  5505. [&](const char *decompressed_data_chunk,
  5506. size_t decompressed_data_chunk_size) {
  5507. decompressed_data.insert(decompressed_data.size(),
  5508. decompressed_data_chunk,
  5509. decompressed_data_chunk_size);
  5510. return true;
  5511. });
  5512. ASSERT_TRUE(result);
  5513. }
  5514. ASSERT_EQ(original_text, decompressed_data);
  5515. }
  5516. #endif
  5517. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5518. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5519. Headers headers;
  5520. headers.emplace("Accept-Encoding", "br");
  5521. auto res = cli_.Get("/streamed-chunked", headers);
  5522. ASSERT_TRUE(res);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. EXPECT_EQ(std::string("123456789"), res->body);
  5525. }
  5526. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5527. Headers headers;
  5528. headers.emplace("Accept-Encoding", "br");
  5529. auto res = cli_.Get("/streamed-chunked2", headers);
  5530. ASSERT_TRUE(res);
  5531. EXPECT_EQ(StatusCode::OK_200, res->status);
  5532. EXPECT_EQ(std::string("123456789"), res->body);
  5533. }
  5534. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5535. cli_.set_compress(true);
  5536. auto res = cli_.Put(
  5537. "/put", 3,
  5538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5539. sink.os << "PUT";
  5540. return true;
  5541. },
  5542. "text/plain");
  5543. ASSERT_TRUE(res);
  5544. EXPECT_EQ(StatusCode::OK_200, res->status);
  5545. EXPECT_EQ("PUT", res->body);
  5546. }
  5547. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5548. cli_.set_compress(true);
  5549. auto res = cli_.Put(
  5550. "/put",
  5551. [](size_t /*offset*/, DataSink &sink) {
  5552. sink.os << "PUT";
  5553. sink.done();
  5554. return true;
  5555. },
  5556. "text/plain");
  5557. ASSERT_TRUE(res);
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_EQ("PUT", res->body);
  5560. }
  5561. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5562. cli_.set_compress(true);
  5563. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5564. ASSERT_TRUE(res);
  5565. EXPECT_EQ(StatusCode::OK_200, res->status);
  5566. EXPECT_EQ(LARGE_DATA, res->body);
  5567. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5568. }
  5569. #endif
  5570. TEST_F(ServerTest, Patch) {
  5571. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5572. ASSERT_TRUE(res);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ("PATCH", res->body);
  5575. }
  5576. TEST_F(ServerTest, Delete) {
  5577. auto res = cli_.Delete("/delete");
  5578. ASSERT_TRUE(res);
  5579. EXPECT_EQ(StatusCode::OK_200, res->status);
  5580. EXPECT_EQ("DELETE", res->body);
  5581. }
  5582. TEST_F(ServerTest, DeleteContentReceiver) {
  5583. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5584. ASSERT_TRUE(res);
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("content", res->body);
  5587. }
  5588. TEST_F(ServerTest, Options) {
  5589. auto res = cli_.Options("*");
  5590. ASSERT_TRUE(res);
  5591. EXPECT_EQ(StatusCode::OK_200, res->status);
  5592. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5593. EXPECT_TRUE(res->body.empty());
  5594. }
  5595. TEST_F(ServerTest, URL) {
  5596. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5597. ASSERT_TRUE(res);
  5598. EXPECT_EQ(StatusCode::OK_200, res->status);
  5599. }
  5600. TEST_F(ServerTest, ArrayParam) {
  5601. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. }
  5605. TEST_F(ServerTest, ArrayParamValues) {
  5606. auto res =
  5607. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. }
  5611. TEST_F(ServerTest, NoMultipleHeaders) {
  5612. Headers headers = {{"Content-Length", "5"}};
  5613. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5614. "text/plain");
  5615. ASSERT_TRUE(res);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. }
  5618. TEST_F(ServerTest, PostContentReceiver) {
  5619. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5620. ASSERT_TRUE(res);
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ("content", res->body);
  5623. }
  5624. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5625. UploadFormDataItems items = {
  5626. {"text1", "text default", "", ""},
  5627. {"text2", "aωb", "", ""},
  5628. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5629. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5630. {"file3", "", "", "application/octet-stream"},
  5631. };
  5632. auto res = cli_.Post("/content_receiver", items);
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. }
  5636. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5637. UploadFormDataItems items = {
  5638. {"text1", "text default", "", ""},
  5639. {"text2", "aωb", "", ""},
  5640. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5641. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5642. {"file3", "", "", "application/octet-stream"},
  5643. };
  5644. auto boundary = std::string("+++++");
  5645. std::string body;
  5646. for (const auto &item : items) {
  5647. body += "--" + boundary + "\r\n";
  5648. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5649. if (!item.filename.empty()) {
  5650. body += "; filename=\"" + item.filename + "\"";
  5651. }
  5652. body += "\r\n";
  5653. if (!item.content_type.empty()) {
  5654. body += "Content-Type: " + item.content_type + "\r\n";
  5655. }
  5656. body += "\r\n";
  5657. body += item.content + "\r\n";
  5658. }
  5659. body += "--" + boundary + "--\r\n";
  5660. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5661. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5662. ASSERT_TRUE(res);
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. }
  5665. TEST(MultipartFormDataTest, FieldEscaping) {
  5666. Server svr;
  5667. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5668. const ContentReader &content_reader) {
  5669. ASSERT_TRUE(req.is_multipart_form_data());
  5670. std::vector<FormData> received;
  5671. content_reader(
  5672. [&](const FormData &file) {
  5673. received.push_back(file);
  5674. return true;
  5675. },
  5676. [&](const char *data, size_t data_length) {
  5677. received.back().content.append(data, data_length);
  5678. return true;
  5679. });
  5680. // '"', CR and LF in names and filenames are escaped following the
  5681. // WHATWG HTML standard, so each part still parses as a single part
  5682. // with no injected headers. Content types get CR/LF escaped too,
  5683. // while '"' (legal there, e.g. quoted charset) is preserved.
  5684. ASSERT_EQ(4U, received.size());
  5685. EXPECT_EQ("na%22me", received[0].name);
  5686. EXPECT_EQ("quoted name", received[0].content);
  5687. EXPECT_EQ("file", received[1].name);
  5688. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5689. received[1].filename);
  5690. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5691. EXPECT_EQ("injected", received[1].content);
  5692. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5693. EXPECT_EQ("my%22file.txt", received[2].filename);
  5694. EXPECT_EQ("cr lf name", received[2].content);
  5695. EXPECT_EQ("typed", received[3].name);
  5696. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5697. received[3].content_type);
  5698. EXPECT_EQ("typed content", received[3].content);
  5699. });
  5700. auto port = svr.bind_to_any_port("localhost");
  5701. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5702. auto se = detail::scope_exit([&] {
  5703. svr.stop();
  5704. t.join();
  5705. ASSERT_FALSE(svr.is_running());
  5706. });
  5707. svr.wait_until_ready();
  5708. Client cli("localhost", port);
  5709. UploadFormDataItems items = {
  5710. {"na\"me", "quoted name", "", ""},
  5711. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5712. "application/octet-stream"},
  5713. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5714. {"typed", "typed content", "",
  5715. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5716. };
  5717. auto res = cli.Post("/post", items);
  5718. ASSERT_TRUE(res);
  5719. EXPECT_EQ(StatusCode::OK_200, res->status);
  5720. }
  5721. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5722. const UploadFormDataItems items = {
  5723. {"name1", "Content 1", "", ""},
  5724. {"name2", "Content 2", "file2.txt", "text/plain"},
  5725. };
  5726. Server svr;
  5727. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5728. const ContentReader &content_reader) {
  5729. ASSERT_TRUE(req.is_multipart_form_data());
  5730. std::vector<FormData> received;
  5731. content_reader(
  5732. [&](const FormData &file) {
  5733. received.push_back(file);
  5734. return true;
  5735. },
  5736. [&](const char *data, size_t data_length) {
  5737. received.back().content.append(data, data_length);
  5738. return true;
  5739. });
  5740. ASSERT_EQ(2U, received.size());
  5741. EXPECT_EQ("name1", received[0].name);
  5742. EXPECT_EQ("Content 1", received[0].content);
  5743. EXPECT_EQ("name2", received[1].name);
  5744. EXPECT_EQ("Content 2", received[1].content);
  5745. EXPECT_EQ("file2.txt", received[1].filename);
  5746. EXPECT_EQ("text/plain", received[1].content_type);
  5747. });
  5748. auto port = svr.bind_to_any_port("localhost");
  5749. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5750. auto se = detail::scope_exit([&] {
  5751. svr.stop();
  5752. t.join();
  5753. ASSERT_FALSE(svr.is_running());
  5754. });
  5755. svr.wait_until_ready();
  5756. Client cli("localhost", port);
  5757. // Whole-body serialization with a generated boundary
  5758. {
  5759. MultipartFormDataWriter writer;
  5760. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5761. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5762. writer.content_type());
  5763. auto body = writer.serialize(items);
  5764. EXPECT_EQ(body.size(), writer.content_length(items));
  5765. auto res = cli.Post("/post", body, writer.content_type());
  5766. ASSERT_TRUE(res);
  5767. EXPECT_EQ(StatusCode::OK_200, res->status);
  5768. }
  5769. // Per-part framing with a custom boundary via a content provider
  5770. {
  5771. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5772. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5773. MultipartFormDataWriter writer("custom-boundary_123");
  5774. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5775. std::string body;
  5776. for (const auto &item : items) {
  5777. body += writer.item_begin(item);
  5778. body += item.content;
  5779. body += MultipartFormDataWriter::item_end();
  5780. }
  5781. body += writer.finish();
  5782. EXPECT_EQ(body.size(), writer.content_length(items));
  5783. auto res = cli.Post(
  5784. "/post", body.size(),
  5785. [&](size_t offset, size_t length, DataSink &sink) {
  5786. sink.write(body.data() + offset, length);
  5787. return true;
  5788. },
  5789. writer.content_type());
  5790. ASSERT_TRUE(res);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. }
  5794. TEST_F(ServerTest, PostContentReceiverGzip) {
  5795. cli_.set_compress(true);
  5796. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5797. ASSERT_TRUE(res);
  5798. ASSERT_EQ(StatusCode::OK_200, res->status);
  5799. ASSERT_EQ("content", res->body);
  5800. }
  5801. TEST_F(ServerTest, PutContentReceiver) {
  5802. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5803. ASSERT_TRUE(res);
  5804. ASSERT_EQ(StatusCode::OK_200, res->status);
  5805. ASSERT_EQ("content", res->body);
  5806. }
  5807. TEST_F(ServerTest, PatchContentReceiver) {
  5808. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5809. ASSERT_TRUE(res);
  5810. ASSERT_EQ(StatusCode::OK_200, res->status);
  5811. ASSERT_EQ("content", res->body);
  5812. }
  5813. template <typename ClientType>
  5814. void TestWithHeadersAndContentReceiver(
  5815. ClientType &cli,
  5816. std::function<Result(ClientType &, const std::string &, const Headers &,
  5817. const std::string &, const std::string &,
  5818. ContentReceiver, DownloadProgress)>
  5819. request_func) {
  5820. Headers headers;
  5821. headers.emplace("X-Custom-Header", "test-value");
  5822. std::string received_body;
  5823. auto res = request_func(
  5824. cli, "/content_receiver", headers, "content", "application/json",
  5825. [&](const char *data, size_t data_length) {
  5826. received_body.append(data, data_length);
  5827. return true;
  5828. },
  5829. nullptr);
  5830. ASSERT_TRUE(res);
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. EXPECT_EQ("content", received_body);
  5833. }
  5834. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5835. #ifdef CPPHTTPLIB_SSL_ENABLED
  5836. using ClientT = SSLClient;
  5837. #else
  5838. using ClientT = Client;
  5839. #endif
  5840. TestWithHeadersAndContentReceiver<ClientT>(
  5841. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5842. const std::string &body, const std::string &content_type,
  5843. ContentReceiver receiver, DownloadProgress progress) {
  5844. return cli.Post(path, headers, body, content_type, receiver, progress);
  5845. });
  5846. }
  5847. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5848. #ifdef CPPHTTPLIB_SSL_ENABLED
  5849. using ClientT = SSLClient;
  5850. #else
  5851. using ClientT = Client;
  5852. #endif
  5853. TestWithHeadersAndContentReceiver<ClientT>(
  5854. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5855. const std::string &body, const std::string &content_type,
  5856. ContentReceiver receiver, DownloadProgress progress) {
  5857. return cli.Put(path, headers, body, content_type, receiver, progress);
  5858. });
  5859. }
  5860. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5861. #ifdef CPPHTTPLIB_SSL_ENABLED
  5862. using ClientT = SSLClient;
  5863. #else
  5864. using ClientT = Client;
  5865. #endif
  5866. TestWithHeadersAndContentReceiver<ClientT>(
  5867. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5868. const std::string &body, const std::string &content_type,
  5869. ContentReceiver receiver, DownloadProgress progress) {
  5870. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5871. });
  5872. }
  5873. template <typename ClientType>
  5874. void TestWithHeadersAndContentReceiverWithProgress(
  5875. ClientType &cli,
  5876. std::function<Result(ClientType &, const std::string &, const Headers &,
  5877. const std::string &, const std::string &,
  5878. ContentReceiver, DownloadProgress)>
  5879. request_func) {
  5880. Headers headers;
  5881. headers.emplace("X-Test-Header", "progress-test");
  5882. std::string received_body;
  5883. auto progress_called = false;
  5884. auto res = request_func(
  5885. cli, "/content_receiver", headers, "content", "text/plain",
  5886. [&](const char *data, size_t data_length) {
  5887. received_body.append(data, data_length);
  5888. return true;
  5889. },
  5890. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5891. progress_called = true;
  5892. return true;
  5893. });
  5894. ASSERT_TRUE(res);
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. EXPECT_EQ("content", received_body);
  5897. EXPECT_TRUE(progress_called);
  5898. }
  5899. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5900. #ifdef CPPHTTPLIB_SSL_ENABLED
  5901. using ClientT = SSLClient;
  5902. #else
  5903. using ClientT = Client;
  5904. #endif
  5905. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5906. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5907. const std::string &body, const std::string &content_type,
  5908. ContentReceiver receiver, DownloadProgress progress) {
  5909. return cli.Post(path, headers, body, content_type, receiver, progress);
  5910. });
  5911. }
  5912. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5913. #ifdef CPPHTTPLIB_SSL_ENABLED
  5914. using ClientT = SSLClient;
  5915. #else
  5916. using ClientT = Client;
  5917. #endif
  5918. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5919. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5920. const std::string &body, const std::string &content_type,
  5921. ContentReceiver receiver, DownloadProgress progress) {
  5922. return cli.Put(path, headers, body, content_type, receiver, progress);
  5923. });
  5924. }
  5925. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5926. #ifdef CPPHTTPLIB_SSL_ENABLED
  5927. using ClientT = SSLClient;
  5928. #else
  5929. using ClientT = Client;
  5930. #endif
  5931. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5932. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5933. const std::string &body, const std::string &content_type,
  5934. ContentReceiver receiver, DownloadProgress progress) {
  5935. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5936. });
  5937. }
  5938. template <typename ClientType>
  5939. void TestWithHeadersAndContentReceiverError(
  5940. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5941. const Headers &, const std::string &,
  5942. const std::string &, ContentReceiver)>
  5943. request_func) {
  5944. Headers headers;
  5945. headers.emplace("X-Error-Test", "true");
  5946. std::string received_body;
  5947. auto receiver_failed = false;
  5948. auto res =
  5949. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5950. [&](const char *data, size_t data_length) {
  5951. received_body.append(data, data_length);
  5952. receiver_failed = true;
  5953. return false;
  5954. });
  5955. ASSERT_FALSE(res);
  5956. EXPECT_TRUE(receiver_failed);
  5957. }
  5958. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5959. #ifdef CPPHTTPLIB_SSL_ENABLED
  5960. using ClientT = SSLClient;
  5961. #else
  5962. using ClientT = Client;
  5963. #endif
  5964. TestWithHeadersAndContentReceiverError<ClientT>(
  5965. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5966. const std::string &body, const std::string &content_type,
  5967. ContentReceiver receiver) {
  5968. return cli.Post(path, headers, body, content_type, receiver);
  5969. });
  5970. }
  5971. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5972. #ifdef CPPHTTPLIB_SSL_ENABLED
  5973. using ClientT = SSLClient;
  5974. #else
  5975. using ClientT = Client;
  5976. #endif
  5977. TestWithHeadersAndContentReceiverError<ClientT>(
  5978. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5979. const std::string &body, const std::string &content_type,
  5980. ContentReceiver receiver) {
  5981. return cli.Put(path, headers, body, content_type, receiver);
  5982. });
  5983. }
  5984. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5985. #ifdef CPPHTTPLIB_SSL_ENABLED
  5986. using ClientT = SSLClient;
  5987. #else
  5988. using ClientT = Client;
  5989. #endif
  5990. TestWithHeadersAndContentReceiverError<ClientT>(
  5991. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5992. const std::string &body, const std::string &content_type,
  5993. ContentReceiver receiver) {
  5994. return cli.Patch(path, headers, body, content_type, receiver);
  5995. });
  5996. }
  5997. TEST_F(ServerTest, PostQueryStringAndBody) {
  5998. auto res =
  5999. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6000. ASSERT_TRUE(res);
  6001. ASSERT_EQ(StatusCode::OK_200, res->status);
  6002. }
  6003. TEST_F(ServerTest, HTTP2Magic) {
  6004. Request req;
  6005. req.method = "PRI";
  6006. req.path = "*";
  6007. req.body = "SM";
  6008. auto res = std::make_shared<Response>();
  6009. auto error = Error::Success;
  6010. auto ret = cli_.send(req, *res, error);
  6011. ASSERT_TRUE(ret);
  6012. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6013. }
  6014. TEST_F(ServerTest, KeepAlive) {
  6015. auto res = cli_.Get("/hi");
  6016. ASSERT_TRUE(res);
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6019. EXPECT_EQ("Hello World!", res->body);
  6020. res = cli_.Get("/hi");
  6021. ASSERT_TRUE(res);
  6022. EXPECT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6024. EXPECT_EQ("Hello World!", res->body);
  6025. res = cli_.Get("/hi");
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("Hello World!", res->body);
  6030. res = cli_.Get("/not-exist");
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6033. res = cli_.Post("/empty", "", "text/plain");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ("empty", res->body);
  6038. EXPECT_EQ("close", res->get_header_value("Connection"));
  6039. res = cli_.Post(
  6040. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6041. "text/plain");
  6042. ASSERT_TRUE(res);
  6043. EXPECT_EQ(StatusCode::OK_200, res->status);
  6044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6045. EXPECT_EQ("empty", res->body);
  6046. cli_.set_keep_alive(false);
  6047. res = cli_.Get("/last-request");
  6048. ASSERT_TRUE(res);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. EXPECT_EQ("close", res->get_header_value("Connection"));
  6051. }
  6052. TEST_F(ServerTest, TooManyRedirect) {
  6053. cli_.set_follow_location(true);
  6054. auto res = cli_.Get("/redirect/0");
  6055. ASSERT_TRUE(!res);
  6056. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6057. }
  6058. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6059. Request req;
  6060. req.method = "FOOBAR";
  6061. req.path = "/hi";
  6062. cli_.set_keep_alive(true);
  6063. auto res = cli_.send(req);
  6064. ASSERT_TRUE(res);
  6065. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6066. EXPECT_EQ("close", res->get_header_value("Connection"));
  6067. EXPECT_FALSE(cli_.is_socket_open());
  6068. }
  6069. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6070. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6071. TEST_F(ServerTest, Gzip) {
  6072. Headers headers;
  6073. headers.emplace("Accept-Encoding", "gzip, deflate");
  6074. auto res = cli_.Get("/compress", headers);
  6075. ASSERT_TRUE(res);
  6076. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6080. "7890123456789012345678901234567890",
  6081. res->body);
  6082. EXPECT_EQ(StatusCode::OK_200, res->status);
  6083. }
  6084. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6085. Headers headers;
  6086. headers.emplace("Accept-Encoding", "gzip, deflate");
  6087. auto res = cli_.Get("/compress-with-charset", headers);
  6088. ASSERT_TRUE(res);
  6089. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6090. EXPECT_EQ("application/json; charset=utf-8",
  6091. res->get_header_value("Content-Type"));
  6092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6093. "7890123456789012345678901234567890",
  6094. res->body);
  6095. EXPECT_EQ(StatusCode::OK_200, res->status);
  6096. }
  6097. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6098. Headers headers;
  6099. headers.emplace("Accept-Encoding", "");
  6100. auto res = cli_.Get("/compress", headers);
  6101. ASSERT_TRUE(res);
  6102. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6103. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6104. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6105. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6106. "7890123456789012345678901234567890",
  6107. res->body);
  6108. EXPECT_EQ(StatusCode::OK_200, res->status);
  6109. }
  6110. TEST_F(ServerTest, GzipWithContentReceiver) {
  6111. Headers headers;
  6112. headers.emplace("Accept-Encoding", "gzip, deflate");
  6113. std::string body;
  6114. auto res = cli_.Get("/compress", headers,
  6115. [&](const char *data, uint64_t data_length) {
  6116. EXPECT_EQ(100U, data_length);
  6117. body.append(data, data_length);
  6118. return true;
  6119. });
  6120. ASSERT_TRUE(res);
  6121. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6122. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6123. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6125. "7890123456789012345678901234567890",
  6126. body);
  6127. EXPECT_EQ(StatusCode::OK_200, res->status);
  6128. }
  6129. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6130. Headers headers;
  6131. headers.emplace("Accept-Encoding", "gzip, deflate");
  6132. cli_.set_decompress(false);
  6133. auto res = cli_.Get("/compress", headers);
  6134. ASSERT_TRUE(res);
  6135. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6137. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6138. EXPECT_EQ(33U, res->body.size());
  6139. EXPECT_EQ(StatusCode::OK_200, res->status);
  6140. }
  6141. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6142. Headers headers;
  6143. headers.emplace("Accept-Encoding", "");
  6144. std::string body;
  6145. auto res = cli_.Get("/compress", headers,
  6146. [&](const char *data, uint64_t data_length) {
  6147. EXPECT_EQ(100U, data_length);
  6148. body.append(data, data_length);
  6149. return true;
  6150. });
  6151. ASSERT_TRUE(res);
  6152. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6156. "7890123456789012345678901234567890",
  6157. body);
  6158. EXPECT_EQ(StatusCode::OK_200, res->status);
  6159. }
  6160. TEST_F(ServerTest, NoGzip) {
  6161. Headers headers;
  6162. headers.emplace("Accept-Encoding", "gzip, deflate");
  6163. auto res = cli_.Get("/nocompress", headers);
  6164. ASSERT_TRUE(res);
  6165. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6169. "7890123456789012345678901234567890",
  6170. res->body);
  6171. EXPECT_EQ(StatusCode::OK_200, res->status);
  6172. }
  6173. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6174. Headers headers;
  6175. headers.emplace("Accept-Encoding", "gzip, deflate");
  6176. std::string body;
  6177. auto res = cli_.Get("/nocompress", headers,
  6178. [&](const char *data, uint64_t data_length) {
  6179. EXPECT_EQ(100U, data_length);
  6180. body.append(data, data_length);
  6181. return true;
  6182. });
  6183. ASSERT_TRUE(res);
  6184. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6185. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6186. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6188. "7890123456789012345678901234567890",
  6189. body);
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. }
  6192. TEST_F(ServerTest, MultipartFormDataGzip) {
  6193. UploadFormDataItems items = {
  6194. {"key1", "test", "", ""},
  6195. {"key2", "--abcdefg123", "", ""},
  6196. };
  6197. cli_.set_compress(true);
  6198. auto res = cli_.Post("/compress-multipart", items);
  6199. ASSERT_TRUE(res);
  6200. EXPECT_EQ(StatusCode::OK_200, res->status);
  6201. }
  6202. #endif
  6203. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6204. TEST_F(ServerTest, Brotli) {
  6205. Headers headers;
  6206. headers.emplace("Accept-Encoding", "br");
  6207. auto res = cli_.Get("/compress", headers);
  6208. ASSERT_TRUE(res);
  6209. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6211. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6212. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6213. "7890123456789012345678901234567890",
  6214. res->body);
  6215. EXPECT_EQ(StatusCode::OK_200, res->status);
  6216. }
  6217. #endif
  6218. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6219. TEST_F(ServerTest, Zstd) {
  6220. Headers headers;
  6221. headers.emplace("Accept-Encoding", "zstd");
  6222. auto res = cli_.Get("/compress", headers);
  6223. ASSERT_TRUE(res);
  6224. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6226. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6228. "7890123456789012345678901234567890",
  6229. res->body);
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. }
  6232. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6233. Headers headers;
  6234. headers.emplace("Accept-Encoding", "");
  6235. auto res = cli_.Get("/compress", headers);
  6236. ASSERT_TRUE(res);
  6237. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6239. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6240. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6241. "7890123456789012345678901234567890",
  6242. res->body);
  6243. EXPECT_EQ(StatusCode::OK_200, res->status);
  6244. }
  6245. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6246. Headers headers;
  6247. headers.emplace("Accept-Encoding", "zstd");
  6248. std::string body;
  6249. auto res = cli_.Get("/compress", headers,
  6250. [&](const char *data, uint64_t data_length) {
  6251. EXPECT_EQ(100U, data_length);
  6252. body.append(data, data_length);
  6253. return true;
  6254. });
  6255. ASSERT_TRUE(res);
  6256. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6258. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6259. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6260. "7890123456789012345678901234567890",
  6261. body);
  6262. EXPECT_EQ(StatusCode::OK_200, res->status);
  6263. }
  6264. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6265. Headers headers;
  6266. headers.emplace("Accept-Encoding", "zstd");
  6267. cli_.set_decompress(false);
  6268. auto res = cli_.Get("/compress", headers);
  6269. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6270. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6271. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6272. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6276. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ(StatusCode::OK_200, res->status);
  6278. ASSERT_EQ(26U, res->body.size());
  6279. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6280. 0);
  6281. }
  6282. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6283. Headers headers;
  6284. headers.emplace("Accept-Encoding", "");
  6285. std::string body;
  6286. auto res = cli_.Get("/compress", headers,
  6287. [&](const char *data, uint64_t data_length) {
  6288. EXPECT_EQ(100U, data_length);
  6289. body.append(data, data_length);
  6290. return true;
  6291. });
  6292. ASSERT_TRUE(res);
  6293. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6295. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6296. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6297. "7890123456789012345678901234567890",
  6298. body);
  6299. EXPECT_EQ(StatusCode::OK_200, res->status);
  6300. }
  6301. TEST_F(ServerTest, NoZstd) {
  6302. Headers headers;
  6303. headers.emplace("Accept-Encoding", "zstd");
  6304. auto res = cli_.Get("/nocompress", headers);
  6305. ASSERT_TRUE(res);
  6306. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6307. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6308. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6309. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6310. "7890123456789012345678901234567890",
  6311. res->body);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. }
  6314. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6315. Headers headers;
  6316. headers.emplace("Accept-Encoding", "zstd");
  6317. std::string body;
  6318. auto res = cli_.Get("/nocompress", headers,
  6319. [&](const char *data, uint64_t data_length) {
  6320. EXPECT_EQ(100U, data_length);
  6321. body.append(data, data_length);
  6322. return true;
  6323. });
  6324. ASSERT_TRUE(res);
  6325. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6326. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6327. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6328. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6329. "7890123456789012345678901234567890",
  6330. body);
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. // TODO: How to enable zstd ??
  6334. TEST_F(ServerTest, MultipartFormDataZstd) {
  6335. UploadFormDataItems items = {
  6336. {"key1", "test", "", ""},
  6337. {"key2", "--abcdefg123", "", ""},
  6338. };
  6339. Headers headers;
  6340. headers.emplace("Accept-Encoding", "zstd");
  6341. cli_.set_compress(true);
  6342. auto res = cli_.Post("/compress-multipart", headers, items);
  6343. ASSERT_TRUE(res);
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6347. Headers headers;
  6348. headers.emplace("Accept-Encoding", "zstd");
  6349. cli_.set_compress(true);
  6350. auto res = cli_.Put(
  6351. "/put", headers, 3,
  6352. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6353. sink.os << "PUT";
  6354. return true;
  6355. },
  6356. "text/plain");
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ("PUT", res->body);
  6360. }
  6361. // Pre-compression logging tests
  6362. TEST_F(ServerTest, PreCompressionLogging) {
  6363. // Test data for compression (matches the actual /compress endpoint content)
  6364. const std::string test_content =
  6365. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6366. "3456789012345678901234567890";
  6367. // Variables to capture logging data
  6368. std::string pre_compression_body;
  6369. std::string pre_compression_content_type;
  6370. std::string pre_compression_content_encoding;
  6371. std::string post_compression_body;
  6372. std::string post_compression_content_type;
  6373. std::string post_compression_content_encoding;
  6374. // Set up pre-compression logger
  6375. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6376. const Response &res) {
  6377. pre_compression_body = res.body;
  6378. pre_compression_content_type = res.get_header_value("Content-Type");
  6379. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6380. });
  6381. // Set up post-compression logger
  6382. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6383. post_compression_body = res.body;
  6384. post_compression_content_type = res.get_header_value("Content-Type");
  6385. post_compression_content_encoding =
  6386. res.get_header_value("Content-Encoding");
  6387. });
  6388. // Test with gzip compression
  6389. Headers headers;
  6390. headers.emplace("Accept-Encoding", "gzip");
  6391. auto res = cli_.Get("/compress", headers);
  6392. // Verify response was compressed
  6393. ASSERT_TRUE(res);
  6394. EXPECT_EQ(StatusCode::OK_200, res->status);
  6395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6396. // Verify pre-compression logger captured uncompressed content
  6397. EXPECT_EQ(test_content, pre_compression_body);
  6398. EXPECT_EQ("text/plain", pre_compression_content_type);
  6399. EXPECT_TRUE(pre_compression_content_encoding
  6400. .empty()); // No encoding header before compression
  6401. // Verify post-compression logger captured compressed content
  6402. EXPECT_NE(test_content,
  6403. post_compression_body); // Should be different after compression
  6404. EXPECT_EQ("text/plain", post_compression_content_type);
  6405. EXPECT_EQ("gzip", post_compression_content_encoding);
  6406. // Verify compressed content is smaller
  6407. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6408. }
  6409. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6410. const std::string test_content =
  6411. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6412. "3456789012345678901234567890";
  6413. std::string pre_compression_body;
  6414. std::string post_compression_body;
  6415. svr_.set_pre_compression_logger(
  6416. [&](const Request & /*req*/, const Response &res) {
  6417. pre_compression_body = res.body;
  6418. });
  6419. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6420. post_compression_body = res.body;
  6421. });
  6422. Headers headers;
  6423. headers.emplace("Accept-Encoding", "br");
  6424. auto res = cli_.Get("/compress", headers);
  6425. ASSERT_TRUE(res);
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6428. // Verify pre-compression content is uncompressed
  6429. EXPECT_EQ(test_content, pre_compression_body);
  6430. // Verify post-compression content is compressed
  6431. EXPECT_NE(test_content, post_compression_body);
  6432. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6433. }
  6434. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6435. const std::string test_content =
  6436. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6437. "3456789012345678901234567890";
  6438. std::string pre_compression_body;
  6439. std::string post_compression_body;
  6440. svr_.set_pre_compression_logger(
  6441. [&](const Request & /*req*/, const Response &res) {
  6442. pre_compression_body = res.body;
  6443. });
  6444. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6445. post_compression_body = res.body;
  6446. });
  6447. // Request without compression (use /nocompress endpoint)
  6448. Headers headers;
  6449. auto res = cli_.Get("/nocompress", headers);
  6450. ASSERT_TRUE(res);
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6453. // Pre-compression logger should not be called when no compression is applied
  6454. EXPECT_TRUE(
  6455. pre_compression_body.empty()); // Pre-compression logger not called
  6456. EXPECT_EQ(
  6457. test_content,
  6458. post_compression_body); // Post-compression logger captures final content
  6459. }
  6460. TEST_F(ServerTest, LoggerSeesContentLength) {
  6461. size_t logged_content_length = 0;
  6462. std::string logged_content_length_header;
  6463. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6464. logged_content_length = res.content_length_;
  6465. logged_content_length_header = res.get_header_value("Content-Length");
  6466. });
  6467. auto res = cli_.Get("/nocompress");
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. EXPECT_EQ(res->body.size(), logged_content_length);
  6471. EXPECT_EQ(std::to_string(logged_content_length),
  6472. logged_content_length_header);
  6473. }
  6474. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6475. const std::string test_content =
  6476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6477. "3456789012345678901234567890";
  6478. std::string pre_compression_body;
  6479. bool pre_logger_called = false;
  6480. // Set only pre-compression logger
  6481. svr_.set_pre_compression_logger(
  6482. [&](const Request & /*req*/, const Response &res) {
  6483. pre_compression_body = res.body;
  6484. pre_logger_called = true;
  6485. });
  6486. Headers headers;
  6487. headers.emplace("Accept-Encoding", "gzip");
  6488. auto res = cli_.Get("/compress", headers);
  6489. ASSERT_TRUE(res);
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6492. // Verify pre-compression logger was called
  6493. EXPECT_TRUE(pre_logger_called);
  6494. EXPECT_EQ(test_content, pre_compression_body);
  6495. }
  6496. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6497. {
  6498. // Test with Expect: 100-continue header - success case
  6499. // Server returns 100 Continue, client sends body, server returns 200 OK
  6500. Request req;
  6501. req.method = "POST";
  6502. req.path = "/post-large";
  6503. req.set_header("Expect", "100-continue");
  6504. req.body = LARGE_DATA;
  6505. Response res;
  6506. auto error = Error::Success;
  6507. cli_.set_keep_alive(true);
  6508. auto ret = cli_.send(req, res, error);
  6509. EXPECT_TRUE(ret);
  6510. EXPECT_EQ(StatusCode::OK_200, res.status);
  6511. EXPECT_EQ(LARGE_DATA, res.body);
  6512. }
  6513. {
  6514. // Test with Expect: 100-continue header - error case
  6515. // Client should not send the body when server returns an error
  6516. Request req;
  6517. req.method = "POST";
  6518. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6519. req.set_header("Expect", "100-continue");
  6520. req.body = LARGE_DATA;
  6521. Response res;
  6522. auto error = Error::Success;
  6523. auto start = std::chrono::high_resolution_clock::now();
  6524. cli_.set_keep_alive(true);
  6525. auto ret = cli_.send(req, res, error);
  6526. auto end = std::chrono::high_resolution_clock::now();
  6527. auto elapsed =
  6528. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6529. .count();
  6530. // With Expect: 100-continue, request completes successfully but with error
  6531. EXPECT_TRUE(ret);
  6532. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6533. EXPECT_EQ("close", res.get_header_value("Connection"));
  6534. EXPECT_FALSE(cli_.is_socket_open());
  6535. EXPECT_LE(elapsed, 2000);
  6536. }
  6537. {
  6538. // Send an extra GET request to ensure error recovery without hanging
  6539. Request req;
  6540. req.method = "GET";
  6541. req.path = "/hi";
  6542. auto start = std::chrono::high_resolution_clock::now();
  6543. auto res = cli_.send(req);
  6544. auto end = std::chrono::high_resolution_clock::now();
  6545. auto elapsed =
  6546. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6547. .count();
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::OK_200, res->status);
  6550. EXPECT_EQ("Hello World!", res->body);
  6551. EXPECT_LE(elapsed, 500);
  6552. }
  6553. }
  6554. TEST(ZstdDecompressor, ChunkedDecompression) {
  6555. std::string data;
  6556. for (size_t i = 0; i < 32 * 1024; ++i) {
  6557. data.push_back(static_cast<char>('a' + i % 26));
  6558. }
  6559. std::string compressed_data;
  6560. {
  6561. httplib::detail::zstd_compressor compressor;
  6562. bool result = compressor.compress(
  6563. data.data(), data.size(),
  6564. /*last=*/true,
  6565. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6566. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6567. compressed_data_size);
  6568. return true;
  6569. });
  6570. ASSERT_TRUE(result);
  6571. }
  6572. std::string decompressed_data;
  6573. {
  6574. httplib::detail::zstd_decompressor decompressor;
  6575. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6576. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6577. size_t chunk_size = 130;
  6578. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6579. chunk_begin += chunk_size) {
  6580. size_t current_chunk_size =
  6581. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6582. bool result = decompressor.decompress(
  6583. compressed_data.data() + chunk_begin, current_chunk_size,
  6584. [&](const char *decompressed_data_chunk,
  6585. size_t decompressed_data_chunk_size) {
  6586. decompressed_data.insert(decompressed_data.size(),
  6587. decompressed_data_chunk,
  6588. decompressed_data_chunk_size);
  6589. return true;
  6590. });
  6591. ASSERT_TRUE(result);
  6592. }
  6593. }
  6594. ASSERT_EQ(data, decompressed_data);
  6595. }
  6596. TEST(ZstdDecompressor, Decompress) {
  6597. std::string original_text = "Compressed with ZSTD";
  6598. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6599. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6600. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6601. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6602. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6603. std::string decompressed_data;
  6604. {
  6605. httplib::detail::zstd_decompressor decompressor;
  6606. bool result = decompressor.decompress(
  6607. compressed_data.data(), compressed_data.size(),
  6608. [&](const char *decompressed_data_chunk,
  6609. size_t decompressed_data_chunk_size) {
  6610. decompressed_data.insert(decompressed_data.size(),
  6611. decompressed_data_chunk,
  6612. decompressed_data_chunk_size);
  6613. return true;
  6614. });
  6615. ASSERT_TRUE(result);
  6616. }
  6617. ASSERT_EQ(original_text, decompressed_data);
  6618. }
  6619. #endif
  6620. // Sends a raw request to a server listening at HOST:PORT.
  6621. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6622. std::string *resp = nullptr) {
  6623. auto error = Error::Success;
  6624. auto client_sock = detail::create_client_socket(
  6625. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6626. /*connection_timeout_sec=*/5, 0,
  6627. /*read_timeout_sec=*/5, 0,
  6628. /*write_timeout_sec=*/5, 0, std::string(), error);
  6629. if (client_sock == INVALID_SOCKET) { return false; }
  6630. auto ret = detail::process_client_socket(
  6631. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6632. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6633. if (req.size() !=
  6634. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6635. return false;
  6636. }
  6637. char buf[512];
  6638. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6639. while (line_reader.getline()) {
  6640. if (resp) { *resp += line_reader.ptr(); }
  6641. }
  6642. return true;
  6643. });
  6644. detail::close_socket(client_sock);
  6645. return ret;
  6646. }
  6647. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6648. Server svr;
  6649. std::string header_value;
  6650. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6651. header_value = req.get_header_value("foo");
  6652. res.set_content("ok", "text/plain");
  6653. });
  6654. thread t = thread([&] { svr.listen(HOST, PORT); });
  6655. auto se = detail::scope_exit([&] {
  6656. svr.stop();
  6657. t.join();
  6658. ASSERT_FALSE(svr.is_running());
  6659. });
  6660. svr.wait_until_ready();
  6661. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6662. // like characters are not treated the same - use vertical tab and escape.
  6663. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6664. "foo: \t \v bar \x1B\t \r\n"
  6665. "Connection: close\r\n"
  6666. "\r\n";
  6667. std::string res;
  6668. ASSERT_TRUE(send_request(5, req, &res));
  6669. EXPECT_EQ(header_value, "");
  6670. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6671. }
  6672. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6673. Server svr;
  6674. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6675. auto i = new int(0);
  6676. res.set_header("Trailer", "X-Safe, X-Reflected");
  6677. res.set_chunked_content_provider(
  6678. "text/plain",
  6679. [i](size_t /*offset*/, DataSink &sink) {
  6680. if (*i == 0) {
  6681. sink.os << "body";
  6682. } else {
  6683. Headers trailer;
  6684. // A valid trailer that must survive.
  6685. trailer.emplace("X-Safe", "safe");
  6686. // Attacker-controlled value carrying CR/LF (response splitting).
  6687. trailer.emplace("X-Reflected",
  6688. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6689. // Attacker-controlled name carrying CR/LF.
  6690. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6691. sink.done_with_trailer(trailer);
  6692. }
  6693. (*i)++;
  6694. return true;
  6695. },
  6696. [i](bool /*success*/) { delete i; });
  6697. });
  6698. thread t = thread([&] { svr.listen(HOST, PORT); });
  6699. auto se = detail::scope_exit([&] {
  6700. svr.stop();
  6701. t.join();
  6702. ASSERT_FALSE(svr.is_running());
  6703. });
  6704. svr.wait_until_ready();
  6705. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6706. "Host: " + HOST +
  6707. "\r\n"
  6708. "Connection: close\r\n"
  6709. "\r\n";
  6710. std::string res;
  6711. ASSERT_TRUE(send_request(5, req, &res));
  6712. // The injected fields must not appear anywhere in the raw response.
  6713. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6714. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6715. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6716. // Invalid trailers are dropped entirely, matching set_header().
  6717. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6718. // The valid trailer still passes through.
  6719. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6720. }
  6721. // Sends a raw request and verifies that there isn't a crash or exception.
  6722. static void test_raw_request(const std::string &req,
  6723. std::string *out = nullptr) {
  6724. Server svr;
  6725. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6726. res.set_content("ok", "text/plain");
  6727. });
  6728. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6729. res.set_content("ok", "text/plain");
  6730. });
  6731. svr.Get("/header_field_value_check",
  6732. [&](const Request & /*req*/, Response &res) {
  6733. res.set_content("ok", "text/plain");
  6734. });
  6735. // Server read timeout must be longer than the client read timeout for the
  6736. // bug to reproduce, probably to force the server to process a request
  6737. // without a trailing blank line.
  6738. const time_t client_read_timeout_sec = 1;
  6739. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6740. bool listen_thread_ok = false;
  6741. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6742. auto se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. t.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. EXPECT_TRUE(listen_thread_ok);
  6747. });
  6748. svr.wait_until_ready();
  6749. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6750. }
  6751. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6752. // A certain header line causes an exception if the header property is parsed
  6753. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6754. test_raw_request(
  6755. "GET /hi HTTP/1.1\r\n"
  6756. " : "
  6757. " "
  6758. " ");
  6759. }
  6760. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6761. // A certain header line causes an exception if the header property *name* is
  6762. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6763. // greedy matcher and requires backtracking when there are a lot of ":"
  6764. // characters.
  6765. // This occurs with libc++ but not libstdc++.
  6766. test_raw_request(
  6767. "GET /hi HTTP/1.1\r\n"
  6768. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6769. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6770. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6771. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6772. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6773. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6774. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6775. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6776. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6777. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6778. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6779. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6780. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6781. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6782. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6783. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6784. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6785. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6786. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6787. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6788. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6789. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6790. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6791. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6792. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6793. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6794. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6795. "&&&%%%");
  6796. }
  6797. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6798. // Make sure this doesn't crash the server.
  6799. // In a previous version of the header line regex, the "\r" rendered the line
  6800. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6801. // a new position where the leading white space ended and the field value
  6802. // began.
  6803. // The crash occurs with libc++ but not libstdc++.
  6804. test_raw_request("GET /hi HTTP/1.1\r\n"
  6805. "a:" +
  6806. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6807. "\r\n"
  6808. "\r\n");
  6809. }
  6810. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6811. std::string out;
  6812. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6813. "Content-Type: text/plain\r\n"
  6814. "Transfer-Encoding: chunked\r\n"
  6815. "\r\n"
  6816. "nothex\r\n",
  6817. &out);
  6818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6819. }
  6820. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6821. std::string out;
  6822. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6823. "Content-Type: text/plain\r\n"
  6824. "Transfer-Encoding: chunked\r\n"
  6825. "\r\n"
  6826. "3\r\n"
  6827. "xyz\r\n"
  6828. "NaN\r\n",
  6829. &out);
  6830. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6831. }
  6832. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6833. std::string out;
  6834. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6835. "Content-Type: text/plain\r\n"
  6836. "Transfer-Encoding: chunked\r\n"
  6837. "\r\n"
  6838. // Length is too large for 64 bits.
  6839. "1ffffffffffffffff\r\n"
  6840. "xyz\r\n",
  6841. &out);
  6842. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6843. }
  6844. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6845. test_raw_request("GET /hi HTTP/1.1\r\n"
  6846. "Content-Type: text/plain\r\n\r");
  6847. }
  6848. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6849. std::string out;
  6850. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6852. }
  6853. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6854. Server svr;
  6855. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6856. EXPECT_TRUE(!req.remote_addr.empty());
  6857. });
  6858. thread t = thread([&] { svr.listen(HOST, PORT); });
  6859. auto se = detail::scope_exit([&] {
  6860. svr.stop();
  6861. t.join();
  6862. ASSERT_FALSE(svr.is_running());
  6863. });
  6864. svr.wait_until_ready();
  6865. // Send an invalid request line to trigger Bad Request
  6866. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6867. std::string out;
  6868. ASSERT_TRUE(send_request(5, bad_req, &out));
  6869. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6870. }
  6871. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6872. std::string out;
  6873. std::string request(
  6874. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6875. test_raw_request(request, &out);
  6876. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6877. }
  6878. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6879. std::string out;
  6880. std::string request(
  6881. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6882. test_raw_request(request, &out);
  6883. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6884. }
  6885. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6886. std::string out;
  6887. std::string request(
  6888. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6889. test_raw_request(request, &out);
  6890. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6891. }
  6892. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6893. std::string out;
  6894. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6895. "Test: \r\n\r\n",
  6896. &out);
  6897. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6898. }
  6899. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6900. Server svr;
  6901. std::string x_custom;
  6902. std::string cookie;
  6903. std::string xff;
  6904. std::string x_unicode;
  6905. std::string x_iis;
  6906. svr.Get("/check", [&](const Request &req, Response &res) {
  6907. x_custom = req.get_header_value("X-Custom");
  6908. cookie = req.get_header_value("Cookie");
  6909. xff = req.get_header_value("X-Forwarded-For");
  6910. x_unicode = req.get_header_value("X-Unicode");
  6911. x_iis = req.get_header_value("X-IIS");
  6912. res.set_content("ok", "text/plain");
  6913. });
  6914. thread t = thread([&] { svr.listen(HOST, PORT); });
  6915. auto se = detail::scope_exit([&] {
  6916. svr.stop();
  6917. t.join();
  6918. ASSERT_FALSE(svr.is_running());
  6919. });
  6920. svr.wait_until_ready();
  6921. const std::string req = "GET /check HTTP/1.1\r\n"
  6922. "Host: localhost\r\n"
  6923. "X-Custom: a%0D%0AInjected: b\r\n"
  6924. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6925. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6926. "X-Unicode: %E3%81%82\r\n"
  6927. "X-IIS: %u00E9\r\n"
  6928. "Connection: close\r\n"
  6929. "\r\n";
  6930. std::string res;
  6931. ASSERT_TRUE(send_request(5, req, &res));
  6932. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6933. // Every value must be returned verbatim (wire form), with no decoding.
  6934. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6935. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6936. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6937. EXPECT_EQ("%E3%81%82", x_unicode);
  6938. EXPECT_EQ("%u00E9", x_iis);
  6939. }
  6940. // Applications that previously relied on automatic percent-decoding can
  6941. // reproduce the old behavior by explicitly calling decode_path_component()
  6942. // or, for RFC 3986 conformance, decode_uri_component().
  6943. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6944. Server svr;
  6945. std::string decoded;
  6946. svr.Get("/check", [&](const Request &req, Response &res) {
  6947. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6948. res.set_content("ok", "text/plain");
  6949. });
  6950. thread t = thread([&] { svr.listen(HOST, PORT); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. const std::string req = "GET /check HTTP/1.1\r\n"
  6958. "Host: localhost\r\n"
  6959. "X-Custom: hello%20world\r\n"
  6960. "Connection: close\r\n"
  6961. "\r\n";
  6962. std::string res;
  6963. ASSERT_TRUE(send_request(5, req, &res));
  6964. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6965. EXPECT_EQ("hello world", decoded);
  6966. }
  6967. // Regression test for #2033. Browsers send Referer values that include
  6968. // percent-encoded characters such as %0A inside the URL. Decoding the
  6969. // header value would either trip the post-decode CR/LF/NUL guard (the
  6970. // original bug, returning 400) or, after that guard was relaxed, silently
  6971. // store a literal LF — both unacceptable. The wire form must round-trip.
  6972. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6973. Server svr;
  6974. std::string referer;
  6975. svr.Get("/check", [&](const Request &req, Response &res) {
  6976. referer = req.get_header_value("Referer");
  6977. res.set_content("ok", "text/plain");
  6978. });
  6979. thread t = thread([&] { svr.listen(HOST, PORT); });
  6980. auto se = detail::scope_exit([&] {
  6981. svr.stop();
  6982. t.join();
  6983. ASSERT_FALSE(svr.is_running());
  6984. });
  6985. svr.wait_until_ready();
  6986. const std::string req = "GET /check HTTP/1.1\r\n"
  6987. "Host: localhost\r\n"
  6988. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6989. "Connection: close\r\n"
  6990. "\r\n";
  6991. std::string res;
  6992. ASSERT_TRUE(send_request(5, req, &res));
  6993. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6994. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6995. }
  6996. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6997. Server svr;
  6998. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6999. res.set_header("Cache-Control", "no-cache");
  7000. res.set_chunked_content_provider(
  7001. "text/event-stream", [](size_t offset, DataSink &sink) {
  7002. std::string s = "data:";
  7003. s += std::to_string(offset);
  7004. s += "\n\n";
  7005. auto ret = sink.write(s.data(), s.size());
  7006. EXPECT_TRUE(ret);
  7007. std::this_thread::sleep_for(std::chrono::seconds(1));
  7008. return true;
  7009. });
  7010. });
  7011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7012. svr.wait_until_ready();
  7013. Client client(HOST, PORT);
  7014. const Headers headers = {{"Accept", "text/event-stream"}};
  7015. auto get_thread = std::thread([&client, &headers]() {
  7016. auto res = client.Get(
  7017. "/events", headers,
  7018. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7019. });
  7020. auto se = detail::scope_exit([&] {
  7021. svr.stop();
  7022. get_thread.join();
  7023. listen_thread.join();
  7024. ASSERT_FALSE(svr.is_running());
  7025. });
  7026. // Give GET time to get a few messages.
  7027. std::this_thread::sleep_for(std::chrono::seconds(2));
  7028. }
  7029. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7030. httplib::Server svr;
  7031. svr.Post("/hi",
  7032. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7033. res.status = StatusCode::OK_200;
  7034. });
  7035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7036. svr.wait_until_ready();
  7037. Client cli(HOST, PORT);
  7038. auto res = cli.Post("/hi", "data", "text/plain");
  7039. ASSERT_TRUE(res);
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. svr.stop();
  7042. thread.join();
  7043. ASSERT_FALSE(svr.is_running());
  7044. res = cli.Post("/hi", "data", "text/plain");
  7045. ASSERT_FALSE(res);
  7046. }
  7047. TEST(ServerStopTest, ListenFailure) {
  7048. Server svr;
  7049. auto t = thread([&]() {
  7050. auto ret = svr.listen("????", PORT);
  7051. EXPECT_FALSE(ret);
  7052. });
  7053. svr.wait_until_ready();
  7054. svr.stop();
  7055. t.join();
  7056. }
  7057. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7058. TEST(ServerStopTest, Decommision) {
  7059. Server svr;
  7060. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7061. for (int i = 0; i < 4; i++) {
  7062. auto is_even = !(i % 2);
  7063. std::thread t{[&] {
  7064. try {
  7065. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7066. if (is_even) {
  7067. throw std::runtime_error("Some thing that happens to go wrong.");
  7068. }
  7069. svr.listen(HOST, PORT);
  7070. } catch (...) { svr.decommission(); }
  7071. }};
  7072. svr.wait_until_ready();
  7073. // Server is up
  7074. {
  7075. Client cli(HOST, PORT);
  7076. auto res = cli.Get("/hi");
  7077. if (is_even) {
  7078. EXPECT_FALSE(res);
  7079. } else {
  7080. EXPECT_TRUE(res);
  7081. EXPECT_EQ("hi...", res->body);
  7082. }
  7083. }
  7084. svr.stop();
  7085. t.join();
  7086. // Server is down...
  7087. {
  7088. Client cli(HOST, PORT);
  7089. auto res = cli.Get("/hi");
  7090. EXPECT_FALSE(res);
  7091. }
  7092. }
  7093. }
  7094. #endif
  7095. // Helper function for string body upload progress tests
  7096. template <typename SetupHandler, typename ClientCall>
  7097. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7098. ClientCall &&client_call,
  7099. const string &body) {
  7100. Server svr;
  7101. setup_handler(svr);
  7102. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7103. auto se = detail::scope_exit([&] {
  7104. svr.stop();
  7105. t.join();
  7106. });
  7107. svr.wait_until_ready();
  7108. Client cli(HOST, PORT);
  7109. vector<uint64_t> progress_values;
  7110. bool progress_called = false;
  7111. auto res =
  7112. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7113. progress_values.push_back(current);
  7114. progress_called = true;
  7115. return true;
  7116. });
  7117. ASSERT_TRUE(res);
  7118. EXPECT_EQ(200, res->status);
  7119. EXPECT_TRUE(progress_called);
  7120. }
  7121. TEST(UploadProgressTest, PostStringBodyBasic) {
  7122. TestStringBodyUploadProgress(
  7123. [](Server &svr) {
  7124. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7125. res.set_content("received", "text/plain");
  7126. });
  7127. },
  7128. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7129. return cli.Post("/test", body, "text/plain", progress_callback);
  7130. },
  7131. "test data for upload progress");
  7132. }
  7133. TEST(UploadProgressTest, PutStringBodyBasic) {
  7134. TestStringBodyUploadProgress(
  7135. [](Server &svr) {
  7136. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7137. res.set_content("put received", "text/plain");
  7138. });
  7139. },
  7140. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7141. return cli.Put("/test", body, "text/plain", progress_callback);
  7142. },
  7143. "put test data for upload progress");
  7144. }
  7145. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7146. TestStringBodyUploadProgress(
  7147. [](Server &svr) {
  7148. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7149. res.set_content("patch received", "text/plain");
  7150. });
  7151. },
  7152. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7153. return cli.Patch("/test", body, "text/plain", progress_callback);
  7154. },
  7155. "patch test data for upload progress");
  7156. }
  7157. // Helper function for content provider upload progress tests
  7158. template <typename SetupHandler, typename ClientCall>
  7159. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7160. ClientCall &&client_call) {
  7161. Server svr;
  7162. setup_handler(svr);
  7163. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7164. auto se = detail::scope_exit([&] {
  7165. svr.stop();
  7166. t.join();
  7167. });
  7168. svr.wait_until_ready();
  7169. Client cli(HOST, PORT);
  7170. vector<uint64_t> progress_values;
  7171. auto res =
  7172. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7173. progress_values.push_back(current);
  7174. return true;
  7175. });
  7176. ASSERT_TRUE(res);
  7177. EXPECT_EQ(200, res->status);
  7178. EXPECT_FALSE(progress_values.empty());
  7179. }
  7180. TEST(UploadProgressTest, PostContentProviderProgress) {
  7181. TestContentProviderUploadProgress(
  7182. [](Server &svr) {
  7183. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7184. res.set_content("provider received", "text/plain");
  7185. });
  7186. },
  7187. [](Client &cli, UploadProgress progress_callback) {
  7188. return cli.Post(
  7189. "/test", 10,
  7190. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7191. sink.os << "test data";
  7192. return true;
  7193. },
  7194. "text/plain", progress_callback);
  7195. });
  7196. }
  7197. // Helper function for multipart upload progress tests
  7198. template <typename SetupHandler, typename ClientCall>
  7199. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7200. ClientCall &&client_call,
  7201. const string &endpoint) {
  7202. Server svr;
  7203. setup_handler(svr);
  7204. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7205. auto se = detail::scope_exit([&] {
  7206. svr.stop();
  7207. t.join();
  7208. });
  7209. svr.wait_until_ready();
  7210. Client cli(HOST, PORT);
  7211. vector<uint64_t> progress_values;
  7212. UploadFormDataItems items = {
  7213. {"field1", "value1", "", ""},
  7214. {"field2", "longer value for progress tracking test", "", ""},
  7215. {"file1", "file content data for upload progress", "test.txt",
  7216. "text/plain"}};
  7217. auto res = client_call(cli, endpoint, items,
  7218. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7219. progress_values.push_back(current);
  7220. return true;
  7221. });
  7222. ASSERT_TRUE(res);
  7223. EXPECT_EQ(200, res->status);
  7224. EXPECT_FALSE(progress_values.empty());
  7225. }
  7226. TEST(UploadProgressTest, PostMultipartProgress) {
  7227. TestMultipartUploadProgress(
  7228. [](Server &svr) {
  7229. svr.Post("/multipart", [](const Request &req, Response &res) {
  7230. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7231. res.set_content("multipart received", "text/plain");
  7232. });
  7233. },
  7234. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7235. UploadProgress progress_callback) {
  7236. return cli.Post(endpoint, items, progress_callback);
  7237. },
  7238. "/multipart");
  7239. }
  7240. // Helper function for basic download progress tests
  7241. template <typename SetupHandler, typename ClientCall>
  7242. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7243. ClientCall &&client_call, const string &endpoint,
  7244. size_t expected_content_size) {
  7245. Server svr;
  7246. setup_handler(svr);
  7247. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7248. auto se = detail::scope_exit([&] {
  7249. svr.stop();
  7250. t.join();
  7251. });
  7252. svr.wait_until_ready();
  7253. Client cli(HOST, PORT);
  7254. vector<uint64_t> progress_values;
  7255. auto res = client_call(cli, endpoint,
  7256. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7257. progress_values.push_back(current);
  7258. return true;
  7259. });
  7260. ASSERT_TRUE(res);
  7261. EXPECT_EQ(200, res->status);
  7262. EXPECT_FALSE(progress_values.empty());
  7263. EXPECT_EQ(expected_content_size, res->body.size());
  7264. }
  7265. TEST(DownloadProgressTest, GetBasic) {
  7266. TestBasicDownloadProgress(
  7267. [](Server &svr) {
  7268. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7269. string content(1000, 'D');
  7270. res.set_content(content, "text/plain");
  7271. });
  7272. },
  7273. [](Client &cli, const string &endpoint,
  7274. DownloadProgress progress_callback) {
  7275. return cli.Get(endpoint, progress_callback);
  7276. },
  7277. "/download", 1000u);
  7278. }
  7279. // Helper function for content receiver download progress tests
  7280. template <typename SetupHandler, typename ClientCall>
  7281. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7282. ClientCall &&client_call,
  7283. const string &endpoint,
  7284. size_t expected_content_size) {
  7285. Server svr;
  7286. setup_handler(svr);
  7287. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7288. auto se = detail::scope_exit([&] {
  7289. svr.stop();
  7290. t.join();
  7291. });
  7292. svr.wait_until_ready();
  7293. Client cli(HOST, PORT);
  7294. vector<uint64_t> progress_values;
  7295. string received_body;
  7296. auto res = client_call(
  7297. cli, endpoint,
  7298. [&](const char *data, size_t data_length) -> bool {
  7299. received_body.append(data, data_length);
  7300. return true;
  7301. },
  7302. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7303. progress_values.push_back(current);
  7304. return true;
  7305. });
  7306. ASSERT_TRUE(res);
  7307. EXPECT_EQ(200, res->status);
  7308. EXPECT_FALSE(progress_values.empty());
  7309. EXPECT_EQ(expected_content_size, received_body.size());
  7310. EXPECT_TRUE(res->body.empty());
  7311. }
  7312. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7313. TestContentReceiverDownloadProgress(
  7314. [](Server &svr) {
  7315. svr.Get("/download-receiver",
  7316. [](const Request & /*req*/, Response &res) {
  7317. string content(2000, 'R');
  7318. res.set_content(content, "text/plain");
  7319. });
  7320. },
  7321. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7322. DownloadProgress progress_callback) {
  7323. return cli.Get(endpoint, content_receiver, progress_callback);
  7324. },
  7325. "/download-receiver", 2000u);
  7326. }
  7327. TEST(StreamingTest, NoContentLengthStreaming) {
  7328. Server svr;
  7329. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7330. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7331. if (offset < 6) {
  7332. sink.os << (offset < 3 ? "a" : "b");
  7333. } else {
  7334. sink.done();
  7335. }
  7336. return true;
  7337. });
  7338. });
  7339. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7340. auto listen_se = detail::scope_exit([&] {
  7341. svr.stop();
  7342. listen_thread.join();
  7343. ASSERT_FALSE(svr.is_running());
  7344. });
  7345. svr.wait_until_ready();
  7346. Client client(HOST, PORT);
  7347. auto get_thread = std::thread([&client]() {
  7348. std::string s;
  7349. auto res =
  7350. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7351. s += std::string(data, len);
  7352. return true;
  7353. });
  7354. ASSERT_TRUE(res);
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("aaabbb", s);
  7357. });
  7358. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7359. // Give GET time to get a few messages.
  7360. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7361. }
  7362. TEST(MountTest, Unmount) {
  7363. Server svr;
  7364. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7365. auto se = detail::scope_exit([&] {
  7366. svr.stop();
  7367. listen_thread.join();
  7368. ASSERT_FALSE(svr.is_running());
  7369. });
  7370. svr.wait_until_ready();
  7371. Client cli("localhost", PORT);
  7372. svr.set_mount_point("/mount2", "./www2");
  7373. auto res = cli.Get("/");
  7374. ASSERT_TRUE(res);
  7375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7376. res = cli.Get("/mount2/dir/test.html");
  7377. ASSERT_TRUE(res);
  7378. EXPECT_EQ(StatusCode::OK_200, res->status);
  7379. svr.set_mount_point("/", "./www");
  7380. res = cli.Get("/dir/");
  7381. ASSERT_TRUE(res);
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. svr.remove_mount_point("/");
  7384. res = cli.Get("/dir/");
  7385. ASSERT_TRUE(res);
  7386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7387. svr.remove_mount_point("/mount2");
  7388. res = cli.Get("/mount2/dir/test.html");
  7389. ASSERT_TRUE(res);
  7390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7391. }
  7392. TEST(MountTest, Redicect) {
  7393. Server svr;
  7394. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7395. auto se = detail::scope_exit([&] {
  7396. svr.stop();
  7397. listen_thread.join();
  7398. ASSERT_FALSE(svr.is_running());
  7399. });
  7400. svr.set_mount_point("/", "./www");
  7401. svr.wait_until_ready();
  7402. Client cli("localhost", PORT);
  7403. auto res = cli.Get("/dir/");
  7404. ASSERT_TRUE(res);
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. res = cli.Get("/dir");
  7407. ASSERT_TRUE(res);
  7408. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7409. res = cli.Get("/file");
  7410. ASSERT_TRUE(res);
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. res = cli.Get("/file/");
  7413. ASSERT_TRUE(res);
  7414. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7415. cli.set_follow_location(true);
  7416. res = cli.Get("/dir");
  7417. ASSERT_TRUE(res);
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. }
  7420. TEST(MountTest, MultibytesPathName) {
  7421. Server svr;
  7422. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7423. auto se = detail::scope_exit([&] {
  7424. svr.stop();
  7425. listen_thread.join();
  7426. ASSERT_FALSE(svr.is_running());
  7427. });
  7428. svr.set_mount_point("/", "./www");
  7429. svr.wait_until_ready();
  7430. Client cli("localhost", PORT);
  7431. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7432. ASSERT_TRUE(res);
  7433. EXPECT_EQ(StatusCode::OK_200, res->status);
  7434. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7435. }
  7436. #ifdef _WIN32
  7437. // Issue #2435: mmap::open() must succeed even when another handle holds
  7438. // the file open for writing (e.g. an active log file).
  7439. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7440. const char *path = "mmap_concurrent_writer_test.txt";
  7441. const char *content = "hello";
  7442. {
  7443. std::ofstream f(path, std::ios::binary);
  7444. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7445. }
  7446. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7447. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7448. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7449. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7450. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7451. detail::mmap m(path);
  7452. ASSERT_TRUE(m.is_open());
  7453. EXPECT_EQ(strlen(content), m.size());
  7454. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7455. }
  7456. #endif
  7457. TEST(KeepAliveTest, ReadTimeout) {
  7458. Server svr;
  7459. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7460. std::this_thread::sleep_for(std::chrono::seconds(2));
  7461. res.set_content("a", "text/plain");
  7462. });
  7463. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7464. res.set_content("b", "text/plain");
  7465. });
  7466. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7467. auto se = detail::scope_exit([&] {
  7468. svr.stop();
  7469. listen_thread.join();
  7470. ASSERT_FALSE(svr.is_running());
  7471. });
  7472. svr.wait_until_ready();
  7473. Client cli("localhost", PORT);
  7474. cli.set_keep_alive(true);
  7475. cli.set_read_timeout(std::chrono::seconds(1));
  7476. auto resa = cli.Get("/a");
  7477. ASSERT_FALSE(resa);
  7478. EXPECT_EQ(Error::Read, resa.error());
  7479. auto resb = cli.Get("/b");
  7480. ASSERT_TRUE(resb);
  7481. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7482. EXPECT_EQ("b", resb->body);
  7483. }
  7484. TEST(KeepAliveTest, MaxCount) {
  7485. size_t keep_alive_max_count = 3;
  7486. Server svr;
  7487. svr.set_keep_alive_max_count(keep_alive_max_count);
  7488. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7489. res.set_content("Hello World!", "text/plain");
  7490. });
  7491. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7492. auto se = detail::scope_exit([&] {
  7493. svr.stop();
  7494. listen_thread.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. Client cli(HOST, PORT);
  7499. cli.set_keep_alive(true);
  7500. for (size_t i = 0; i < 5; i++) {
  7501. auto result = cli.Get("/hi");
  7502. ASSERT_TRUE(result);
  7503. EXPECT_EQ(StatusCode::OK_200, result->status);
  7504. if (i == keep_alive_max_count - 1) {
  7505. EXPECT_EQ("close", result->get_header_value("Connection"));
  7506. } else {
  7507. EXPECT_FALSE(result->has_header("Connection"));
  7508. }
  7509. }
  7510. }
  7511. TEST(KeepAliveTest, Issue1041) {
  7512. Server svr;
  7513. svr.set_keep_alive_timeout(3);
  7514. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7515. res.set_content("Hello World!", "text/plain");
  7516. });
  7517. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7518. auto se = detail::scope_exit([&] {
  7519. svr.stop();
  7520. listen_thread.join();
  7521. ASSERT_FALSE(svr.is_running());
  7522. });
  7523. svr.wait_until_ready();
  7524. Client cli(HOST, PORT);
  7525. cli.set_keep_alive(true);
  7526. auto result = cli.Get("/hi");
  7527. ASSERT_TRUE(result);
  7528. EXPECT_EQ(StatusCode::OK_200, result->status);
  7529. std::this_thread::sleep_for(std::chrono::seconds(5));
  7530. result = cli.Get("/hi");
  7531. ASSERT_TRUE(result);
  7532. EXPECT_EQ(StatusCode::OK_200, result->status);
  7533. }
  7534. TEST(KeepAliveTest, Issue1959) {
  7535. Server svr;
  7536. svr.set_keep_alive_timeout(5);
  7537. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7538. res.set_content("a", "text/plain");
  7539. });
  7540. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7541. auto se = detail::scope_exit([&] {
  7542. if (!svr.is_running()) return;
  7543. svr.stop();
  7544. listen_thread.join();
  7545. ASSERT_FALSE(svr.is_running());
  7546. });
  7547. svr.wait_until_ready();
  7548. Client cli("localhost", PORT);
  7549. cli.set_keep_alive(true);
  7550. using namespace std::chrono;
  7551. auto start = steady_clock::now();
  7552. cli.Get("/a");
  7553. svr.stop();
  7554. listen_thread.join();
  7555. auto end = steady_clock::now();
  7556. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7557. EXPECT_LT(elapsed, 5000);
  7558. }
  7559. #ifdef CPPHTTPLIB_SSL_ENABLED
  7560. TEST(KeepAliveTest, SSLClientReconnection) {
  7561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7562. ASSERT_TRUE(svr.is_valid());
  7563. svr.set_keep_alive_timeout(1);
  7564. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7565. res.set_content("Hello World!", "text/plain");
  7566. });
  7567. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7568. auto se = detail::scope_exit([&] {
  7569. svr.stop();
  7570. listen_thread.join();
  7571. ASSERT_FALSE(svr.is_running());
  7572. });
  7573. svr.wait_until_ready();
  7574. SSLClient cli(HOST, PORT);
  7575. cli.enable_server_certificate_verification(false);
  7576. cli.set_keep_alive(true);
  7577. auto result = cli.Get("/hi");
  7578. ASSERT_TRUE(result);
  7579. EXPECT_EQ(StatusCode::OK_200, result->status);
  7580. result = cli.Get("/hi");
  7581. ASSERT_TRUE(result);
  7582. EXPECT_EQ(StatusCode::OK_200, result->status);
  7583. std::this_thread::sleep_for(std::chrono::seconds(2));
  7584. // Recoonect
  7585. result = cli.Get("/hi");
  7586. ASSERT_TRUE(result);
  7587. EXPECT_EQ(StatusCode::OK_200, result->status);
  7588. result = cli.Get("/hi");
  7589. ASSERT_TRUE(result);
  7590. EXPECT_EQ(StatusCode::OK_200, result->status);
  7591. }
  7592. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7594. ASSERT_TRUE(svr.is_valid());
  7595. svr.set_keep_alive_timeout(1);
  7596. std::string content = "reconnect";
  7597. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7598. res.set_content("Hello World!", "text/plain");
  7599. });
  7600. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7601. auto se = detail::scope_exit([&] {
  7602. svr.stop();
  7603. listen_thread.join();
  7604. ASSERT_FALSE(svr.is_running());
  7605. });
  7606. svr.wait_until_ready();
  7607. SSLClient cli(HOST, PORT);
  7608. cli.enable_server_certificate_verification(false);
  7609. cli.set_keep_alive(true);
  7610. auto result = cli.Post(
  7611. "/hi", content.size(),
  7612. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7613. sink.write(content.c_str(), content.size());
  7614. return true;
  7615. },
  7616. "text/plain");
  7617. ASSERT_TRUE(result);
  7618. EXPECT_EQ(200, result->status);
  7619. std::this_thread::sleep_for(std::chrono::seconds(2));
  7620. // Recoonect
  7621. result = cli.Post(
  7622. "/hi", content.size(),
  7623. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7624. sink.write(content.c_str(), content.size());
  7625. return true;
  7626. },
  7627. "text/plain");
  7628. ASSERT_TRUE(result);
  7629. EXPECT_EQ(200, result->status);
  7630. result = cli.Post(
  7631. "/hi", content.size(),
  7632. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7633. sink.write(content.c_str(), content.size());
  7634. return true;
  7635. },
  7636. "text/plain");
  7637. ASSERT_TRUE(result);
  7638. EXPECT_EQ(200, result->status);
  7639. }
  7640. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7641. using namespace httplib::tls;
  7642. {
  7643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7644. ASSERT_TRUE(svr.is_valid());
  7645. svr.Get("/sni", [&](const Request &req, Response &res) {
  7646. std::string expected = req.sni();
  7647. EXPECT_EQ(expected, req.get_param_value("expected"));
  7648. res.set_content("ok", "text/plain");
  7649. });
  7650. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7651. auto se = detail::scope_exit([&] {
  7652. svr.stop();
  7653. listen_thread.join();
  7654. ASSERT_FALSE(svr.is_running());
  7655. });
  7656. svr.wait_until_ready();
  7657. {
  7658. SSLClient cli("localhost", PORT);
  7659. cli.enable_server_certificate_verification(false);
  7660. auto res = cli.Get("/sni?expected=localhost");
  7661. ASSERT_TRUE(res);
  7662. }
  7663. {
  7664. SSLClient cli("::1", PORT);
  7665. cli.enable_server_certificate_verification(false);
  7666. auto res = cli.Get("/sni?expected=");
  7667. // NOTE: This may fail if the server is listening on IPv4 only
  7668. // (e.g., when localhost resolves to 127.0.0.1 only)
  7669. if (res) {
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. } else {
  7672. EXPECT_EQ(Error::Connection, res.error());
  7673. }
  7674. }
  7675. }
  7676. }
  7677. #endif
  7678. TEST(ClientProblemDetectionTest, ContentProvider) {
  7679. Server svr;
  7680. size_t content_length = 1024 * 1024;
  7681. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7682. res.set_content_provider(
  7683. content_length, "text/plain",
  7684. [&](size_t offset, size_t length, DataSink &sink) {
  7685. auto out_len = std::min(length, static_cast<size_t>(1024));
  7686. std::string out(out_len, '@');
  7687. sink.write(out.data(), out_len);
  7688. return offset < 4096;
  7689. },
  7690. [](bool success) { ASSERT_FALSE(success); });
  7691. });
  7692. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7693. res.set_content_provider(
  7694. 0, "text/plain",
  7695. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7696. EXPECT_TRUE(false);
  7697. return true;
  7698. },
  7699. [](bool success) { ASSERT_FALSE(success); });
  7700. });
  7701. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7702. auto se = detail::scope_exit([&] {
  7703. svr.stop();
  7704. listen_thread.join();
  7705. ASSERT_FALSE(svr.is_running());
  7706. });
  7707. svr.wait_until_ready();
  7708. Client cli("localhost", PORT);
  7709. {
  7710. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7711. size_t /*data_length*/) { return false; });
  7712. ASSERT_FALSE(res);
  7713. }
  7714. {
  7715. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7716. size_t /*data_length*/) { return false; });
  7717. ASSERT_TRUE(res);
  7718. }
  7719. }
  7720. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7721. Server svr;
  7722. svr.set_error_handler([](Request const &, Response &res) -> void {
  7723. res.set_chunked_content_provider(
  7724. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7725. sink.os << "hello";
  7726. sink.os << "world";
  7727. sink.done();
  7728. return true;
  7729. });
  7730. });
  7731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7732. auto se = detail::scope_exit([&] {
  7733. svr.stop();
  7734. listen_thread.join();
  7735. ASSERT_FALSE(svr.is_running());
  7736. });
  7737. svr.wait_until_ready();
  7738. Client cli("localhost", PORT);
  7739. auto res = cli.Get("/");
  7740. ASSERT_TRUE(res);
  7741. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7742. EXPECT_EQ("helloworld", res->body);
  7743. }
  7744. TEST(LongPollingTest, ClientCloseDetection) {
  7745. Server svr;
  7746. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7747. res.set_chunked_content_provider(
  7748. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7749. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7750. sink.os << "hello";
  7751. auto count = 10;
  7752. while (count > 0 && sink.is_writable()) {
  7753. this_thread::sleep_for(chrono::milliseconds(10));
  7754. count--;
  7755. }
  7756. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7757. return true;
  7758. });
  7759. });
  7760. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7761. auto se = detail::scope_exit([&] {
  7762. svr.stop();
  7763. listen_thread.join();
  7764. ASSERT_FALSE(svr.is_running());
  7765. });
  7766. svr.wait_until_ready();
  7767. Client cli("localhost", PORT);
  7768. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7769. EXPECT_EQ("hello", string(data, data_length));
  7770. return false; // close the socket immediately.
  7771. });
  7772. ASSERT_FALSE(res);
  7773. }
  7774. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7775. Server svr;
  7776. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7777. res.set_chunked_content_provider(
  7778. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7779. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7780. sink.os << "hello";
  7781. EXPECT_TRUE(sink.os.good());
  7782. // Wait for the client to close the connection
  7783. auto count = 10;
  7784. while (count > 0 && sink.is_writable()) {
  7785. this_thread::sleep_for(chrono::milliseconds(10));
  7786. count--;
  7787. }
  7788. // After client disconnect, write repeatedly until the socket
  7789. // write actually fails (small writes may be absorbed by the
  7790. // kernel buffer)
  7791. std::string chunk(1024, 'x');
  7792. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7793. sink.os << chunk;
  7794. }
  7795. EXPECT_TRUE(sink.os.fail());
  7796. return true;
  7797. });
  7798. });
  7799. auto port = svr.bind_to_any_port("localhost");
  7800. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7801. auto se = detail::scope_exit([&] {
  7802. svr.stop();
  7803. listen_thread.join();
  7804. ASSERT_FALSE(svr.is_running());
  7805. });
  7806. svr.wait_until_ready();
  7807. Client cli("localhost", port);
  7808. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7809. EXPECT_EQ("hello", string(data, data_length));
  7810. return false; // close the socket immediately.
  7811. });
  7812. ASSERT_FALSE(res);
  7813. }
  7814. TEST(GetWithParametersTest, GetWithParameters) {
  7815. Server svr;
  7816. svr.Get("/", [&](const Request &req, Response &) {
  7817. EXPECT_EQ("world", req.get_param_value("hello"));
  7818. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7819. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7820. });
  7821. svr.Get("/params", [&](const Request &req, Response &) {
  7822. EXPECT_EQ("world", req.get_param_value("hello"));
  7823. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7824. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7825. });
  7826. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7827. EXPECT_EQ("resource-id", req.matches[1]);
  7828. EXPECT_EQ("foo", req.get_param_value("param1"));
  7829. EXPECT_EQ("bar", req.get_param_value("param2"));
  7830. });
  7831. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7832. EXPECT_EQ("user-id", req.path_params.at("id"));
  7833. EXPECT_EQ("foo", req.get_param_value("param1"));
  7834. EXPECT_EQ("bar", req.get_param_value("param2"));
  7835. });
  7836. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7837. auto se = detail::scope_exit([&] {
  7838. svr.stop();
  7839. listen_thread.join();
  7840. ASSERT_FALSE(svr.is_running());
  7841. });
  7842. svr.wait_until_ready();
  7843. {
  7844. Client cli(HOST, PORT);
  7845. Params params;
  7846. params.emplace("hello", "world");
  7847. params.emplace("hello2", "world2");
  7848. params.emplace("hello3", "world3");
  7849. auto res = cli.Get("/", params, Headers{});
  7850. ASSERT_TRUE(res);
  7851. EXPECT_EQ(StatusCode::OK_200, res->status);
  7852. }
  7853. {
  7854. Client cli(HOST, PORT);
  7855. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7856. ASSERT_TRUE(res);
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. }
  7859. {
  7860. Client cli(HOST, PORT);
  7861. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7862. ASSERT_TRUE(res);
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. }
  7865. {
  7866. Client cli(HOST, PORT);
  7867. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7868. ASSERT_TRUE(res);
  7869. EXPECT_EQ(StatusCode::OK_200, res->status);
  7870. }
  7871. }
  7872. TEST(GetWithParametersTest, GetWithParameters2) {
  7873. Server svr;
  7874. svr.Get("/", [&](const Request &req, Response &res) {
  7875. auto text = req.get_param_value("hello");
  7876. res.set_content(text, "text/plain");
  7877. });
  7878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7879. auto se = detail::scope_exit([&] {
  7880. svr.stop();
  7881. listen_thread.join();
  7882. ASSERT_FALSE(svr.is_running());
  7883. });
  7884. svr.wait_until_ready();
  7885. Client cli("localhost", PORT);
  7886. Params params;
  7887. params.emplace("hello", "world");
  7888. std::string body;
  7889. auto res = cli.Get("/", params, Headers{},
  7890. [&](const char *data, size_t data_length) {
  7891. body.append(data, data_length);
  7892. return true;
  7893. });
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("world", body);
  7897. }
  7898. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7899. Server svr;
  7900. svr.Get("/search", [&](const Request &req, Response &res) {
  7901. auto q = req.get_param_value("q");
  7902. res.set_content(q, "text/plain");
  7903. });
  7904. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7905. auto se = detail::scope_exit([&] {
  7906. svr.stop();
  7907. listen_thread.join();
  7908. ASSERT_FALSE(svr.is_running());
  7909. });
  7910. svr.wait_until_ready();
  7911. Client cli("localhost", PORT);
  7912. // Verify that Get(path, params) works without requiring Headers argument
  7913. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7914. ASSERT_TRUE(res);
  7915. EXPECT_EQ(StatusCode::OK_200, res->status);
  7916. EXPECT_EQ("cpp-httplib", res->body);
  7917. }
  7918. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7919. auto host = "httpbingo.org";
  7920. auto path = std::string{"/range/32"};
  7921. #ifdef CPPHTTPLIB_SSL_ENABLED
  7922. SSLClient cli(host);
  7923. #else
  7924. Client cli(host);
  7925. #endif
  7926. cli.set_default_headers({make_range_header({{1, 10}})});
  7927. cli.set_connection_timeout(5);
  7928. {
  7929. auto res = cli.Get(path);
  7930. ASSERT_TRUE(res);
  7931. EXPECT_EQ("bcdefghijk", res->body);
  7932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7933. }
  7934. {
  7935. auto res = cli.Get(path);
  7936. ASSERT_TRUE(res);
  7937. EXPECT_EQ("bcdefghijk", res->body);
  7938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7939. }
  7940. }
  7941. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7942. Server svr;
  7943. svr.set_default_headers({{"Hello", "World"}});
  7944. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7945. res.set_content("ok", "text/plain");
  7946. });
  7947. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7948. auto se = detail::scope_exit([&] {
  7949. svr.stop();
  7950. listen_thread.join();
  7951. ASSERT_FALSE(svr.is_running());
  7952. });
  7953. svr.wait_until_ready();
  7954. Client cli("localhost", PORT);
  7955. auto res = cli.Get("/");
  7956. ASSERT_TRUE(res);
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. EXPECT_EQ("ok", res->body);
  7959. EXPECT_EQ("World", res->get_header_value("Hello"));
  7960. }
  7961. #ifdef CPPHTTPLIB_SSL_ENABLED
  7962. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7964. ASSERT_TRUE(svr.is_valid());
  7965. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7966. std::this_thread::sleep_for(std::chrono::seconds(2));
  7967. res.set_content("a", "text/plain");
  7968. });
  7969. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7970. res.set_content("b", "text/plain");
  7971. });
  7972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7973. auto se = detail::scope_exit([&] {
  7974. svr.stop();
  7975. listen_thread.join();
  7976. ASSERT_FALSE(svr.is_running());
  7977. });
  7978. svr.wait_until_ready();
  7979. SSLClient cli("localhost", PORT);
  7980. cli.enable_server_certificate_verification(false);
  7981. cli.set_keep_alive(true);
  7982. cli.set_read_timeout(std::chrono::seconds(1));
  7983. auto resa = cli.Get("/a");
  7984. ASSERT_TRUE(!resa);
  7985. EXPECT_EQ(Error::Read, resa.error());
  7986. auto resb = cli.Get("/b");
  7987. ASSERT_TRUE(resb);
  7988. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7989. EXPECT_EQ("b", resb->body);
  7990. }
  7991. #endif
  7992. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7993. protected:
  7994. ServerTestWithAI_PASSIVE()
  7995. : cli_(HOST, PORT)
  7996. #ifdef CPPHTTPLIB_SSL_ENABLED
  7997. ,
  7998. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7999. #endif
  8000. {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. cli_.enable_server_certificate_verification(false);
  8003. #endif
  8004. }
  8005. virtual void SetUp() {
  8006. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8007. res.set_content("Hello World!", "text/plain");
  8008. });
  8009. t_ = thread(
  8010. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8011. svr_.wait_until_ready();
  8012. }
  8013. virtual void TearDown() {
  8014. svr_.stop();
  8015. t_.join();
  8016. }
  8017. #ifdef CPPHTTPLIB_SSL_ENABLED
  8018. SSLClient cli_;
  8019. SSLServer svr_;
  8020. #else
  8021. Client cli_;
  8022. Server svr_;
  8023. #endif
  8024. thread t_;
  8025. };
  8026. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8027. auto res = cli_.Get("/hi");
  8028. ASSERT_TRUE(res);
  8029. EXPECT_EQ(StatusCode::OK_200, res->status);
  8030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8031. EXPECT_EQ("Hello World!", res->body);
  8032. }
  8033. class ServerUpDownTest : public ::testing::Test {
  8034. protected:
  8035. ServerUpDownTest() : cli_(HOST, PORT) {}
  8036. virtual void SetUp() {
  8037. t_ = thread([&]() {
  8038. svr_.bind_to_any_port(HOST);
  8039. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8040. ASSERT_TRUE(svr_.listen_after_bind());
  8041. });
  8042. svr_.wait_until_ready();
  8043. }
  8044. virtual void TearDown() {
  8045. svr_.stop();
  8046. t_.join();
  8047. }
  8048. Client cli_;
  8049. Server svr_;
  8050. thread t_;
  8051. };
  8052. TEST_F(ServerUpDownTest, QuickStartStop) {
  8053. // Should not crash, especially when run with
  8054. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8055. }
  8056. class PayloadMaxLengthTest : public ::testing::Test {
  8057. protected:
  8058. PayloadMaxLengthTest()
  8059. : cli_(HOST, PORT)
  8060. #ifdef CPPHTTPLIB_SSL_ENABLED
  8061. ,
  8062. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8063. #endif
  8064. {
  8065. #ifdef CPPHTTPLIB_SSL_ENABLED
  8066. cli_.enable_server_certificate_verification(false);
  8067. #endif
  8068. }
  8069. virtual void SetUp() {
  8070. svr_.set_payload_max_length(8);
  8071. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8072. res.set_content("test", "text/plain");
  8073. });
  8074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8075. svr_.wait_until_ready();
  8076. }
  8077. virtual void TearDown() {
  8078. svr_.stop();
  8079. t_.join();
  8080. }
  8081. #ifdef CPPHTTPLIB_SSL_ENABLED
  8082. SSLClient cli_;
  8083. SSLServer svr_;
  8084. #else
  8085. Client cli_;
  8086. Server svr_;
  8087. #endif
  8088. thread t_;
  8089. };
  8090. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8091. auto res = cli_.Post("/test", "123456789", "text/plain");
  8092. ASSERT_TRUE(res);
  8093. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8094. res = cli_.Post("/test", "12345678", "text/plain");
  8095. ASSERT_TRUE(res);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8099. // Test chunked encoding with payload exceeding the 8-byte limit
  8100. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8101. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8102. ASSERT_TRUE(res);
  8103. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8104. }
  8105. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8106. // Test chunked encoding with payload within the 8-byte limit
  8107. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8108. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8109. ASSERT_TRUE(res);
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. }
  8112. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8113. // Test using send_request to send chunked data exceeding payload limit
  8114. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8115. "Host: " +
  8116. std::string(HOST) + ":" + std::to_string(PORT) +
  8117. "\r\n"
  8118. "Transfer-Encoding: chunked\r\n"
  8119. "Connection: close\r\n"
  8120. "\r\n"
  8121. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8122. "0123456789\r\n"
  8123. "0\r\n" // End chunk
  8124. "\r\n";
  8125. std::string response;
  8126. bool result = send_request(1, chunked_request, &response);
  8127. if (!result) {
  8128. // If send_request fails, it might be because the server closed the
  8129. // connection due to payload limit enforcement, which is acceptable
  8130. SUCCEED()
  8131. << "Server rejected oversized chunked request (connection closed)";
  8132. } else {
  8133. // If we got a response, check if it's an error response or connection was
  8134. // closed early Short response length indicates connection was closed due to
  8135. // payload limit
  8136. if (response.length() <= 10) {
  8137. SUCCEED() << "Server closed connection for oversized chunked request";
  8138. } else {
  8139. // Check for error status codes
  8140. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8141. response.find("Payload Too Large") != std::string::npos ||
  8142. response.find("400") != std::string::npos);
  8143. }
  8144. }
  8145. }
  8146. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8147. // Test request without Content-Length header exceeding payload limit
  8148. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8149. "Host: " +
  8150. std::string(HOST) + ":" +
  8151. std::to_string(PORT) +
  8152. "\r\n"
  8153. "Connection: close\r\n"
  8154. "\r\n";
  8155. // Add payload exceeding the 8-byte limit
  8156. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8157. request_without_content_length += large_payload;
  8158. std::string response;
  8159. bool result = send_request(1, request_without_content_length, &response);
  8160. if (!result) {
  8161. // If send_request fails, server likely closed connection due to payload
  8162. // limit
  8163. SUCCEED() << "Server rejected oversized request without Content-Length "
  8164. "(connection closed)";
  8165. } else {
  8166. // Check if server responded with error or closed connection early
  8167. if (response.length() <= 10) {
  8168. SUCCEED() << "Server closed connection for oversized request without "
  8169. "Content-Length";
  8170. } else {
  8171. // Check for error status codes
  8172. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8173. response.find("Payload Too Large") != std::string::npos ||
  8174. response.find("400") != std::string::npos);
  8175. }
  8176. }
  8177. }
  8178. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8179. // Test request without Content-Length header within payload limit
  8180. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8181. "Host: " +
  8182. std::string(HOST) + ":" +
  8183. std::to_string(PORT) +
  8184. "\r\n"
  8185. "Connection: close\r\n"
  8186. "\r\n";
  8187. // Add payload within the 8-byte limit
  8188. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8189. request_without_content_length += small_payload;
  8190. std::string response;
  8191. bool result = send_request(1, request_without_content_length, &response);
  8192. // For requests without Content-Length, the server may have different behavior
  8193. // The key is that it should not reject due to payload limit for small
  8194. // payloads
  8195. if (result) {
  8196. // Check for any HTTP response (success or error, but not connection closed)
  8197. if (response.length() > 10) {
  8198. SUCCEED()
  8199. << "Server processed request without Content-Length within limit";
  8200. } else {
  8201. // Short response might indicate connection closed, which is acceptable
  8202. SUCCEED() << "Server closed connection for request without "
  8203. "Content-Length (acceptable behavior)";
  8204. }
  8205. } else {
  8206. // Connection failure might be due to protocol requirements
  8207. SUCCEED() << "Connection issue with request without Content-Length "
  8208. "(environment-specific)";
  8209. }
  8210. }
  8211. class LargePayloadMaxLengthTest : public ::testing::Test {
  8212. protected:
  8213. LargePayloadMaxLengthTest()
  8214. : cli_(HOST, PORT)
  8215. #ifdef CPPHTTPLIB_SSL_ENABLED
  8216. ,
  8217. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8218. #endif
  8219. {
  8220. #ifdef CPPHTTPLIB_SSL_ENABLED
  8221. cli_.enable_server_certificate_verification(false);
  8222. #endif
  8223. }
  8224. virtual void SetUp() {
  8225. // Set 10MB payload limit
  8226. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8227. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8228. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8229. res.set_content("Large payload test", "text/plain");
  8230. });
  8231. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8232. svr_.wait_until_ready();
  8233. }
  8234. virtual void TearDown() {
  8235. svr_.stop();
  8236. t_.join();
  8237. }
  8238. #ifdef CPPHTTPLIB_SSL_ENABLED
  8239. SSLClient cli_;
  8240. SSLServer svr_;
  8241. #else
  8242. Client cli_;
  8243. Server svr_;
  8244. #endif
  8245. thread t_;
  8246. };
  8247. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8248. // Test chunked encoding with payload within 10MB limit
  8249. std::string medium_payload(5 * 1024 * 1024,
  8250. 'A'); // 5MB payload, within 10MB limit
  8251. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8252. ASSERT_TRUE(res);
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. }
  8255. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8256. // Test chunked encoding with payload exceeding 10MB limit
  8257. std::string large_payload(12 * 1024 * 1024,
  8258. 'B'); // 12MB payload, exceeds 10MB limit
  8259. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8260. // Server may either return 413 or close the connection
  8261. if (res) {
  8262. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8263. } else {
  8264. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8265. }
  8266. }
  8267. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8268. // Test request without Content-Length header within 10MB limit
  8269. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8270. "Host: " +
  8271. std::string(HOST) + ":" +
  8272. std::to_string(PORT) +
  8273. "\r\n"
  8274. "Connection: close\r\n"
  8275. "\r\n";
  8276. // Add 1MB payload (within 10MB limit)
  8277. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8278. request_without_content_length += medium_payload;
  8279. std::string response;
  8280. bool result = send_request(5, request_without_content_length, &response);
  8281. if (result) {
  8282. // Should get a proper HTTP response for payloads within limit
  8283. if (response.length() > 10) {
  8284. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8285. "10MB limit";
  8286. } else {
  8287. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8288. "Content-Length)";
  8289. }
  8290. } else {
  8291. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8292. }
  8293. }
  8294. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8295. // Test request without Content-Length header exceeding 10MB limit
  8296. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8297. "Host: " +
  8298. std::string(HOST) + ":" +
  8299. std::to_string(PORT) +
  8300. "\r\n"
  8301. "Connection: close\r\n"
  8302. "\r\n";
  8303. // Add 12MB payload (exceeds 10MB limit)
  8304. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8305. request_without_content_length += large_payload;
  8306. std::string response;
  8307. bool result = send_request(10, request_without_content_length, &response);
  8308. if (!result) {
  8309. // Server should close connection due to payload limit
  8310. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8311. "(connection closed)";
  8312. } else {
  8313. // Check for error response
  8314. if (response.length() <= 10) {
  8315. SUCCEED()
  8316. << "Server closed connection for 12MB request exceeding 10MB limit";
  8317. } else {
  8318. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8319. response.find("Payload Too Large") != std::string::npos ||
  8320. response.find("400") != std::string::npos);
  8321. }
  8322. }
  8323. }
  8324. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8325. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8326. // path.
  8327. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8328. Server svr;
  8329. const size_t LIMIT = 64 * 1024; // 64KB
  8330. svr.set_payload_max_length(LIMIT);
  8331. size_t total = 0;
  8332. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8333. const ContentReader &content_reader) {
  8334. content_reader([&](const char * /*data*/, size_t len) {
  8335. total += len;
  8336. return true;
  8337. });
  8338. res.status = 200;
  8339. res.set_content("stream_ok", "text/plain");
  8340. });
  8341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8342. auto se = detail::scope_exit([&] {
  8343. svr.stop();
  8344. thread.join();
  8345. ASSERT_FALSE(svr.is_running());
  8346. });
  8347. svr.wait_until_ready();
  8348. // Prepare 256KB raw data and gzip-compress it
  8349. std::string raw(256 * 1024, 'A');
  8350. std::string gz;
  8351. {
  8352. z_stream zs{};
  8353. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8354. Z_DEFAULT_STRATEGY);
  8355. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8356. zs.avail_in = static_cast<uInt>(raw.size());
  8357. char outbuf[4096];
  8358. int ret;
  8359. do {
  8360. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8361. zs.avail_out = sizeof(outbuf);
  8362. ret = deflate(&zs, Z_FINISH);
  8363. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8364. } while (ret != Z_STREAM_END);
  8365. deflateEnd(&zs);
  8366. }
  8367. Client cli(HOST, PORT);
  8368. cli.set_connection_timeout(std::chrono::seconds(5));
  8369. Headers headers = {{"Content-Encoding", "gzip"}};
  8370. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8371. "application/octet-stream");
  8372. ASSERT_TRUE(res);
  8373. // Server must reject oversized decompressed payloads with 413.
  8374. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8375. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8376. EXPECT_LE(total, LIMIT);
  8377. }
  8378. #endif
  8379. // Regression test for DoS vulnerability: a malicious server sending a response
  8380. // without Content-Length header must not cause unbounded memory consumption on
  8381. // the client side. The client should stop reading after a reasonable limit,
  8382. // similar to the server-side set_payload_max_length protection.
  8383. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8384. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8385. #ifndef _WIN32
  8386. signal(SIGPIPE, SIG_IGN);
  8387. #endif
  8388. auto server_thread = std::thread([] {
  8389. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8390. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8391. default_socket_options(srv);
  8392. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8393. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8394. sockaddr_in addr{};
  8395. addr.sin_family = AF_INET;
  8396. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8398. int opt = 1;
  8399. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8400. #ifdef _WIN32
  8401. reinterpret_cast<const char *>(&opt),
  8402. #else
  8403. &opt,
  8404. #endif
  8405. sizeof(opt));
  8406. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8407. ::listen(srv, 1);
  8408. sockaddr_in cli_addr{};
  8409. socklen_t cli_len = sizeof(cli_addr);
  8410. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8411. if (cli != INVALID_SOCKET) {
  8412. char buf[4096];
  8413. ::recv(cli, buf, sizeof(buf), 0);
  8414. // Malicious response: no Content-Length, no chunked encoding
  8415. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8416. "Connection: close\r\n"
  8417. "\r\n";
  8418. ::send(cli,
  8419. #ifdef _WIN32
  8420. static_cast<const char *>(response_header.c_str()),
  8421. static_cast<int>(response_header.size()),
  8422. #else
  8423. response_header.c_str(), response_header.size(),
  8424. #endif
  8425. 0);
  8426. // Send 10MB of data
  8427. std::string chunk(64 * 1024, 'A');
  8428. size_t total_sent = 0;
  8429. while (total_sent < MALICIOUS_DATA_SIZE) {
  8430. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8431. auto sent = ::send(cli,
  8432. #ifdef _WIN32
  8433. static_cast<const char *>(chunk.c_str()),
  8434. static_cast<int>(to_send),
  8435. #else
  8436. chunk.c_str(), to_send,
  8437. #endif
  8438. 0);
  8439. if (sent <= 0) break;
  8440. total_sent += static_cast<size_t>(sent);
  8441. }
  8442. detail::close_socket(cli);
  8443. }
  8444. detail::close_socket(srv);
  8445. });
  8446. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8447. size_t total_read = 0;
  8448. {
  8449. Client cli("127.0.0.1", PORT + 2);
  8450. cli.set_read_timeout(5, 0);
  8451. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8452. auto stream = cli.open_stream("GET", "/malicious");
  8453. ASSERT_TRUE(stream.is_valid());
  8454. char buffer[64 * 1024];
  8455. ssize_t n;
  8456. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8457. total_read += static_cast<size_t>(n);
  8458. }
  8459. } // StreamHandle and Client destroyed here, closing the socket
  8460. server_thread.join();
  8461. // With set_payload_max_length, the client must stop reading before consuming
  8462. // all 10MB. The read loop should be cut off at or near the configured limit.
  8463. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8464. << "Client read " << total_read << " bytes, exceeding the configured "
  8465. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8466. }
  8467. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8468. // the entire response body without truncation.
  8469. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8470. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8471. #ifndef _WIN32
  8472. signal(SIGPIPE, SIG_IGN);
  8473. #endif
  8474. auto server_thread = std::thread([] {
  8475. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8476. default_socket_options(srv);
  8477. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8478. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8479. sockaddr_in addr{};
  8480. addr.sin_family = AF_INET;
  8481. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8483. int opt = 1;
  8484. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8485. #ifdef _WIN32
  8486. reinterpret_cast<const char *>(&opt),
  8487. #else
  8488. &opt,
  8489. #endif
  8490. sizeof(opt));
  8491. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8492. ::listen(srv, 1);
  8493. sockaddr_in cli_addr{};
  8494. socklen_t cli_len = sizeof(cli_addr);
  8495. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8496. if (cli != INVALID_SOCKET) {
  8497. char buf[4096];
  8498. ::recv(cli, buf, sizeof(buf), 0);
  8499. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8500. "Connection: close\r\n"
  8501. "\r\n";
  8502. ::send(cli,
  8503. #ifdef _WIN32
  8504. static_cast<const char *>(response_header.c_str()),
  8505. static_cast<int>(response_header.size()),
  8506. #else
  8507. response_header.c_str(), response_header.size(),
  8508. #endif
  8509. 0);
  8510. std::string chunk(64 * 1024, 'A');
  8511. size_t total_sent = 0;
  8512. while (total_sent < DATA_SIZE) {
  8513. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8514. auto sent = ::send(cli,
  8515. #ifdef _WIN32
  8516. static_cast<const char *>(chunk.c_str()),
  8517. static_cast<int>(to_send),
  8518. #else
  8519. chunk.c_str(), to_send,
  8520. #endif
  8521. 0);
  8522. if (sent <= 0) break;
  8523. total_sent += static_cast<size_t>(sent);
  8524. }
  8525. #ifdef _WIN32
  8526. ::shutdown(cli, SD_SEND);
  8527. #else
  8528. ::shutdown(cli, SHUT_WR);
  8529. #endif
  8530. // Drain until the client closes its end, ensuring all data is delivered
  8531. char drain[1024];
  8532. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8533. detail::close_socket(cli);
  8534. }
  8535. detail::close_socket(srv);
  8536. });
  8537. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8538. size_t total_read = 0;
  8539. {
  8540. Client cli("127.0.0.1", PORT + 2);
  8541. cli.set_read_timeout(5, 0);
  8542. cli.set_payload_max_length(0); // 0 means no limit
  8543. auto stream = cli.open_stream("GET", "/data");
  8544. ASSERT_TRUE(stream.is_valid());
  8545. char buffer[64 * 1024];
  8546. ssize_t n;
  8547. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8548. total_read += static_cast<size_t>(n);
  8549. }
  8550. }
  8551. server_thread.join();
  8552. EXPECT_EQ(total_read, DATA_SIZE)
  8553. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8554. << " bytes without truncation, but only read " << total_read << " bytes.";
  8555. }
  8556. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8557. // enormous Content-Length must not cause the client to pre-allocate a huge
  8558. // response body buffer. The reservation is capped at payload_max_length_, and
  8559. // the read itself fails when the body exceeds the limit.
  8560. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8561. #ifndef _WIN32
  8562. signal(SIGPIPE, SIG_IGN);
  8563. #endif
  8564. auto server_thread = std::thread([] {
  8565. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8566. default_socket_options(srv);
  8567. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8568. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8569. sockaddr_in addr{};
  8570. addr.sin_family = AF_INET;
  8571. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8572. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8573. int opt = 1;
  8574. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8575. #ifdef _WIN32
  8576. reinterpret_cast<const char *>(&opt),
  8577. #else
  8578. &opt,
  8579. #endif
  8580. sizeof(opt));
  8581. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8582. ::listen(srv, 1);
  8583. sockaddr_in cli_addr{};
  8584. socklen_t cli_len = sizeof(cli_addr);
  8585. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8586. if (cli != INVALID_SOCKET) {
  8587. char buf[4096];
  8588. ::recv(cli, buf, sizeof(buf), 0);
  8589. // Malicious response: claim a 20GB body but send only a tiny payload.
  8590. std::string response = "HTTP/1.1 200 OK\r\n"
  8591. "Content-Length: 20000000000\r\n"
  8592. "\r\n"
  8593. "abc";
  8594. ::send(cli,
  8595. #ifdef _WIN32
  8596. static_cast<const char *>(response.c_str()),
  8597. static_cast<int>(response.size()),
  8598. #else
  8599. response.c_str(), response.size(),
  8600. #endif
  8601. 0);
  8602. detail::close_socket(cli);
  8603. }
  8604. detail::close_socket(srv);
  8605. });
  8606. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8607. {
  8608. Client cli("127.0.0.1", PORT + 2);
  8609. cli.set_read_timeout(5, 0);
  8610. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8611. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8612. // (server claims more bytes than payload_max_length permits), but it must
  8613. // not exhaust memory before getting there.
  8614. auto res = cli.Get("/malicious");
  8615. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8616. }
  8617. server_thread.join();
  8618. }
  8619. // Verify that content_receiver bypasses the default payload_max_length,
  8620. // allowing streaming downloads larger than 100MB without requiring an explicit
  8621. // set_payload_max_length call.
  8622. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8623. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8624. #ifndef _WIN32
  8625. signal(SIGPIPE, SIG_IGN);
  8626. #endif
  8627. auto server_thread = std::thread([] {
  8628. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8629. default_socket_options(srv);
  8630. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8631. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8632. sockaddr_in addr{};
  8633. addr.sin_family = AF_INET;
  8634. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8635. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8636. int opt = 1;
  8637. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8638. #ifdef _WIN32
  8639. reinterpret_cast<const char *>(&opt),
  8640. #else
  8641. &opt,
  8642. #endif
  8643. sizeof(opt));
  8644. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8645. ::listen(srv, 1);
  8646. sockaddr_in cli_addr{};
  8647. socklen_t cli_len = sizeof(cli_addr);
  8648. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8649. if (cli != INVALID_SOCKET) {
  8650. char buf[4096];
  8651. ::recv(cli, buf, sizeof(buf), 0);
  8652. // Response with Content-Length larger than default 100MB limit
  8653. auto content_length = std::to_string(DATA_SIZE);
  8654. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8655. "Content-Length: " +
  8656. content_length +
  8657. "\r\n"
  8658. "Connection: close\r\n"
  8659. "\r\n";
  8660. ::send(cli,
  8661. #ifdef _WIN32
  8662. static_cast<const char *>(response_header.c_str()),
  8663. static_cast<int>(response_header.size()),
  8664. #else
  8665. response_header.c_str(), response_header.size(),
  8666. #endif
  8667. 0);
  8668. std::string chunk(64 * 1024, 'A');
  8669. size_t total_sent = 0;
  8670. while (total_sent < DATA_SIZE) {
  8671. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8672. auto sent = ::send(cli,
  8673. #ifdef _WIN32
  8674. static_cast<const char *>(chunk.c_str()),
  8675. static_cast<int>(to_send),
  8676. #else
  8677. chunk.c_str(), to_send,
  8678. #endif
  8679. 0);
  8680. if (sent <= 0) break;
  8681. total_sent += static_cast<size_t>(sent);
  8682. }
  8683. detail::close_socket(cli);
  8684. }
  8685. detail::close_socket(srv);
  8686. });
  8687. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8688. size_t total_received = 0;
  8689. {
  8690. Client cli("127.0.0.1", PORT + 2);
  8691. cli.set_read_timeout(10, 0);
  8692. // Do NOT call set_payload_max_length — use the default 100MB limit
  8693. auto res =
  8694. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8695. total_received += data_length;
  8696. return true;
  8697. });
  8698. ASSERT_TRUE(res);
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. }
  8701. server_thread.join();
  8702. EXPECT_EQ(total_received, DATA_SIZE)
  8703. << "With content_receiver, the client should read all " << DATA_SIZE
  8704. << " bytes despite the default 100MB payload_max_length, but only read "
  8705. << total_received << " bytes.";
  8706. }
  8707. // Verify that an explicit set_payload_max_length smaller than the response is
  8708. // enforced even when a content_receiver is used.
  8709. TEST(ClientVulnerabilityTest,
  8710. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8711. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8712. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8713. #ifndef _WIN32
  8714. signal(SIGPIPE, SIG_IGN);
  8715. #endif
  8716. auto server_thread = std::thread([] {
  8717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8718. default_socket_options(srv);
  8719. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8720. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8721. sockaddr_in addr{};
  8722. addr.sin_family = AF_INET;
  8723. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8725. int opt = 1;
  8726. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8727. #ifdef _WIN32
  8728. reinterpret_cast<const char *>(&opt),
  8729. #else
  8730. &opt,
  8731. #endif
  8732. sizeof(opt));
  8733. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8734. ::listen(srv, 1);
  8735. sockaddr_in cli_addr{};
  8736. socklen_t cli_len = sizeof(cli_addr);
  8737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8738. if (cli != INVALID_SOCKET) {
  8739. char buf[4096];
  8740. ::recv(cli, buf, sizeof(buf), 0);
  8741. auto content_length = std::to_string(DATA_SIZE);
  8742. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8743. "Content-Length: " +
  8744. content_length +
  8745. "\r\n"
  8746. "Connection: close\r\n"
  8747. "\r\n";
  8748. ::send(cli,
  8749. #ifdef _WIN32
  8750. static_cast<const char *>(response_header.c_str()),
  8751. static_cast<int>(response_header.size()),
  8752. #else
  8753. response_header.c_str(), response_header.size(),
  8754. #endif
  8755. 0);
  8756. std::string chunk(64 * 1024, 'A');
  8757. size_t total_sent = 0;
  8758. while (total_sent < DATA_SIZE) {
  8759. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8760. auto sent = ::send(cli,
  8761. #ifdef _WIN32
  8762. static_cast<const char *>(chunk.c_str()),
  8763. static_cast<int>(to_send),
  8764. #else
  8765. chunk.c_str(), to_send,
  8766. #endif
  8767. 0);
  8768. if (sent <= 0) break;
  8769. total_sent += static_cast<size_t>(sent);
  8770. }
  8771. detail::close_socket(cli);
  8772. }
  8773. detail::close_socket(srv);
  8774. });
  8775. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8776. size_t total_received = 0;
  8777. {
  8778. Client cli("127.0.0.1", PORT + 2);
  8779. cli.set_read_timeout(10, 0);
  8780. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8781. auto res =
  8782. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8783. total_received += data_length;
  8784. return true;
  8785. });
  8786. // Should fail because 200MB exceeds the explicit 150MB limit
  8787. EXPECT_FALSE(res);
  8788. }
  8789. server_thread.join();
  8790. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8791. << "Client with content_receiver should respect the explicit "
  8792. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8793. << total_received << " bytes.";
  8794. }
  8795. // Verify that an explicit set_payload_max_length larger than the response
  8796. // allows the content_receiver to read all data successfully.
  8797. TEST(ClientVulnerabilityTest,
  8798. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8799. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8800. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8801. #ifndef _WIN32
  8802. signal(SIGPIPE, SIG_IGN);
  8803. #endif
  8804. auto server_thread = std::thread([] {
  8805. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8806. default_socket_options(srv);
  8807. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8808. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8809. sockaddr_in addr{};
  8810. addr.sin_family = AF_INET;
  8811. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8812. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8813. int opt = 1;
  8814. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8815. #ifdef _WIN32
  8816. reinterpret_cast<const char *>(&opt),
  8817. #else
  8818. &opt,
  8819. #endif
  8820. sizeof(opt));
  8821. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8822. ::listen(srv, 1);
  8823. sockaddr_in cli_addr{};
  8824. socklen_t cli_len = sizeof(cli_addr);
  8825. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8826. if (cli != INVALID_SOCKET) {
  8827. char buf[4096];
  8828. ::recv(cli, buf, sizeof(buf), 0);
  8829. auto content_length = std::to_string(DATA_SIZE);
  8830. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8831. "Content-Length: " +
  8832. content_length +
  8833. "\r\n"
  8834. "Connection: close\r\n"
  8835. "\r\n";
  8836. ::send(cli,
  8837. #ifdef _WIN32
  8838. static_cast<const char *>(response_header.c_str()),
  8839. static_cast<int>(response_header.size()),
  8840. #else
  8841. response_header.c_str(), response_header.size(),
  8842. #endif
  8843. 0);
  8844. std::string chunk(64 * 1024, 'A');
  8845. size_t total_sent = 0;
  8846. while (total_sent < DATA_SIZE) {
  8847. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8848. auto sent = ::send(cli,
  8849. #ifdef _WIN32
  8850. static_cast<const char *>(chunk.c_str()),
  8851. static_cast<int>(to_send),
  8852. #else
  8853. chunk.c_str(), to_send,
  8854. #endif
  8855. 0);
  8856. if (sent <= 0) break;
  8857. total_sent += static_cast<size_t>(sent);
  8858. }
  8859. #ifdef _WIN32
  8860. ::shutdown(cli, SD_SEND);
  8861. #else
  8862. ::shutdown(cli, SHUT_WR);
  8863. #endif
  8864. char drain[1024];
  8865. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8866. detail::close_socket(cli);
  8867. }
  8868. detail::close_socket(srv);
  8869. });
  8870. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8871. size_t total_received = 0;
  8872. {
  8873. Client cli("127.0.0.1", PORT + 2);
  8874. cli.set_read_timeout(10, 0);
  8875. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8876. auto res =
  8877. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8878. total_received += data_length;
  8879. return true;
  8880. });
  8881. ASSERT_TRUE(res);
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. }
  8884. server_thread.join();
  8885. EXPECT_EQ(total_received, DATA_SIZE)
  8886. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8887. << " bytes (larger than " << DATA_SIZE
  8888. << " bytes response), content_receiver should read all data, but only "
  8889. "read "
  8890. << total_received << " bytes.";
  8891. }
  8892. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8893. // Regression test for "zip bomb" attack on the client side: a malicious server
  8894. // sends a small gzip-compressed response that decompresses to a huge payload.
  8895. // The client must enforce payload_max_length on the decompressed size.
  8896. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8897. constexpr size_t DECOMPRESSED_SIZE =
  8898. 10 * 1024 * 1024; // 10MB after decompression
  8899. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8900. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8901. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8902. std::string compressed;
  8903. {
  8904. httplib::detail::gzip_compressor compressor;
  8905. bool ok =
  8906. compressor.compress(uncompressed.data(), uncompressed.size(),
  8907. /*last=*/true, [&](const char *buf, size_t len) {
  8908. compressed.append(buf, len);
  8909. return true;
  8910. });
  8911. ASSERT_TRUE(ok);
  8912. }
  8913. // Sanity: compressed data should be much smaller than the decompressed size
  8914. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8915. #ifndef _WIN32
  8916. signal(SIGPIPE, SIG_IGN);
  8917. #endif
  8918. // Set up the listening socket in the main thread so the server is guaranteed
  8919. // to be ready before the client connects (eliminates race condition).
  8920. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8921. default_socket_options(srv);
  8922. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8923. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8924. sockaddr_in addr{};
  8925. addr.sin_family = AF_INET;
  8926. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8927. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8928. int opt = 1;
  8929. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8930. #ifdef _WIN32
  8931. reinterpret_cast<const char *>(&opt),
  8932. #else
  8933. &opt,
  8934. #endif
  8935. sizeof(opt));
  8936. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8937. ASSERT_EQ(0, ::listen(srv, 1));
  8938. auto server_thread = std::thread([&compressed, srv] {
  8939. sockaddr_in cli_addr{};
  8940. socklen_t cli_len = sizeof(cli_addr);
  8941. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8942. if (cli != INVALID_SOCKET) {
  8943. // Read the full HTTP request (until \r\n\r\n)
  8944. char buf[4096];
  8945. size_t total = 0;
  8946. while (total < sizeof(buf)) {
  8947. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8948. if (n <= 0) break;
  8949. total += static_cast<size_t>(n);
  8950. // Check for end of headers
  8951. if (total >= 4) {
  8952. std::string req(buf, total);
  8953. if (req.find("\r\n\r\n") != std::string::npos) break;
  8954. }
  8955. }
  8956. // Malicious response: gzip-compressed body, no Content-Length
  8957. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8958. "Content-Encoding: gzip\r\n"
  8959. "Connection: close\r\n"
  8960. "\r\n";
  8961. ::send(cli,
  8962. #ifdef _WIN32
  8963. static_cast<const char *>(response_header.c_str()),
  8964. static_cast<int>(response_header.size()),
  8965. #else
  8966. response_header.c_str(), response_header.size(),
  8967. #endif
  8968. 0);
  8969. // Send the compressed payload (small on the wire, huge when decompressed)
  8970. size_t total_sent = 0;
  8971. while (total_sent < compressed.size()) {
  8972. auto to_send = std::min(compressed.size() - total_sent,
  8973. static_cast<size_t>(64 * 1024));
  8974. auto sent =
  8975. ::send(cli,
  8976. #ifdef _WIN32
  8977. static_cast<const char *>(compressed.c_str() + total_sent),
  8978. static_cast<int>(to_send),
  8979. #else
  8980. compressed.c_str() + total_sent, to_send,
  8981. #endif
  8982. 0);
  8983. if (sent <= 0) break;
  8984. total_sent += static_cast<size_t>(sent);
  8985. }
  8986. detail::close_socket(cli);
  8987. }
  8988. });
  8989. auto se = detail::scope_exit([&] {
  8990. detail::close_socket(srv);
  8991. server_thread.join();
  8992. });
  8993. size_t total_decompressed = 0;
  8994. {
  8995. Client cli("127.0.0.1", PORT + 3);
  8996. cli.set_read_timeout(5, 0);
  8997. cli.set_decompress(true);
  8998. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8999. auto stream = cli.open_stream("GET", "/zipbomb");
  9000. ASSERT_TRUE(stream.is_valid());
  9001. char buffer[64 * 1024];
  9002. ssize_t n;
  9003. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9004. total_decompressed += static_cast<size_t>(n);
  9005. }
  9006. }
  9007. // The decompressed size must be capped by payload_max_length. Without
  9008. // protection, the client would decompress the full 10MB from a tiny
  9009. // compressed payload, enabling a zip bomb DoS attack.
  9010. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9011. << "Client decompressed " << total_decompressed
  9012. << " bytes from a gzip response. The decompressed size should be "
  9013. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9014. }
  9015. #endif
  9016. TEST(HostAndPortPropertiesTest, NoSSL) {
  9017. httplib::Client cli("www.google.com", 1234);
  9018. ASSERT_EQ("www.google.com", cli.host());
  9019. ASSERT_EQ(1234, cli.port());
  9020. }
  9021. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9022. httplib::Client cli("www.google.com:1234");
  9023. ASSERT_EQ("www.google.com", cli.host());
  9024. ASSERT_EQ(1234, cli.port());
  9025. }
  9026. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9027. // Port number that overflows int — should not crash, client becomes invalid
  9028. httplib::Client cli("http://www.google.com:99999999999999999999");
  9029. ASSERT_FALSE(cli.is_valid());
  9030. }
  9031. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9032. // Port 99999 exceeds valid range (1-65535) — should not crash
  9033. httplib::Client cli("http://www.google.com:99999");
  9034. ASSERT_FALSE(cli.is_valid());
  9035. }
  9036. #ifdef CPPHTTPLIB_SSL_ENABLED
  9037. TEST(HostAndPortPropertiesTest, SSL) {
  9038. httplib::SSLClient cli("www.google.com");
  9039. ASSERT_EQ("www.google.com", cli.host());
  9040. ASSERT_EQ(443, cli.port());
  9041. }
  9042. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9043. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9044. std::string cert;
  9045. read_file(CA_CERT_FILE, cert);
  9046. httplib::SSLClient httplib_client("www.google.com");
  9047. // Load CA store first time
  9048. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9049. // Load CA store second time (update)
  9050. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9051. // Verify client is still valid and can make connections
  9052. httplib_client.enable_server_certificate_verification(true);
  9053. auto res = httplib_client.Get("/");
  9054. ASSERT_TRUE(res);
  9055. // Google may return 200 or 301 depending on various factors
  9056. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9057. res->status == StatusCode::MovedPermanently_301);
  9058. }
  9059. TEST(SSLClientTest, ServerNameIndication_Online) {
  9060. auto host = "httpbingo.org";
  9061. auto path = std::string{"/get"};
  9062. SSLClient cli(host, 443);
  9063. auto res = cli.Get(path);
  9064. ASSERT_TRUE(res);
  9065. ASSERT_EQ(StatusCode::OK_200, res->status);
  9066. }
  9067. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9068. // Use a site that will cause SSL verification failure due to self-signed cert
  9069. SSLClient cli("self-signed.badssl.com", 443);
  9070. cli.enable_server_certificate_verification(true);
  9071. auto res = cli.Get("/");
  9072. ASSERT_TRUE(!res);
  9073. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9074. // Verify backend error is captured for SSLServerVerification
  9075. // This occurs when certificate verification fails
  9076. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9077. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9078. EXPECT_NE(0UL, res.ssl_backend_error());
  9079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9080. // For OpenSSL, ssl_error is 0 for verification errors
  9081. EXPECT_EQ(0, res.ssl_error());
  9082. #if !defined(_WIN32) || \
  9083. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9084. // On non-Windows or when Windows Schannel is disabled, the error comes
  9085. // from OpenSSL's verification
  9086. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9087. res.ssl_backend_error());
  9088. #endif
  9089. #endif
  9090. }
  9091. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9092. // Use a site where hostname doesn't match the certificate
  9093. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9094. SSLClient cli("wrong.host.badssl.com", 443);
  9095. cli.enable_server_certificate_verification(true);
  9096. cli.enable_server_hostname_verification(true);
  9097. auto res = cli.Get("/");
  9098. ASSERT_TRUE(!res);
  9099. // The error type depends on when hostname verification occurs:
  9100. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9101. // - Mbed TLS: SSLServerVerification (during handshake)
  9102. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9103. res.error() == Error::SSLServerVerification);
  9104. // Verify backend error is captured for hostname verification failure
  9105. EXPECT_NE(0UL, res.ssl_backend_error());
  9106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9107. // For OpenSSL, ssl_error is 0 for verification errors
  9108. EXPECT_EQ(0, res.ssl_error());
  9109. #if !defined(_WIN32) || \
  9110. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9111. // On non-Windows or when Windows Schannel is disabled, the error comes
  9112. // from OpenSSL's hostname verification
  9113. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9114. res.ssl_backend_error());
  9115. #endif
  9116. #endif
  9117. }
  9118. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9119. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9120. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9121. SSLClient cli("www.google.com", 443);
  9122. cli.enable_server_certificate_verification(true);
  9123. auto res = cli.Get("/");
  9124. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9125. }
  9126. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9127. SSLClient cli("www.google.com", 443);
  9128. cli.enable_server_certificate_verification(true);
  9129. cli.enable_windows_certificate_verification(false);
  9130. auto res = cli.Get("/");
  9131. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9132. }
  9133. #endif
  9134. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9135. Client cli("https://google.com");
  9136. auto res = cli.Get("/");
  9137. ASSERT_TRUE(res);
  9138. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9139. }
  9140. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9141. SSLClient cli("google.com");
  9142. cli.set_ca_cert_path(CA_CERT_FILE);
  9143. auto res = cli.Get("/");
  9144. ASSERT_TRUE(res);
  9145. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9146. }
  9147. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9148. SSLClient cli("google.com");
  9149. cli.enable_server_certificate_verification(true);
  9150. cli.set_ca_cert_path("hello");
  9151. auto res = cli.Get("/");
  9152. ASSERT_TRUE(!res);
  9153. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9154. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9155. // should be set
  9156. EXPECT_EQ(0, res.ssl_error());
  9157. // Verify backend error is captured for SSLLoadingCerts
  9158. // This error occurs when loading CA certificates fails
  9159. EXPECT_NE(0UL, res.ssl_backend_error());
  9160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9161. // OpenSSL specific error codes:
  9162. // > openssl errstr 0x80000002
  9163. // error:80000002:system library::No such file or directory
  9164. // > openssl errstr 0xA000126
  9165. // error:0A000126:SSL routines::unexpected eof while reading
  9166. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9167. res.ssl_backend_error() == 0xA000126);
  9168. #endif
  9169. }
  9170. TEST(SSLClientTest, ServerCertificateVerification4) {
  9171. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9172. ASSERT_TRUE(svr.is_valid());
  9173. svr.Get("/test", [&](const Request &, Response &res) {
  9174. res.set_content("test", "text/plain");
  9175. svr.stop();
  9176. ASSERT_TRUE(true);
  9177. });
  9178. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9179. auto se = detail::scope_exit([&] {
  9180. t.join();
  9181. ASSERT_FALSE(svr.is_running());
  9182. });
  9183. svr.wait_until_ready();
  9184. SSLClient cli("127.0.0.1", PORT);
  9185. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9186. cli.enable_server_certificate_verification(true);
  9187. cli.set_connection_timeout(30);
  9188. auto res = cli.Get("/test");
  9189. ASSERT_TRUE(res);
  9190. ASSERT_EQ(StatusCode::OK_200, res->status);
  9191. }
  9192. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9193. std::string cert;
  9194. read_file(CA_CERT_FILE, cert);
  9195. SSLClient cli("google.com");
  9196. cli.load_ca_cert_store(cert.data(), cert.size());
  9197. const auto res = cli.Get("/");
  9198. ASSERT_TRUE(res);
  9199. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9200. }
  9201. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9202. // clang-format off
  9203. static constexpr char cert[] =
  9204. "GlobalSign Root CA\n"
  9205. "==================\n"
  9206. "-----BEGIN CERTIFICATE-----\n"
  9207. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9208. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9209. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9210. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9211. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9212. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9213. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9214. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9215. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9216. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9217. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9218. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9219. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9220. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9221. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9222. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9223. "-----END CERTIFICATE-----\n";
  9224. // clang-format on
  9225. SSLClient cli("google.com");
  9226. cli.load_ca_cert_store(cert, sizeof(cert));
  9227. const auto res = cli.Get("/");
  9228. ASSERT_TRUE(res);
  9229. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9230. }
  9231. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9232. SSLClient cli("www.youtube.com");
  9233. cli.set_ca_cert_path(CA_CERT_FILE);
  9234. cli.enable_server_certificate_verification(true);
  9235. cli.set_follow_location(true);
  9236. auto res = cli.Get("/");
  9237. ASSERT_TRUE(res);
  9238. ASSERT_EQ(StatusCode::OK_200, res->status);
  9239. }
  9240. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9241. SSLClient cli("wWw.YouTube.Com");
  9242. cli.set_ca_cert_path(CA_CERT_FILE);
  9243. cli.enable_server_certificate_verification(true);
  9244. cli.enable_server_hostname_verification(true);
  9245. cli.set_follow_location(true);
  9246. auto res = cli.Get("/");
  9247. ASSERT_TRUE(res);
  9248. ASSERT_EQ(StatusCode::OK_200, res->status);
  9249. }
  9250. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9251. SSLClient cli("gOoGlE.COm");
  9252. cli.enable_server_certificate_verification(true);
  9253. cli.enable_server_hostname_verification(true);
  9254. cli.set_follow_location(true);
  9255. auto res = cli.Get("/");
  9256. ASSERT_TRUE(res);
  9257. ASSERT_EQ(StatusCode::OK_200, res->status);
  9258. }
  9259. TEST(SSLClientTest, Issue2004_Online) {
  9260. Client client("https://google.com");
  9261. client.set_follow_location(true);
  9262. auto res = client.Get("/");
  9263. ASSERT_TRUE(res);
  9264. ASSERT_EQ(StatusCode::OK_200, res->status);
  9265. auto body = res->body;
  9266. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9267. }
  9268. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9269. // Create SSLClient with invalid cert/key to make is_valid() return false
  9270. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9271. "nonexistent_key.pem");
  9272. // is_valid() should be false due to cert loading failure
  9273. ASSERT_FALSE(cli.is_valid());
  9274. auto res = cli.Get("/");
  9275. ASSERT_FALSE(res);
  9276. EXPECT_EQ(Error::SSLConnection, res.error());
  9277. }
  9278. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9279. // Test for Issue #2251: SSL error not properly reported when client cert
  9280. // and key paths are swapped or mismatched
  9281. // This simulates the scenario where user accidentally swaps the cert and key
  9282. // files
  9283. // Using client cert file as private key and vice versa (completely wrong)
  9284. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9285. // Should fail validation due to cert/key mismatch
  9286. ASSERT_FALSE(cli.is_valid());
  9287. // Attempt to make a request should fail with proper error
  9288. auto res = cli.Get("/");
  9289. ASSERT_FALSE(res);
  9290. EXPECT_EQ(Error::SSLConnection, res.error());
  9291. // SSL error should be recorded in the Result object (this is the key fix for
  9292. // Issue #2251)
  9293. auto backend_error = res.ssl_backend_error();
  9294. EXPECT_NE(0u, backend_error);
  9295. }
  9296. // Tests cert/key mismatch detection at the TLS context level
  9297. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9298. // Test that using mismatched cert/key causes connection failure.
  9299. // We verify this at the SSLClient level rather than through internal
  9300. // TLS API functions.
  9301. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9302. cli.enable_server_certificate_verification(false);
  9303. cli.set_connection_timeout(2);
  9304. // The mismatch should cause a connection or handshake error
  9305. auto res = cli.Get("/test");
  9306. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9307. // Either way, the request should fail
  9308. EXPECT_FALSE(res);
  9309. }
  9310. #endif
  9311. #if 0
  9312. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9313. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9314. ASSERT_TRUE(cli != nullptr);
  9315. cli->set_address_family(AF_INET6);
  9316. cli->set_interface("en0");
  9317. auto res = cli->Get("/get");
  9318. ASSERT_TRUE(res);
  9319. ASSERT_EQ(StatusCode::OK_200, res->status);
  9320. }
  9321. #endif
  9322. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9323. #ifdef CPPHTTPLIB_SSL_ENABLED
  9324. void ClientCertPresent(
  9325. const std::string &client_cert_file,
  9326. const std::string &client_private_key_file,
  9327. const std::string &client_encrypted_private_key_pass = std::string()) {
  9328. using namespace httplib::tls;
  9329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9330. CLIENT_CA_CERT_DIR);
  9331. ASSERT_TRUE(svr.is_valid());
  9332. svr.Get("/test", [&](const Request &req, Response &res) {
  9333. res.set_content("test", "text/plain");
  9334. auto cert = req.peer_cert();
  9335. ASSERT_TRUE(static_cast<bool>(cert));
  9336. std::string common_name = cert.subject_cn();
  9337. EXPECT_EQ("Common Name", common_name);
  9338. });
  9339. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9340. auto se = detail::scope_exit([&] {
  9341. svr.stop();
  9342. t.join();
  9343. ASSERT_FALSE(svr.is_running());
  9344. });
  9345. svr.wait_until_ready();
  9346. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9347. client_encrypted_private_key_pass);
  9348. cli.enable_server_certificate_verification(false);
  9349. cli.set_connection_timeout(30);
  9350. auto res = cli.Get("/test");
  9351. ASSERT_TRUE(res);
  9352. ASSERT_EQ(StatusCode::OK_200, res->status);
  9353. }
  9354. TEST(SSLClientServerTest, ClientCertPresent) {
  9355. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9356. }
  9357. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9358. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9359. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9360. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9361. }
  9362. // PEM memory-based constructor tests (works with all TLS backends)
  9363. void PemMemoryClientCertPresent(
  9364. const std::string &client_cert_file,
  9365. const std::string &client_private_key_file,
  9366. const std::string &client_encrypted_private_key_pass = std::string()) {
  9367. // Read PEM files into memory
  9368. std::string server_cert_pem, server_key_pem;
  9369. std::string client_ca_pem;
  9370. std::string client_cert_pem, client_key_pem;
  9371. read_file(SERVER_CERT_FILE, server_cert_pem);
  9372. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9373. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9374. read_file(client_cert_file, client_cert_pem);
  9375. read_file(client_private_key_file, client_key_pem);
  9376. // Create server with PEM memory
  9377. SSLServer::PemMemory server_pem = {
  9378. server_cert_pem.c_str(),
  9379. server_cert_pem.size(),
  9380. server_key_pem.c_str(),
  9381. server_key_pem.size(),
  9382. client_ca_pem.c_str(),
  9383. client_ca_pem.size(),
  9384. nullptr // no password for server key
  9385. };
  9386. SSLServer svr(server_pem);
  9387. ASSERT_TRUE(svr.is_valid());
  9388. svr.Get("/test", [&](const Request &, Response &res) {
  9389. res.set_content("test", "text/plain");
  9390. });
  9391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9392. auto se = detail::scope_exit([&] {
  9393. svr.stop();
  9394. t.join();
  9395. ASSERT_FALSE(svr.is_running());
  9396. });
  9397. svr.wait_until_ready();
  9398. // Create client with PEM memory
  9399. const char *password = client_encrypted_private_key_pass.empty()
  9400. ? nullptr
  9401. : client_encrypted_private_key_pass.c_str();
  9402. SSLClient::PemMemory client_pem = {
  9403. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9404. client_key_pem.size(), password};
  9405. SSLClient cli(HOST, PORT, client_pem);
  9406. cli.enable_server_certificate_verification(false);
  9407. cli.set_connection_timeout(30);
  9408. auto res = cli.Get("/test");
  9409. ASSERT_TRUE(res);
  9410. ASSERT_EQ(StatusCode::OK_200, res->status);
  9411. }
  9412. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9413. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9414. }
  9415. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9416. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9417. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9418. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9419. }
  9420. TEST(SSLClientServerTest, ClientCertMissing) {
  9421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9422. CLIENT_CA_CERT_DIR);
  9423. ASSERT_TRUE(svr.is_valid());
  9424. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9426. auto se = detail::scope_exit([&] {
  9427. svr.stop();
  9428. t.join();
  9429. ASSERT_FALSE(svr.is_running());
  9430. });
  9431. svr.wait_until_ready();
  9432. SSLClient cli(HOST, PORT);
  9433. cli.set_connection_timeout(30);
  9434. auto res = cli.Get("/test");
  9435. ASSERT_TRUE(!res);
  9436. // When client cert is missing and server requires it, connection fails
  9437. // Error type depends on backend implementation
  9438. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9439. res.error() == Error::SSLConnection);
  9440. // Verify backend error is captured
  9441. // Note: This test may have different error codes depending on the exact
  9442. // verification failure
  9443. EXPECT_NE(0UL, res.ssl_backend_error());
  9444. }
  9445. TEST(SSLClientServerTest, TrustDirOptional) {
  9446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9447. ASSERT_TRUE(svr.is_valid());
  9448. svr.Get("/test", [&](const Request &, Response &res) {
  9449. res.set_content("test", "text/plain");
  9450. });
  9451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9452. auto se = detail::scope_exit([&] {
  9453. svr.stop();
  9454. t.join();
  9455. ASSERT_FALSE(svr.is_running());
  9456. });
  9457. svr.wait_until_ready();
  9458. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9459. cli.enable_server_certificate_verification(false);
  9460. cli.set_connection_timeout(30);
  9461. auto res = cli.Get("/test");
  9462. ASSERT_TRUE(res);
  9463. ASSERT_EQ(StatusCode::OK_200, res->status);
  9464. }
  9465. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9466. class NoListenSSLServer : public SSLServer {
  9467. public:
  9468. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9469. const char *client_ca_cert_file_path,
  9470. const char *client_ca_cert_dir_path = nullptr)
  9471. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9472. client_ca_cert_dir_path),
  9473. stop_(false) {}
  9474. std::atomic_bool stop_;
  9475. private:
  9476. bool process_and_close_socket(socket_t /*sock*/) override {
  9477. // Don't create SSL context
  9478. while (!stop_.load()) {
  9479. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9480. }
  9481. return true;
  9482. }
  9483. };
  9484. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9485. CLIENT_CA_CERT_FILE);
  9486. ASSERT_TRUE(svr.is_valid());
  9487. svr.Get("/test", [&](const Request &, Response &res) {
  9488. res.set_content("test", "text/plain");
  9489. });
  9490. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop_ = true;
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9499. cli.enable_server_certificate_verification(false);
  9500. cli.set_connection_timeout(1);
  9501. auto res = cli.Get("/test");
  9502. ASSERT_TRUE(!res);
  9503. EXPECT_EQ(Error::SSLConnection, res.error());
  9504. // Timeout results in WantRead error code (maps to backend-specific value)
  9505. EXPECT_NE(0, res.ssl_error());
  9506. }
  9507. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9508. // Test SSLServer with client certificate verification using the standard
  9509. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9511. CLIENT_CA_CERT_DIR);
  9512. ASSERT_TRUE(svr.is_valid());
  9513. svr.Get("/test", [&](const Request &req, Response &res) {
  9514. res.set_content("test", "text/plain");
  9515. auto cert = req.peer_cert();
  9516. ASSERT_TRUE(static_cast<bool>(cert));
  9517. auto common_name = cert.subject_cn();
  9518. EXPECT_EQ("Common Name", common_name);
  9519. });
  9520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9521. auto se = detail::scope_exit([&] {
  9522. svr.stop();
  9523. t.join();
  9524. ASSERT_FALSE(svr.is_running());
  9525. });
  9526. svr.wait_until_ready();
  9527. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9528. cli.enable_server_certificate_verification(false);
  9529. cli.set_connection_timeout(30);
  9530. auto res = cli.Get("/test");
  9531. ASSERT_TRUE(res);
  9532. ASSERT_EQ(StatusCode::OK_200, res->status);
  9533. }
  9534. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9535. // Verifies that wildcard matching and exact matching work consistently
  9536. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9537. using namespace httplib::tls;
  9538. // We need a running server to test against
  9539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9540. ASSERT_TRUE(svr.is_valid());
  9541. svr.Get("/test", [](const Request &, Response &res) {
  9542. res.set_content("ok", "text/plain");
  9543. });
  9544. thread t([&]() { svr.listen(HOST, PORT); });
  9545. auto se = detail::scope_exit([&] {
  9546. svr.stop();
  9547. t.join();
  9548. });
  9549. svr.wait_until_ready();
  9550. bool verify_callback_called = false;
  9551. bool verify_result_wrong = false;
  9552. SSLClient cli(HOST, PORT);
  9553. cli.enable_server_certificate_verification(true);
  9554. cli.set_ca_cert_path(CA_CERT_FILE);
  9555. cli.set_connection_timeout(5);
  9556. // Note: Test certificate has CN="Common Name", not "localhost"
  9557. bool verify_result_cn = false;
  9558. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9559. verify_callback_called = true;
  9560. if (!ctx.cert) return false;
  9561. // Test 1: "Common Name" should match (our test server cert CN)
  9562. verify_result_cn = ctx.check_hostname("Common Name");
  9563. // Test 2: wrong hostname should not match
  9564. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9565. return true; // Accept for the purpose of this test
  9566. });
  9567. auto res = cli.Get("/test");
  9568. // The request may succeed or fail depending on cert configuration
  9569. // but the callback should have been called
  9570. ASSERT_TRUE(verify_callback_called)
  9571. << "Verify callback should have been called";
  9572. // CN="Common Name" should match our test certificate
  9573. //
  9574. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9575. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9576. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9577. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9578. // <openssl/base.h>, which is included transitively when
  9579. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9580. #if defined(OPENSSL_IS_BORINGSSL)
  9581. EXPECT_FALSE(verify_result_cn)
  9582. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9583. #else
  9584. EXPECT_TRUE(verify_result_cn)
  9585. << "verify_hostname should match 'Common Name' (certificate CN)";
  9586. #endif
  9587. // Wrong hostname should not match
  9588. EXPECT_FALSE(verify_result_wrong)
  9589. << "verify_hostname should not match 'wronghost.example.com'";
  9590. }
  9591. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9592. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9593. // X509_check_ip behavior and must hold for every backend.
  9594. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9595. using namespace httplib::tls;
  9596. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9597. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9598. ASSERT_TRUE(svr.is_valid());
  9599. svr.Get("/test", [](const Request &, Response &res) {
  9600. res.set_content("ok", "text/plain");
  9601. });
  9602. thread t([&]() { svr.listen(HOST, PORT); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. });
  9607. svr.wait_until_ready();
  9608. bool verify_callback_called = false;
  9609. bool ip_matched_via_cn = true;
  9610. SSLClient cli(HOST, PORT);
  9611. cli.enable_server_certificate_verification(true);
  9612. cli.set_ca_cert_path(CA_CERT_FILE);
  9613. cli.set_connection_timeout(5);
  9614. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9615. verify_callback_called = true;
  9616. if (!ctx.cert) return false;
  9617. // The IP appears only in the CN, so it must NOT be accepted.
  9618. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9619. return true; // Accept for the purpose of this test
  9620. });
  9621. cli.Get("/test");
  9622. ASSERT_TRUE(verify_callback_called)
  9623. << "Verify callback should have been called";
  9624. EXPECT_FALSE(ip_matched_via_cn)
  9625. << "An IP host must not be authenticated via the certificate CN";
  9626. }
  9627. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9628. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9629. using namespace httplib::tls;
  9630. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9631. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9632. ASSERT_TRUE(svr.is_valid());
  9633. svr.Get("/test", [](const Request &, Response &res) {
  9634. res.set_content("ok", "text/plain");
  9635. });
  9636. thread t([&]() { svr.listen(HOST, PORT); });
  9637. auto se = detail::scope_exit([&] {
  9638. svr.stop();
  9639. t.join();
  9640. });
  9641. svr.wait_until_ready();
  9642. bool verify_callback_called = false;
  9643. bool san_matched = false;
  9644. bool wrong_ipv6_matched = true;
  9645. bool cn_ipv6_matched = true;
  9646. SSLClient cli(HOST, PORT);
  9647. cli.enable_server_certificate_verification(true);
  9648. cli.set_ca_cert_path(CA_CERT_FILE);
  9649. cli.set_connection_timeout(5);
  9650. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9651. verify_callback_called = true;
  9652. if (!ctx.cert) return false;
  9653. // Matches the IPv6 iPAddress SAN.
  9654. san_matched = ctx.check_hostname("2001:db8::1");
  9655. // A different IPv6 address must not match.
  9656. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9657. // "::1" lives only in the CN, so it must not be accepted.
  9658. cn_ipv6_matched = ctx.check_hostname("::1");
  9659. return true; // Accept for the purpose of this test
  9660. });
  9661. cli.Get("/test");
  9662. ASSERT_TRUE(verify_callback_called)
  9663. << "Verify callback should have been called";
  9664. EXPECT_TRUE(san_matched)
  9665. << "verify_hostname should match an IPv6 iPAddress SAN";
  9666. EXPECT_FALSE(wrong_ipv6_matched)
  9667. << "verify_hostname should not match a non-matching IPv6 address";
  9668. EXPECT_FALSE(cn_ipv6_matched)
  9669. << "An IPv6 host must not be authenticated via the certificate CN";
  9670. }
  9671. #endif
  9672. // mbedTLS-specific callback constructor test
  9673. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9674. #ifdef CPPHTTPLIB_SSL_ENABLED
  9675. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9677. ASSERT_TRUE(svr.is_valid());
  9678. // Set up a handler to verify client certificate is present
  9679. bool client_cert_verified = false;
  9680. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9681. // Verify that client certificate was provided
  9682. client_cert_verified = true;
  9683. res.set_content("success", "text/plain");
  9684. });
  9685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. });
  9691. svr.wait_until_ready();
  9692. // Client with certificate
  9693. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9694. cli.enable_server_certificate_verification(false);
  9695. cli.set_connection_timeout(30);
  9696. auto res = cli.Get("/test");
  9697. ASSERT_TRUE(res);
  9698. ASSERT_EQ(StatusCode::OK_200, res->status);
  9699. ASSERT_TRUE(client_cert_verified);
  9700. EXPECT_EQ("success", res->body);
  9701. }
  9702. #endif
  9703. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9704. // backends
  9705. #ifdef CPPHTTPLIB_SSL_ENABLED
  9706. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9707. using namespace httplib::tls;
  9708. // Test that when client CA cert file is provided,
  9709. // the server properly requests and validates client certificates
  9710. // Create a server with client authentication
  9711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9712. ASSERT_TRUE(svr.is_valid());
  9713. bool handler_called = false;
  9714. svr.Get("/test", [&](const Request &req, Response &res) {
  9715. handler_called = true;
  9716. // Verify that a client certificate was provided
  9717. auto cert = req.peer_cert();
  9718. ASSERT_TRUE(static_cast<bool>(cert));
  9719. // Get the issuer name
  9720. std::string issuer_str = cert.issuer_name();
  9721. ASSERT_FALSE(issuer_str.empty());
  9722. // The client certificate should be issued by our test CA
  9723. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9724. res.set_content("authenticated", "text/plain");
  9725. });
  9726. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. t.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. });
  9732. svr.wait_until_ready();
  9733. // Connect with a client certificate issued by the CA
  9734. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9735. cli.enable_server_certificate_verification(false);
  9736. cli.set_connection_timeout(30);
  9737. auto res = cli.Get("/test");
  9738. ASSERT_TRUE(res);
  9739. ASSERT_EQ(StatusCode::OK_200, res->status);
  9740. ASSERT_TRUE(handler_called);
  9741. EXPECT_EQ("authenticated", res->body);
  9742. }
  9743. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9744. using namespace httplib::tls;
  9745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9746. ASSERT_TRUE(svr.is_valid());
  9747. svr.Get("/test", [](const Request &, Response &res) {
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. t.join();
  9754. });
  9755. svr.wait_until_ready();
  9756. SSLClient cli(HOST, PORT);
  9757. cli.enable_server_certificate_verification(false);
  9758. cli.set_connection_timeout(30);
  9759. bool cert_checked = false;
  9760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9761. if (ctx.cert) {
  9762. auto sans = ctx.sans();
  9763. // Test certificate may or may not have SANs - just verify the API
  9764. // works If SANs exist, verify the types are valid
  9765. for (const auto &san : sans) {
  9766. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9767. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9768. san.type == SanType::OTHER);
  9769. EXPECT_FALSE(san.value.empty());
  9770. }
  9771. cert_checked = true;
  9772. }
  9773. return true;
  9774. });
  9775. auto res = cli.Get("/test");
  9776. ASSERT_TRUE(res);
  9777. EXPECT_TRUE(cert_checked);
  9778. }
  9779. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9780. using namespace httplib::tls;
  9781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9782. ASSERT_TRUE(svr.is_valid());
  9783. svr.Get("/test", [](const Request &, Response &res) {
  9784. res.set_content("ok", "text/plain");
  9785. });
  9786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9787. auto se = detail::scope_exit([&] {
  9788. svr.stop();
  9789. t.join();
  9790. });
  9791. svr.wait_until_ready();
  9792. SSLClient cli(HOST, PORT);
  9793. cli.enable_server_certificate_verification(false);
  9794. cli.set_connection_timeout(30);
  9795. bool validity_checked = false;
  9796. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9797. if (ctx.cert) {
  9798. time_t not_before = 0, not_after = 0;
  9799. bool result = ctx.validity(not_before, not_after);
  9800. EXPECT_TRUE(result);
  9801. // Verify that not_before < now < not_after for a valid cert
  9802. time_t now = time(nullptr);
  9803. EXPECT_LT(not_before, now);
  9804. EXPECT_GT(not_after, now);
  9805. validity_checked = true;
  9806. }
  9807. return true;
  9808. });
  9809. auto res = cli.Get("/test");
  9810. ASSERT_TRUE(res);
  9811. EXPECT_TRUE(validity_checked);
  9812. }
  9813. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9814. using namespace httplib::tls;
  9815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9816. ASSERT_TRUE(svr.is_valid());
  9817. svr.Get("/test", [](const Request &, Response &res) {
  9818. res.set_content("ok", "text/plain");
  9819. });
  9820. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9821. auto se = detail::scope_exit([&] {
  9822. svr.stop();
  9823. t.join();
  9824. });
  9825. svr.wait_until_ready();
  9826. SSLClient cli(HOST, PORT);
  9827. cli.enable_server_certificate_verification(false);
  9828. cli.set_connection_timeout(30);
  9829. bool serial_checked = false;
  9830. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9831. if (ctx.cert) {
  9832. std::string serial = ctx.serial();
  9833. EXPECT_FALSE(serial.empty());
  9834. // Serial should be a hex string
  9835. for (char c : serial) {
  9836. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9837. (c >= 'a' && c <= 'f'));
  9838. }
  9839. serial_checked = true;
  9840. }
  9841. return true;
  9842. });
  9843. auto res = cli.Get("/test");
  9844. ASSERT_TRUE(res);
  9845. EXPECT_TRUE(serial_checked);
  9846. }
  9847. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9848. // Test 1: Valid CA file - no error should be recorded
  9849. {
  9850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9851. CLIENT_CA_CERT_FILE);
  9852. ASSERT_TRUE(svr.is_valid());
  9853. // With valid setup, last_ssl_error should be 0
  9854. EXPECT_EQ(0, svr.ssl_last_error());
  9855. }
  9856. // Test 2: Invalid CA file content
  9857. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9858. {
  9859. // Create a temporary file with completely invalid content
  9860. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9861. {
  9862. std::ofstream ofs(temp_invalid_ca);
  9863. ofs << "This is not a certificate file at all\n";
  9864. ofs << "Just plain text content\n";
  9865. }
  9866. // Create server with invalid CA file
  9867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9868. // Clean up temporary file
  9869. std::remove(temp_invalid_ca);
  9870. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9871. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9872. // Note: SSL_CTX_load_verify_locations typically fails first,
  9873. // but our error handling code path is still exercised
  9874. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9875. }
  9876. }
  9877. TEST(VerifyCallbackTest, VerifyContextFields) {
  9878. using namespace httplib::tls;
  9879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9880. ASSERT_TRUE(svr.is_valid());
  9881. svr.Get("/test", [](const Request &, Response &res) {
  9882. res.set_content("ok", "text/plain");
  9883. });
  9884. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9885. auto se = detail::scope_exit([&] {
  9886. svr.stop();
  9887. t.join();
  9888. });
  9889. svr.wait_until_ready();
  9890. SSLClient cli(HOST, PORT);
  9891. cli.enable_server_certificate_verification(false);
  9892. cli.set_connection_timeout(30);
  9893. int callback_count = 0;
  9894. bool saw_leaf_cert = false;
  9895. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9896. if (ctx.cert) {
  9897. callback_count++;
  9898. // We should see at least one certificate (the leaf)
  9899. std::string cn = ctx.subject_cn();
  9900. if (!cn.empty()) { saw_leaf_cert = true; }
  9901. // Verify context fields are populated
  9902. EXPECT_NE(ctx.session, nullptr);
  9903. EXPECT_GE(ctx.depth, 0);
  9904. }
  9905. return true;
  9906. });
  9907. auto res = cli.Get("/test");
  9908. ASSERT_TRUE(res);
  9909. EXPECT_GT(callback_count, 0);
  9910. EXPECT_TRUE(saw_leaf_cert);
  9911. }
  9912. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9913. using httplib::tls::TlsError;
  9914. // Test that verify_error_to_string returns empty for success
  9915. std::string success_str = TlsError::verify_error_to_string(0);
  9916. EXPECT_TRUE(success_str.empty());
  9917. // Test that verify_error_to_string returns non-empty for error codes
  9918. // Using a common error code (certificate expired)
  9919. std::string error_str =
  9920. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9921. EXPECT_FALSE(error_str.empty());
  9922. }
  9923. TEST(SessionVerifierTest, CertificateAccepted) {
  9924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9925. ASSERT_TRUE(svr.is_valid());
  9926. svr.Get("/test", [](const Request &, Response &res) {
  9927. res.set_content("ok", "text/plain");
  9928. });
  9929. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9930. auto se = detail::scope_exit([&] {
  9931. svr.stop();
  9932. t.join();
  9933. });
  9934. svr.wait_until_ready();
  9935. SSLClient cli(HOST, PORT);
  9936. cli.enable_server_certificate_verification(false);
  9937. cli.set_connection_timeout(30);
  9938. bool callback_called = false;
  9939. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9940. EXPECT_NE(session, nullptr);
  9941. callback_called = true;
  9942. return SSLVerifierResponse::CertificateAccepted;
  9943. });
  9944. auto res = cli.Get("/test");
  9945. ASSERT_TRUE(res);
  9946. EXPECT_EQ(200, res->status);
  9947. EXPECT_TRUE(callback_called);
  9948. }
  9949. TEST(SessionVerifierTest, CertificateRejected) {
  9950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9951. ASSERT_TRUE(svr.is_valid());
  9952. svr.Get("/test", [](const Request &, Response &res) {
  9953. res.set_content("ok", "text/plain");
  9954. });
  9955. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. t.join();
  9959. });
  9960. svr.wait_until_ready();
  9961. SSLClient cli(HOST, PORT);
  9962. cli.enable_server_certificate_verification(false);
  9963. cli.set_connection_timeout(30);
  9964. bool callback_called = false;
  9965. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9966. EXPECT_NE(session, nullptr);
  9967. callback_called = true;
  9968. return SSLVerifierResponse::CertificateRejected;
  9969. });
  9970. auto res = cli.Get("/test");
  9971. EXPECT_FALSE(res);
  9972. EXPECT_TRUE(callback_called);
  9973. }
  9974. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9976. ASSERT_TRUE(svr.is_valid());
  9977. svr.Get("/test", [](const Request &, Response &res) {
  9978. res.set_content("ok", "text/plain");
  9979. });
  9980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9981. auto se = detail::scope_exit([&] {
  9982. svr.stop();
  9983. t.join();
  9984. });
  9985. svr.wait_until_ready();
  9986. // NoDecisionMade with verification disabled should succeed (no default check)
  9987. SSLClient cli(HOST, PORT);
  9988. cli.enable_server_certificate_verification(false);
  9989. cli.set_connection_timeout(30);
  9990. bool callback_called = false;
  9991. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9992. EXPECT_NE(session, nullptr);
  9993. callback_called = true;
  9994. return SSLVerifierResponse::NoDecisionMade;
  9995. });
  9996. auto res = cli.Get("/test");
  9997. ASSERT_TRUE(res);
  9998. EXPECT_EQ(200, res->status);
  9999. EXPECT_TRUE(callback_called);
  10000. }
  10001. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10003. ASSERT_TRUE(svr.is_valid());
  10004. svr.Get("/test", [](const Request &, Response &res) {
  10005. res.set_content("ok", "text/plain");
  10006. });
  10007. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10008. auto se = detail::scope_exit([&] {
  10009. svr.stop();
  10010. t.join();
  10011. });
  10012. svr.wait_until_ready();
  10013. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10014. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10015. // so we only check that the request fails, not whether the callback was
  10016. // called.
  10017. SSLClient cli(HOST, PORT);
  10018. cli.enable_server_certificate_verification(true);
  10019. cli.set_connection_timeout(30);
  10020. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10021. EXPECT_NE(session, nullptr);
  10022. return SSLVerifierResponse::NoDecisionMade;
  10023. });
  10024. auto res = cli.Get("/test");
  10025. EXPECT_FALSE(res);
  10026. }
  10027. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10028. // Test SSL server using PemMemory constructor with client CA certificates
  10029. // Read PEM files
  10030. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10031. read_file(SERVER_CERT_FILE, server_cert_pem);
  10032. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10033. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10034. // Create SSLServer with PemMemory constructor including client CA
  10035. SSLServer::PemMemory server_pem = {
  10036. server_cert_pem.c_str(),
  10037. server_cert_pem.size(),
  10038. server_key_pem.c_str(),
  10039. server_key_pem.size(),
  10040. client_ca_pem.c_str(),
  10041. client_ca_pem.size(),
  10042. nullptr // no password for server key
  10043. };
  10044. SSLServer svr(server_pem);
  10045. ASSERT_TRUE(svr.is_valid());
  10046. // No SSL error should be recorded for valid setup
  10047. EXPECT_EQ(0, svr.ssl_last_error());
  10048. // Set up server endpoints
  10049. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10050. res.set_content("ok", "text/plain");
  10051. });
  10052. // Start server in a thread
  10053. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10054. svr.wait_until_ready();
  10055. // Connect with client certificate (using constructor with paths)
  10056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10057. cli.enable_server_certificate_verification(false);
  10058. auto res = cli.Get("/test-pem-ca");
  10059. ASSERT_TRUE(res);
  10060. EXPECT_EQ(200, res->status);
  10061. EXPECT_EQ("ok", res->body);
  10062. svr.stop();
  10063. server_thread.join();
  10064. }
  10065. #endif
  10066. #ifdef _WIN32
  10067. TEST(CleanupTest, WSACleanup) {
  10068. int ret = WSACleanup();
  10069. ASSERT_EQ(0, ret);
  10070. }
  10071. #endif
  10072. #ifndef CPPHTTPLIB_SSL_ENABLED
  10073. TEST(NoSSLSupport, SimpleInterface) {
  10074. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10075. }
  10076. #endif
  10077. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10078. TEST(InvalidScheme, SimpleInterface) {
  10079. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10080. }
  10081. #endif
  10082. TEST(NoScheme, SimpleInterface) {
  10083. Client cli("yahoo.com:80");
  10084. ASSERT_TRUE(cli.is_valid());
  10085. }
  10086. TEST(SendAPI, SimpleInterface_Online) {
  10087. Client cli("http://yahoo.com");
  10088. Request req;
  10089. req.method = "GET";
  10090. req.path = "/";
  10091. auto res = cli.send(req);
  10092. ASSERT_TRUE(res);
  10093. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10094. }
  10095. TEST(SendAPI, WithParamsInRequest) {
  10096. Server svr;
  10097. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10098. EXPECT_TRUE(req.has_param("test"));
  10099. EXPECT_EQ("test_value", req.get_param_value("test"));
  10100. });
  10101. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10102. auto se = detail::scope_exit([&] {
  10103. svr.stop();
  10104. t.join();
  10105. ASSERT_FALSE(svr.is_running());
  10106. });
  10107. svr.wait_until_ready();
  10108. Client cli(HOST, PORT);
  10109. {
  10110. Request req;
  10111. req.method = "GET";
  10112. req.path = "/";
  10113. req.params.emplace("test", "test_value");
  10114. auto res = cli.send(req);
  10115. ASSERT_TRUE(res);
  10116. }
  10117. {
  10118. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10119. ASSERT_TRUE(res);
  10120. }
  10121. }
  10122. TEST(ClientImplMethods, GetSocketTest) {
  10123. httplib::Server svr;
  10124. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10125. res.status = StatusCode::OK_200;
  10126. });
  10127. auto port = svr.bind_to_any_port("127.0.0.1");
  10128. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10129. auto se = detail::scope_exit([&] {
  10130. svr.stop();
  10131. thread.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. });
  10134. svr.wait_until_ready();
  10135. {
  10136. httplib::Client cli("127.0.0.1", port);
  10137. cli.set_keep_alive(true);
  10138. // Use the behavior of cpp-httplib of opening the connection
  10139. // only when the first request happens. If that changes,
  10140. // this test would be obsolete.
  10141. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10142. // This also implicitly tests the server. But other tests would fail much
  10143. // earlier than this one to be considered.
  10144. auto res = cli.Get("/");
  10145. ASSERT_TRUE(res);
  10146. EXPECT_EQ(StatusCode::OK_200, res->status);
  10147. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10148. }
  10149. }
  10150. #ifdef CPPHTTPLIB_SSL_ENABLED
  10151. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10152. Client cli("http://yahoo.com");
  10153. auto res = cli.Get("/");
  10154. ASSERT_TRUE(res);
  10155. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10156. cli.set_follow_location(true);
  10157. res = cli.Get("/");
  10158. ASSERT_TRUE(res);
  10159. EXPECT_EQ(StatusCode::OK_200, res->status);
  10160. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10161. }
  10162. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10163. Client cli("https://yahoo.com");
  10164. auto res = cli.Get("/");
  10165. ASSERT_TRUE(res);
  10166. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10167. cli.set_follow_location(true);
  10168. res = cli.Get("/");
  10169. ASSERT_TRUE(res);
  10170. EXPECT_EQ(StatusCode::OK_200, res->status);
  10171. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10172. }
  10173. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10174. Client cli("https://yahoo.com");
  10175. auto res = cli.Get("/");
  10176. ASSERT_TRUE(res);
  10177. ASSERT_FALSE(!res);
  10178. ASSERT_TRUE(res);
  10179. ASSERT_FALSE(res == nullptr);
  10180. ASSERT_TRUE(res != nullptr);
  10181. EXPECT_EQ(Error::Success, res.error());
  10182. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10183. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10185. cli.set_follow_location(true);
  10186. res = cli.Get("/");
  10187. ASSERT_TRUE(res);
  10188. EXPECT_EQ(Error::Success, res.error());
  10189. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10190. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10191. EXPECT_EQ(StatusCode::OK_200, res->status);
  10192. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10193. }
  10194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10195. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10196. Client cli("https://cdnjs.cloudflare.com");
  10197. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10198. Headers{{"Accept-Encoding", "br"}});
  10199. ASSERT_TRUE(res);
  10200. EXPECT_EQ(StatusCode::OK_200, res->status);
  10201. EXPECT_EQ(287630U, res->body.size());
  10202. EXPECT_EQ("application/javascript; charset=utf-8",
  10203. res->get_header_value("Content-Type"));
  10204. }
  10205. #endif
  10206. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10207. #undef REDIR_HOST // Silence compiler warning
  10208. #define REDIR_HOST "https://httpbingo.org"
  10209. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10210. Client cli(REDIR_HOST);
  10211. cli.set_follow_location(true);
  10212. auto res =
  10213. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10214. ASSERT_TRUE(res);
  10215. EXPECT_EQ(StatusCode::OK_200, res->status);
  10216. }
  10217. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10218. Client cli(REDIR_HOST);
  10219. cli.set_follow_location(true);
  10220. Params params;
  10221. params.emplace("url", "http://example.com");
  10222. params.emplace("status_code", "302");
  10223. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10224. ASSERT_TRUE(res);
  10225. EXPECT_EQ(StatusCode::OK_200, res->status);
  10226. }
  10227. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10228. Client cli(REDIR_HOST);
  10229. cli.set_follow_location(true);
  10230. Params params;
  10231. params.emplace("url", "http://example.com");
  10232. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10233. ASSERT_TRUE(res);
  10234. EXPECT_EQ(StatusCode::OK_200, res->status);
  10235. }
  10236. TEST(HttpToHttpsRedirectTest, CertFile) {
  10237. auto ssl_port = PORT + 1;
  10238. Server svr;
  10239. ASSERT_TRUE(svr.is_valid());
  10240. svr.Get("/index", [&](const Request &, Response &res) {
  10241. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10242. "/index");
  10243. svr.stop();
  10244. });
  10245. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10246. ASSERT_TRUE(ssl_svr.is_valid());
  10247. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10248. res.set_content("test", "text/plain");
  10249. ssl_svr.stop();
  10250. });
  10251. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10252. thread t2 =
  10253. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10254. auto se = detail::scope_exit([&] {
  10255. t2.join();
  10256. t.join();
  10257. ASSERT_FALSE(svr.is_running());
  10258. });
  10259. svr.wait_until_ready();
  10260. ssl_svr.wait_until_ready();
  10261. Client cli("127.0.0.1", PORT);
  10262. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10263. cli.enable_server_certificate_verification(true);
  10264. cli.set_follow_location(true);
  10265. cli.set_connection_timeout(30);
  10266. auto res = cli.Get("/index");
  10267. ASSERT_TRUE(res);
  10268. ASSERT_EQ(StatusCode::OK_200, res->status);
  10269. }
  10270. TEST(SSLClientRedirectTest, CertFile) {
  10271. auto ssl_port = PORT + 1;
  10272. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10273. ASSERT_TRUE(ssl_svr1.is_valid());
  10274. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10275. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10276. "/index");
  10277. ssl_svr1.stop();
  10278. });
  10279. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10280. ASSERT_TRUE(ssl_svr2.is_valid());
  10281. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10282. res.set_content("test", "text/plain");
  10283. ssl_svr2.stop();
  10284. });
  10285. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10286. thread t2 =
  10287. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10288. auto se = detail::scope_exit([&] {
  10289. t2.join();
  10290. t.join();
  10291. ASSERT_FALSE(ssl_svr1.is_running());
  10292. });
  10293. ssl_svr1.wait_until_ready();
  10294. ssl_svr2.wait_until_ready();
  10295. SSLClient cli("127.0.0.1", PORT);
  10296. std::string cert;
  10297. read_file(SERVER_CERT2_FILE, cert);
  10298. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10299. cli.enable_server_certificate_verification(true);
  10300. cli.set_follow_location(true);
  10301. cli.set_connection_timeout(30);
  10302. auto res = cli.Get("/index");
  10303. ASSERT_TRUE(res);
  10304. ASSERT_EQ(StatusCode::OK_200, res->status);
  10305. }
  10306. #endif
  10307. #ifdef CPPHTTPLIB_SSL_ENABLED
  10308. // Test that set_ca_cert_store() skips system certs (consistent with
  10309. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10310. // should be trusted - system certs should NOT be loaded.
  10311. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10312. // Load a specific cert that is NOT a system CA cert
  10313. std::string cert;
  10314. read_file(SERVER_CERT2_FILE, cert);
  10315. SSLClient cli("google.com");
  10316. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10317. cli.enable_server_certificate_verification(true);
  10318. // This should FAIL because:
  10319. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10320. // 2. System certs should NOT be loaded when custom store is set
  10321. // If system certs WERE loaded, this would succeed
  10322. auto res = cli.Get("/");
  10323. ASSERT_FALSE(res);
  10324. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10325. }
  10326. // Same as above, but through the native store handle path. Regression test:
  10327. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10328. // merged system certs into the user-provided store.
  10329. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10330. std::string cert;
  10331. read_file(SERVER_CERT2_FILE, cert);
  10332. SSLClient cli("google.com");
  10333. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10334. cli.enable_server_certificate_verification(true);
  10335. auto res = cli.Get("/");
  10336. ASSERT_FALSE(res);
  10337. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10338. }
  10339. // A custom store set via the native handle must still verify a server whose
  10340. // cert it does contain.
  10341. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10342. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10343. ASSERT_TRUE(svr.is_valid());
  10344. svr.Get("/test", [&](const Request &, Response &res) {
  10345. res.set_content("test", "text/plain");
  10346. });
  10347. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. ASSERT_FALSE(svr.is_running());
  10352. });
  10353. svr.wait_until_ready();
  10354. SSLClient cli("127.0.0.1", PORT);
  10355. std::string cert;
  10356. read_file(SERVER_CERT2_FILE, cert);
  10357. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10358. cli.enable_server_certificate_verification(true);
  10359. cli.set_connection_timeout(30);
  10360. auto res = cli.Get("/test");
  10361. ASSERT_TRUE(res);
  10362. ASSERT_EQ(StatusCode::OK_200, res->status);
  10363. }
  10364. // CA certs loaded through the universal Client must be transferred to the
  10365. // client created internally for following an HTTPS redirect. Regression test:
  10366. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10367. // the CA data for redirect transfer.
  10368. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10369. auto ssl_port = PORT + 1;
  10370. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10371. ASSERT_TRUE(ssl_svr1.is_valid());
  10372. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10373. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10374. "/index");
  10375. });
  10376. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10377. ASSERT_TRUE(ssl_svr2.is_valid());
  10378. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10379. res.set_content("test", "text/plain");
  10380. });
  10381. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10382. thread t2 =
  10383. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10384. auto se = detail::scope_exit([&] {
  10385. ssl_svr2.stop();
  10386. ssl_svr1.stop();
  10387. t2.join();
  10388. t.join();
  10389. ASSERT_FALSE(ssl_svr1.is_running());
  10390. });
  10391. ssl_svr1.wait_until_ready();
  10392. ssl_svr2.wait_until_ready();
  10393. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10394. std::string cert;
  10395. read_file(SERVER_CERT2_FILE, cert);
  10396. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10397. cli.enable_server_certificate_verification(true);
  10398. cli.set_follow_location(true);
  10399. cli.set_connection_timeout(30);
  10400. auto res = cli.Get("/index");
  10401. ASSERT_TRUE(res);
  10402. ASSERT_EQ(StatusCode::OK_200, res->status);
  10403. }
  10404. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10405. // so a host signed by a system CA verifies even though a custom CA is set
  10406. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10407. std::string cert;
  10408. read_file(SERVER_CERT2_FILE, cert);
  10409. SSLClient cli("google.com");
  10410. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10411. cli.enable_system_ca(true);
  10412. cli.enable_server_certificate_verification(true);
  10413. auto res = cli.Get("/");
  10414. ASSERT_TRUE(res);
  10415. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10416. }
  10417. // The custom CA remains effective when combined with the system CA
  10418. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10419. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10420. ASSERT_TRUE(svr.is_valid());
  10421. svr.Get("/test", [&](const Request &, Response &res) {
  10422. res.set_content("test", "text/plain");
  10423. });
  10424. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10425. auto se = detail::scope_exit([&] {
  10426. svr.stop();
  10427. t.join();
  10428. ASSERT_FALSE(svr.is_running());
  10429. });
  10430. svr.wait_until_ready();
  10431. SSLClient cli("127.0.0.1", PORT);
  10432. std::string cert;
  10433. read_file(SERVER_CERT2_FILE, cert);
  10434. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10435. cli.enable_system_ca(true);
  10436. cli.enable_server_certificate_verification(true);
  10437. cli.set_connection_timeout(30);
  10438. auto res = cli.Get("/test");
  10439. ASSERT_TRUE(res);
  10440. ASSERT_EQ(StatusCode::OK_200, res->status);
  10441. }
  10442. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10443. // skip chain verification entirely (only the certificate identity was
  10444. // checked), so a server presenting an untrusted certificate with a matching
  10445. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10446. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10447. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10448. ASSERT_TRUE(svr.is_valid());
  10449. svr.Get("/test", [&](const Request &, Response &res) {
  10450. res.set_content("test", "text/plain");
  10451. });
  10452. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10453. auto se = detail::scope_exit([&] {
  10454. svr.stop();
  10455. t.join();
  10456. ASSERT_FALSE(svr.is_running());
  10457. });
  10458. svr.wait_until_ready();
  10459. SSLClient cli("127.0.0.1", PORT);
  10460. std::string cert;
  10461. // A trusted CA that did not sign the server certificate. The server cert
  10462. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10463. // this connection.
  10464. read_file(CLIENT_CA_CERT_FILE, cert);
  10465. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10466. cli.enable_server_certificate_verification(true);
  10467. cli.set_connection_timeout(30);
  10468. auto res = cli.Get("/test");
  10469. ASSERT_FALSE(res);
  10470. }
  10471. // enable_system_ca(false) prevents system CA loading entirely
  10472. TEST(SSLClientTest, DisableSystemCa_Online) {
  10473. SSLClient cli("google.com");
  10474. cli.enable_system_ca(false);
  10475. cli.enable_server_certificate_verification(true);
  10476. auto res = cli.Get("/");
  10477. ASSERT_FALSE(res);
  10478. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10479. // itself when the CA chain is empty
  10480. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10481. res.error() == Error::SSLConnection);
  10482. }
  10483. // The universal Client forwards enable_system_ca()
  10484. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10485. std::string cert;
  10486. read_file(SERVER_CERT2_FILE, cert);
  10487. Client cli("https://google.com");
  10488. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10489. cli.enable_system_ca(true);
  10490. cli.enable_server_certificate_verification(true);
  10491. auto res = cli.Get("/");
  10492. ASSERT_TRUE(res);
  10493. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10494. }
  10495. // The system CA policy must carry over to the client created internally for
  10496. // following a cross-host HTTPS redirect
  10497. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10498. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10499. ASSERT_TRUE(svr.is_valid());
  10500. svr.Get("/index", [&](const Request &, Response &res) {
  10501. res.set_redirect("https://www.google.com/");
  10502. });
  10503. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10504. auto se = detail::scope_exit([&] {
  10505. svr.stop();
  10506. t.join();
  10507. ASSERT_FALSE(svr.is_running());
  10508. });
  10509. svr.wait_until_ready();
  10510. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10511. std::string cert;
  10512. read_file(SERVER_CERT2_FILE, cert);
  10513. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10514. cli.enable_system_ca(true);
  10515. cli.enable_server_certificate_verification(true);
  10516. cli.set_follow_location(true);
  10517. cli.set_connection_timeout(30);
  10518. // Receiving any response proves the redirect client completed the TLS
  10519. // handshake with a system-CA-signed host
  10520. auto res = cli.Get("/index");
  10521. ASSERT_TRUE(res);
  10522. }
  10523. TEST(MultipartFormDataTest, LargeData) {
  10524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10525. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10526. const ContentReader &content_reader) {
  10527. if (req.is_multipart_form_data()) {
  10528. std::vector<FormData> items;
  10529. content_reader(
  10530. [&](const FormData &file) {
  10531. items.push_back(file);
  10532. return true;
  10533. },
  10534. [&](const char *data, size_t data_length) {
  10535. items.back().content.append(data, data_length);
  10536. return true;
  10537. });
  10538. EXPECT_TRUE(std::string(items[0].name) == "document");
  10539. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10540. EXPECT_TRUE(items[0].filename == "2MB_data");
  10541. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10542. EXPECT_TRUE(items[1].name == "hello");
  10543. EXPECT_TRUE(items[1].content == "world");
  10544. EXPECT_TRUE(items[1].filename == "");
  10545. EXPECT_TRUE(items[1].content_type == "");
  10546. } else {
  10547. std::string body;
  10548. content_reader([&](const char *data, size_t data_length) {
  10549. body.append(data, data_length);
  10550. return true;
  10551. });
  10552. }
  10553. });
  10554. auto port = svr.bind_to_any_port(HOST);
  10555. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10556. auto se = detail::scope_exit([&] {
  10557. svr.stop();
  10558. t.join();
  10559. ASSERT_FALSE(svr.is_running());
  10560. });
  10561. svr.wait_until_ready();
  10562. {
  10563. std::string data(1024 * 1024 * 2, '.');
  10564. std::stringstream buffer;
  10565. buffer << data;
  10566. SSLClient cli(HOST, port);
  10567. cli.enable_server_certificate_verification(false);
  10568. UploadFormDataItems items{
  10569. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10570. {"hello", "world", "", ""},
  10571. };
  10572. auto res = cli.Post("/post", items);
  10573. ASSERT_TRUE(res);
  10574. ASSERT_EQ(StatusCode::OK_200, res->status);
  10575. }
  10576. }
  10577. TEST(MultipartFormDataTest, DataProviderItems) {
  10578. std::random_device seed_gen;
  10579. std::mt19937 random(seed_gen());
  10580. std::string rand1;
  10581. rand1.resize(1000);
  10582. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10583. std::string rand2;
  10584. rand2.resize(3000);
  10585. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10587. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10588. const ContentReader &content_reader) {
  10589. ASSERT_FALSE(req.is_multipart_form_data());
  10590. std::string body;
  10591. content_reader([&](const char *data, size_t data_length) {
  10592. body.append(data, data_length);
  10593. return true;
  10594. });
  10595. EXPECT_EQ(body, "");
  10596. });
  10597. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10598. const ContentReader &content_reader) {
  10599. ASSERT_TRUE(req.is_multipart_form_data());
  10600. std::vector<FormData> items;
  10601. content_reader(
  10602. [&](const FormData &file) {
  10603. items.push_back(file);
  10604. return true;
  10605. },
  10606. [&](const char *data, size_t data_length) {
  10607. items.back().content.append(data, data_length);
  10608. return true;
  10609. });
  10610. ASSERT_TRUE(items.size() == 2);
  10611. EXPECT_EQ(std::string(items[0].name), "name1");
  10612. EXPECT_EQ(items[0].content, "Testing123");
  10613. EXPECT_EQ(items[0].filename, "filename1");
  10614. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10615. EXPECT_EQ(items[1].name, "name2");
  10616. EXPECT_EQ(items[1].content, "Testing456");
  10617. EXPECT_EQ(items[1].filename, "");
  10618. EXPECT_EQ(items[1].content_type, "");
  10619. });
  10620. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10621. const ContentReader &content_reader) {
  10622. ASSERT_TRUE(req.is_multipart_form_data());
  10623. std::vector<FormData> items;
  10624. content_reader(
  10625. [&](const FormData &file) {
  10626. items.push_back(file);
  10627. return true;
  10628. },
  10629. [&](const char *data, size_t data_length) {
  10630. items.back().content.append(data, data_length);
  10631. return true;
  10632. });
  10633. ASSERT_TRUE(items.size() == 2);
  10634. EXPECT_EQ(items[0].name, "name3");
  10635. EXPECT_EQ(items[0].content, rand1);
  10636. EXPECT_EQ(items[0].filename, "filename3");
  10637. EXPECT_EQ(items[0].content_type, "");
  10638. EXPECT_EQ(items[1].name, "name4");
  10639. EXPECT_EQ(items[1].content, rand2);
  10640. EXPECT_EQ(items[1].filename, "filename4");
  10641. EXPECT_EQ(items[1].content_type, "");
  10642. });
  10643. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10644. const ContentReader &content_reader) {
  10645. ASSERT_TRUE(req.is_multipart_form_data());
  10646. std::vector<FormData> items;
  10647. content_reader(
  10648. [&](const FormData &file) {
  10649. items.push_back(file);
  10650. return true;
  10651. },
  10652. [&](const char *data, size_t data_length) {
  10653. items.back().content.append(data, data_length);
  10654. return true;
  10655. });
  10656. ASSERT_TRUE(items.size() == 4);
  10657. EXPECT_EQ(std::string(items[0].name), "name1");
  10658. EXPECT_EQ(items[0].content, "Testing123");
  10659. EXPECT_EQ(items[0].filename, "filename1");
  10660. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10661. EXPECT_EQ(items[1].name, "name2");
  10662. EXPECT_EQ(items[1].content, "Testing456");
  10663. EXPECT_EQ(items[1].filename, "");
  10664. EXPECT_EQ(items[1].content_type, "");
  10665. EXPECT_EQ(items[2].name, "name3");
  10666. EXPECT_EQ(items[2].content, rand1);
  10667. EXPECT_EQ(items[2].filename, "filename3");
  10668. EXPECT_EQ(items[2].content_type, "");
  10669. EXPECT_EQ(items[3].name, "name4");
  10670. EXPECT_EQ(items[3].content, rand2);
  10671. EXPECT_EQ(items[3].filename, "filename4");
  10672. EXPECT_EQ(items[3].content_type, "");
  10673. });
  10674. auto port = svr.bind_to_any_port("localhost");
  10675. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. {
  10683. SSLClient cli("localhost", port);
  10684. cli.enable_server_certificate_verification(false);
  10685. UploadFormDataItems items{
  10686. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10687. {"name2", "Testing456", "", ""}, // not a file
  10688. };
  10689. {
  10690. auto res = cli.Post("/post-none", {}, {}, {});
  10691. ASSERT_TRUE(res);
  10692. ASSERT_EQ(StatusCode::OK_200, res->status);
  10693. }
  10694. FormDataProviderItems providers;
  10695. {
  10696. auto res =
  10697. cli.Post("/post-items", {}, items, providers); // empty providers
  10698. ASSERT_TRUE(res);
  10699. ASSERT_EQ(StatusCode::OK_200, res->status);
  10700. }
  10701. providers.push_back({"name3",
  10702. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10703. // test the offset is given correctly at each step
  10704. if (!offset)
  10705. sink.os.write(rand1.data(), 30);
  10706. else if (offset == 30)
  10707. sink.os.write(rand1.data() + 30, 300);
  10708. else if (offset == 330)
  10709. sink.os.write(rand1.data() + 330, 670);
  10710. else if (offset == rand1.size())
  10711. sink.done();
  10712. return true;
  10713. },
  10714. "filename3",
  10715. {}});
  10716. providers.push_back({"name4",
  10717. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10718. // test the offset is given correctly at each step
  10719. if (!offset)
  10720. sink.os.write(rand2.data(), 2000);
  10721. else if (offset == 2000)
  10722. sink.os.write(rand2.data() + 2000, 1);
  10723. else if (offset == 2001)
  10724. sink.os.write(rand2.data() + 2001, 999);
  10725. else if (offset == rand2.size())
  10726. sink.done();
  10727. return true;
  10728. },
  10729. "filename4",
  10730. {}});
  10731. {
  10732. auto res = cli.Post("/post-providers", {}, {}, providers);
  10733. ASSERT_TRUE(res);
  10734. ASSERT_EQ(StatusCode::OK_200, res->status);
  10735. }
  10736. {
  10737. auto res = cli.Post("/post-both", {}, items, providers);
  10738. ASSERT_TRUE(res);
  10739. ASSERT_EQ(StatusCode::OK_200, res->status);
  10740. }
  10741. }
  10742. }
  10743. TEST(MultipartFormDataTest, BadHeader) {
  10744. Server svr;
  10745. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10746. res.set_content("ok", "text/plain");
  10747. });
  10748. thread t = thread([&] { svr.listen(HOST, PORT); });
  10749. auto se = detail::scope_exit([&] {
  10750. svr.stop();
  10751. t.join();
  10752. ASSERT_FALSE(svr.is_running());
  10753. });
  10754. svr.wait_until_ready();
  10755. const std::string body =
  10756. "This is the preamble. It is to be ignored, though it\r\n"
  10757. "is a handy place for composition agents to include an\r\n"
  10758. "explanatory note to non-MIME conformant readers.\r\n"
  10759. "\r\n"
  10760. "\r\n"
  10761. "--simple boundary\r\n"
  10762. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10763. ": BAD...\r\n"
  10764. "\r\n"
  10765. "value1\r\n"
  10766. "--simple boundary\r\n"
  10767. "Content-Disposition: form-data; name=\"field2\"; "
  10768. "filename=\"example.txt\"\r\n"
  10769. "\r\n"
  10770. "value2\r\n"
  10771. "--simple boundary--\r\n"
  10772. "This is the epilogue. It is also to be ignored.\r\n";
  10773. std::string content_type =
  10774. R"(multipart/form-data; boundary="simple boundary")";
  10775. Client cli(HOST, PORT);
  10776. auto res = cli.Post("/post", body, content_type.c_str());
  10777. ASSERT_TRUE(res);
  10778. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10779. }
  10780. TEST(MultipartFormDataTest, WithPreamble) {
  10781. Server svr;
  10782. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10783. res.set_content("ok", "text/plain");
  10784. });
  10785. thread t = thread([&] { svr.listen(HOST, PORT); });
  10786. auto se = detail::scope_exit([&] {
  10787. svr.stop();
  10788. t.join();
  10789. ASSERT_FALSE(svr.is_running());
  10790. });
  10791. svr.wait_until_ready();
  10792. const std::string body =
  10793. "This is the preamble. It is to be ignored, though it\r\n"
  10794. "is a handy place for composition agents to include an\r\n"
  10795. "explanatory note to non-MIME conformant readers.\r\n"
  10796. "\r\n"
  10797. "\r\n"
  10798. "--simple boundary\r\n"
  10799. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10800. "\r\n"
  10801. "value1\r\n"
  10802. "--simple boundary\r\n"
  10803. "Content-Disposition: form-data; name=\"field2\"; "
  10804. "filename=\"example.txt\"\r\n"
  10805. "\r\n"
  10806. "value2\r\n"
  10807. "--simple boundary--\r\n"
  10808. "This is the epilogue. It is also to be ignored.\r\n";
  10809. std::string content_type =
  10810. R"(multipart/form-data; boundary="simple boundary")";
  10811. Client cli(HOST, PORT);
  10812. auto res = cli.Post("/post", body, content_type.c_str());
  10813. ASSERT_TRUE(res);
  10814. EXPECT_EQ(StatusCode::OK_200, res->status);
  10815. }
  10816. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10818. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10819. const ContentReader &content_reader) {
  10820. if (req.is_multipart_form_data()) {
  10821. std::vector<FormData> items;
  10822. content_reader(
  10823. [&](const FormData &file) {
  10824. items.push_back(file);
  10825. return true;
  10826. },
  10827. [&](const char *data, size_t data_length) {
  10828. items.back().content.append(data, data_length);
  10829. return true;
  10830. });
  10831. EXPECT_TRUE(std::string(items[0].name) == "document");
  10832. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10833. EXPECT_TRUE(items[0].filename == "2MB_data");
  10834. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10835. EXPECT_TRUE(items[1].name == "hello");
  10836. EXPECT_TRUE(items[1].content == "world");
  10837. EXPECT_TRUE(items[1].filename == "");
  10838. EXPECT_TRUE(items[1].content_type == "");
  10839. } else {
  10840. std::string body;
  10841. content_reader([&](const char *data, size_t data_length) {
  10842. body.append(data, data_length);
  10843. return true;
  10844. });
  10845. }
  10846. });
  10847. auto port = svr.bind_to_any_port("localhost");
  10848. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10849. auto se = detail::scope_exit([&] {
  10850. svr.stop();
  10851. t.join();
  10852. ASSERT_FALSE(svr.is_running());
  10853. });
  10854. svr.wait_until_ready();
  10855. {
  10856. std::string data(1024 * 1024 * 2, '.');
  10857. std::stringstream buffer;
  10858. buffer << data;
  10859. SSLClient cli("localhost", port);
  10860. cli.enable_server_certificate_verification(false);
  10861. UploadFormDataItems items{
  10862. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10863. {"hello", "world", "", ""},
  10864. };
  10865. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10866. ASSERT_TRUE(res);
  10867. ASSERT_EQ(StatusCode::OK_200, res->status);
  10868. }
  10869. }
  10870. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10871. std::string data(1024 * 1024 * 2, '&');
  10872. std::stringstream buffer;
  10873. buffer << data;
  10874. Client cli("https://localhost:8080");
  10875. UploadFormDataItems items{
  10876. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10877. {"hello", "world", "", ""},
  10878. };
  10879. for (const char &c : " \t\r\n") {
  10880. auto res =
  10881. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10882. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10883. ASSERT_FALSE(res);
  10884. }
  10885. }
  10886. TEST(MultipartFormDataTest, PutFormData) {
  10887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10888. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10889. const ContentReader &content_reader) {
  10890. if (req.is_multipart_form_data()) {
  10891. std::vector<FormData> items;
  10892. content_reader(
  10893. [&](const FormData &file) {
  10894. items.push_back(file);
  10895. return true;
  10896. },
  10897. [&](const char *data, size_t data_length) {
  10898. items.back().content.append(data, data_length);
  10899. return true;
  10900. });
  10901. EXPECT_TRUE(std::string(items[0].name) == "document");
  10902. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10903. EXPECT_TRUE(items[0].filename == "2MB_data");
  10904. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10905. EXPECT_TRUE(items[1].name == "hello");
  10906. EXPECT_TRUE(items[1].content == "world");
  10907. EXPECT_TRUE(items[1].filename == "");
  10908. EXPECT_TRUE(items[1].content_type == "");
  10909. } else {
  10910. std::string body;
  10911. content_reader([&](const char *data, size_t data_length) {
  10912. body.append(data, data_length);
  10913. return true;
  10914. });
  10915. }
  10916. });
  10917. auto port = svr.bind_to_any_port("localhost");
  10918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. t.join();
  10922. ASSERT_FALSE(svr.is_running());
  10923. });
  10924. svr.wait_until_ready();
  10925. {
  10926. std::string data(1024 * 1024 * 2, '&');
  10927. std::stringstream buffer;
  10928. buffer << data;
  10929. SSLClient cli("localhost", port);
  10930. cli.enable_server_certificate_verification(false);
  10931. UploadFormDataItems items{
  10932. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10933. {"hello", "world", "", ""},
  10934. };
  10935. auto res = cli.Put("/put", items);
  10936. ASSERT_TRUE(res);
  10937. ASSERT_EQ(StatusCode::OK_200, res->status);
  10938. }
  10939. }
  10940. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10942. svr.Put("/put_customboundary",
  10943. [&](const Request &req, const Response & /*res*/,
  10944. const ContentReader &content_reader) {
  10945. if (req.is_multipart_form_data()) {
  10946. std::vector<FormData> items;
  10947. content_reader(
  10948. [&](const FormData &file) {
  10949. items.push_back(file);
  10950. return true;
  10951. },
  10952. [&](const char *data, size_t data_length) {
  10953. items.back().content.append(data, data_length);
  10954. return true;
  10955. });
  10956. EXPECT_TRUE(std::string(items[0].name) == "document");
  10957. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10958. EXPECT_TRUE(items[0].filename == "2MB_data");
  10959. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10960. EXPECT_TRUE(items[1].name == "hello");
  10961. EXPECT_TRUE(items[1].content == "world");
  10962. EXPECT_TRUE(items[1].filename == "");
  10963. EXPECT_TRUE(items[1].content_type == "");
  10964. } else {
  10965. std::string body;
  10966. content_reader([&](const char *data, size_t data_length) {
  10967. body.append(data, data_length);
  10968. return true;
  10969. });
  10970. }
  10971. });
  10972. auto port = svr.bind_to_any_port("localhost");
  10973. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10974. auto se = detail::scope_exit([&] {
  10975. svr.stop();
  10976. t.join();
  10977. ASSERT_FALSE(svr.is_running());
  10978. });
  10979. svr.wait_until_ready();
  10980. {
  10981. std::string data(1024 * 1024 * 2, '&');
  10982. std::stringstream buffer;
  10983. buffer << data;
  10984. SSLClient cli("localhost", port);
  10985. cli.enable_server_certificate_verification(false);
  10986. UploadFormDataItems items{
  10987. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10988. {"hello", "world", "", ""},
  10989. };
  10990. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10991. ASSERT_TRUE(res);
  10992. ASSERT_EQ(StatusCode::OK_200, res->status);
  10993. }
  10994. }
  10995. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10996. std::string data(1024 * 1024 * 2, '&');
  10997. std::stringstream buffer;
  10998. buffer << data;
  10999. Client cli("https://localhost:8080");
  11000. cli.enable_server_certificate_verification(false);
  11001. UploadFormDataItems items{
  11002. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11003. {"hello", "world", "", ""},
  11004. };
  11005. for (const char &c : " \t\r\n") {
  11006. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11007. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11008. ASSERT_FALSE(res);
  11009. }
  11010. }
  11011. TEST(MultipartFormDataTest, AlternateFilename) {
  11012. auto handled = false;
  11013. Server svr;
  11014. svr.Post("/test", [&](const Request &req, Response &res) {
  11015. ASSERT_EQ(2u, req.form.files.size());
  11016. ASSERT_EQ(1u, req.form.fields.size());
  11017. // Test files
  11018. const auto &file1 = req.form.get_file("file1");
  11019. ASSERT_EQ("file1", file1.name);
  11020. ASSERT_EQ("A.txt", file1.filename);
  11021. ASSERT_EQ("text/plain", file1.content_type);
  11022. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11023. const auto &file2 = req.form.get_file("file2");
  11024. ASSERT_EQ("file2", file2.name);
  11025. ASSERT_EQ("a.html", file2.filename);
  11026. ASSERT_EQ("text/html", file2.content_type);
  11027. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11028. file2.content);
  11029. // Test text field
  11030. const auto &text = req.form.get_field("text");
  11031. ASSERT_EQ("text default", text);
  11032. res.set_content("ok", "text/plain");
  11033. handled = true;
  11034. });
  11035. thread t = thread([&] { svr.listen(HOST, PORT); });
  11036. auto se = detail::scope_exit([&] {
  11037. svr.stop();
  11038. t.join();
  11039. ASSERT_FALSE(svr.is_running());
  11040. ASSERT_TRUE(handled);
  11041. });
  11042. svr.wait_until_ready();
  11043. auto req = "POST /test HTTP/1.1\r\n"
  11044. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11045. "Content-Length: 399\r\n"
  11046. "\r\n"
  11047. "----------\r\n"
  11048. "Content-Disposition: form-data; name=\"text\"\r\n"
  11049. "\r\n"
  11050. "text default\r\n"
  11051. "----------\r\n"
  11052. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11053. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11054. "Content-Type: text/plain\r\n"
  11055. "\r\n"
  11056. "Content of a.txt.\r\n"
  11057. "\r\n"
  11058. "----------\r\n"
  11059. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11060. "\"a.html\"\r\n"
  11061. "Content-Type: text/html\r\n"
  11062. "\r\n"
  11063. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11064. "\r\n"
  11065. "------------\r\n";
  11066. ASSERT_TRUE(send_request(1, req));
  11067. }
  11068. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11069. auto handled = false;
  11070. Server svr;
  11071. svr.Post("/test", [&](const Request &req, Response &res) {
  11072. // Case-insensitive "utf-8''" prefix with a long value
  11073. const auto &file = req.form.get_file("file1");
  11074. ASSERT_EQ("file1", file.name);
  11075. // 8000 chars exercises both the Content-Disposition parser and the
  11076. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11077. // Prior to the fix, std::regex_match on this header would cause O(N)
  11078. // stack recursion in libstdc++, leading to SIGSEGV.
  11079. std::string expected_filename(8000, 'A');
  11080. ASSERT_EQ(expected_filename, file.filename);
  11081. res.set_content("ok", "text/plain");
  11082. handled = true;
  11083. });
  11084. thread t = thread([&] { svr.listen(HOST, PORT); });
  11085. auto se = detail::scope_exit([&] {
  11086. svr.stop();
  11087. t.join();
  11088. ASSERT_FALSE(svr.is_running());
  11089. ASSERT_TRUE(handled);
  11090. });
  11091. svr.wait_until_ready();
  11092. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11093. // Regression test for GHSA-qq6v-r583-3h69
  11094. std::string long_filename(8000, 'A');
  11095. std::string body = "----------\r\n"
  11096. "Content-Disposition: form-data; name=\"file1\"; "
  11097. "filename*=\"Utf-8''" +
  11098. long_filename +
  11099. "\"\r\n"
  11100. "\r\n"
  11101. "hello\r\n"
  11102. "------------\r\n";
  11103. auto req = "POST /test HTTP/1.1\r\n"
  11104. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11105. "Content-Length: " +
  11106. std::to_string(body.size()) + "\r\n\r\n" + body;
  11107. ASSERT_TRUE(send_request(1, req));
  11108. }
  11109. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11110. auto handled = false;
  11111. Server svr;
  11112. svr.Post("/test", [&](const Request &req, Response &) {
  11113. ASSERT_EQ(2u, req.form.fields.size());
  11114. const auto &text1 = req.form.get_field("text1");
  11115. ASSERT_EQ("text1", text1);
  11116. const auto &text2 = req.form.get_field("text2");
  11117. ASSERT_EQ("text2", text2);
  11118. handled = true;
  11119. });
  11120. thread t = thread([&] { svr.listen(HOST, PORT); });
  11121. auto se = detail::scope_exit([&] {
  11122. svr.stop();
  11123. t.join();
  11124. ASSERT_FALSE(svr.is_running());
  11125. ASSERT_TRUE(handled);
  11126. });
  11127. svr.wait_until_ready();
  11128. auto req = "POST /test HTTP/1.1\r\n"
  11129. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11130. "Content-Length: 146\r\n"
  11131. "\r\n----------\r\n"
  11132. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11133. "\r\n"
  11134. "text1"
  11135. "\r\n----------\r\n"
  11136. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11137. "\r\n"
  11138. "text2"
  11139. "\r\n------------";
  11140. std::string response;
  11141. ASSERT_TRUE(send_request(1, req, &response));
  11142. ASSERT_EQ("200", response.substr(9, 3));
  11143. }
  11144. TEST(MultipartFormDataTest, ContentLength) {
  11145. auto handled = false;
  11146. Server svr;
  11147. svr.Post("/test", [&](const Request &req, Response &) {
  11148. ASSERT_EQ(2u, req.form.fields.size());
  11149. const auto &text1 = req.form.get_field("text1");
  11150. ASSERT_EQ("text1", text1);
  11151. const auto &text2 = req.form.get_field("text2");
  11152. ASSERT_EQ("text2", text2);
  11153. handled = true;
  11154. });
  11155. thread t = thread([&] { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. ASSERT_TRUE(handled);
  11161. });
  11162. svr.wait_until_ready();
  11163. auto req = "POST /test HTTP/1.1\r\n"
  11164. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11165. "Content-Length: 167\r\n"
  11166. "\r\n----------\r\n"
  11167. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11168. "Content-Length: 5\r\n"
  11169. "\r\n"
  11170. "text1"
  11171. "\r\n----------\r\n"
  11172. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11173. "\r\n"
  11174. "text2"
  11175. "\r\n------------\r\n";
  11176. std::string response;
  11177. ASSERT_TRUE(send_request(1, req, &response));
  11178. ASSERT_EQ("200", response.substr(9, 3));
  11179. }
  11180. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11181. auto handled = false;
  11182. Server svr;
  11183. svr.Post("/test", [&](const Request &req, Response &) {
  11184. ASSERT_EQ(2u, req.form.fields.size());
  11185. const auto &text1 = req.form.get_field("text1");
  11186. ASSERT_EQ("text1", text1);
  11187. // TODO: Add header access for text fields if needed
  11188. const auto &text2 = req.form.get_field("text2");
  11189. ASSERT_EQ("text2", text2);
  11190. // TODO: Header access for text fields needs to be implemented
  11191. // auto &headers = it->second.headers;
  11192. // ASSERT_EQ(3U, headers.size());
  11193. // auto custom_header = headers.find("x-whatever");
  11194. // ASSERT_TRUE(custom_header != headers.end());
  11195. // ASSERT_NE("customvalue", custom_header->second);
  11196. // ASSERT_EQ("CustomValue", custom_header->second);
  11197. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11198. handled = true;
  11199. });
  11200. thread t = thread([&] { svr.listen(HOST, PORT); });
  11201. auto se = detail::scope_exit([&] {
  11202. svr.stop();
  11203. t.join();
  11204. ASSERT_FALSE(svr.is_running());
  11205. ASSERT_TRUE(handled);
  11206. });
  11207. svr.wait_until_ready();
  11208. auto req = "POST /test HTTP/1.1\r\n"
  11209. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11210. "Content-Length: 232\r\n"
  11211. "\r\n----------\r\n"
  11212. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11213. "Content-Length: 5\r\n"
  11214. "X-Test: 1\r\n"
  11215. "\r\n"
  11216. "text1"
  11217. "\r\n----------\r\n"
  11218. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11219. "Content-Type: text/plain\r\n"
  11220. "X-Whatever: CustomValue\r\n"
  11221. "\r\n"
  11222. "text2"
  11223. "\r\n------------\r\n"
  11224. "That should be disregarded. Not even read";
  11225. std::string response;
  11226. ASSERT_TRUE(send_request(1, req, &response));
  11227. ASSERT_EQ("200", response.substr(9, 3));
  11228. }
  11229. TEST(MultipartFormDataTest, LargeHeader) {
  11230. auto handled = false;
  11231. Server svr;
  11232. svr.Post("/test", [&](const Request &req, Response &) {
  11233. ASSERT_EQ(1u, req.form.fields.size());
  11234. const auto &text = req.form.get_field("name1");
  11235. ASSERT_EQ("text1", text);
  11236. handled = true;
  11237. });
  11238. thread t = thread([&] { svr.listen(HOST, PORT); });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. t.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. ASSERT_TRUE(handled);
  11244. });
  11245. svr.wait_until_ready();
  11246. auto boundary = std::string("cpp-httplib-multipart-data");
  11247. std::string content = "--" + boundary +
  11248. "\r\n"
  11249. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11250. "\r\n"
  11251. "text1\r\n"
  11252. "--" +
  11253. boundary + "--\r\n";
  11254. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11255. "Content-Type: multipart/form-data;boundary=" +
  11256. boundary +
  11257. "\r\n"
  11258. "Content-Length: " +
  11259. std::to_string(content.size()) +
  11260. "\r\n"
  11261. "Dummy-Header: ";
  11262. std::string header_suffix = "\r\n"
  11263. "\r\n";
  11264. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11265. size_t header_dummy_size =
  11266. read_buff_size -
  11267. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11268. auto header_dummy = std::string(header_dummy_size, '@');
  11269. auto req = header_prefix + header_dummy + header_suffix + content;
  11270. std::string response;
  11271. ASSERT_TRUE(send_request(1, req, &response));
  11272. ASSERT_EQ("200", response.substr(9, 3));
  11273. }
  11274. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11275. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11276. // (not chunked Transfer-Encoding) after the streaming refactor.
  11277. auto handled = false;
  11278. Server svr;
  11279. svr.Post("/upload", [&](const Request &req, Response &res) {
  11280. auto cl_it = req.headers.find("Content-Length");
  11281. EXPECT_TRUE(cl_it != req.headers.end());
  11282. auto te_it = req.headers.find("Transfer-Encoding");
  11283. EXPECT_TRUE(te_it == req.headers.end());
  11284. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11285. res.set_content("ok", "text/plain");
  11286. handled = true;
  11287. });
  11288. auto port = svr.bind_to_any_port(HOST);
  11289. auto t = thread([&] { svr.listen_after_bind(); });
  11290. auto se = detail::scope_exit([&] {
  11291. svr.stop();
  11292. t.join();
  11293. ASSERT_FALSE(svr.is_running());
  11294. ASSERT_TRUE(handled);
  11295. });
  11296. svr.wait_until_ready();
  11297. UploadFormDataItems items = {
  11298. {"field1", "hello", "", "text/plain"},
  11299. {"file1", "world", "test.txt", "application/octet-stream"},
  11300. };
  11301. Client cli(HOST, port);
  11302. auto res = cli.Post("/upload", {}, items);
  11303. ASSERT_TRUE(res);
  11304. EXPECT_EQ(StatusCode::OK_200, res->status);
  11305. }
  11306. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11307. // Verify that make_multipart_content_provider coalesces many small segments
  11308. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11309. constexpr size_t kItemCount = 1000;
  11310. UploadFormDataItems items;
  11311. items.reserve(kItemCount);
  11312. for (size_t i = 0; i < kItemCount; i++) {
  11313. items.push_back(
  11314. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11315. }
  11316. const std::string boundary = "----test-boundary";
  11317. auto content_length = detail::get_multipart_content_length(items, boundary);
  11318. auto provider = detail::make_multipart_content_provider(items, boundary);
  11319. // Drive the provider the same way write_content_with_progress does
  11320. size_t write_count = 0;
  11321. size_t total_bytes = 0;
  11322. DataSink sink;
  11323. size_t offset = 0;
  11324. sink.write = [&](const char *d, size_t l) -> bool {
  11325. (void)d;
  11326. write_count++;
  11327. total_bytes += l;
  11328. offset += l;
  11329. return true;
  11330. };
  11331. sink.is_writable = []() -> bool { return true; };
  11332. while (offset < content_length) {
  11333. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11334. }
  11335. EXPECT_EQ(content_length, total_bytes);
  11336. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11337. // With buffering into 64KB blocks, write_count should be much smaller.
  11338. auto segment_count = 3 * kItemCount + 1;
  11339. EXPECT_LT(write_count, segment_count / 10);
  11340. }
  11341. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11342. // Integration test: send many UploadFormDataItems and verify the server
  11343. // receives all of them correctly (#2410).
  11344. constexpr size_t kItemCount = 500;
  11345. auto handled = false;
  11346. Server svr;
  11347. svr.Post("/upload", [&](const Request &req, Response &res) {
  11348. EXPECT_EQ(kItemCount, req.form.fields.size());
  11349. for (size_t i = 0; i < kItemCount; i++) {
  11350. auto key = "field" + std::to_string(i);
  11351. auto val = "value" + std::to_string(i);
  11352. auto it = req.form.fields.find(key);
  11353. if (it != req.form.fields.end()) {
  11354. EXPECT_EQ(val, it->second.content);
  11355. } else {
  11356. ADD_FAILURE() << "Missing field: " << key;
  11357. }
  11358. }
  11359. res.set_content("ok", "text/plain");
  11360. handled = true;
  11361. });
  11362. auto port = svr.bind_to_any_port(HOST);
  11363. auto t = thread([&] { svr.listen_after_bind(); });
  11364. auto se = detail::scope_exit([&] {
  11365. svr.stop();
  11366. t.join();
  11367. ASSERT_FALSE(svr.is_running());
  11368. ASSERT_TRUE(handled);
  11369. });
  11370. svr.wait_until_ready();
  11371. UploadFormDataItems items;
  11372. items.reserve(kItemCount);
  11373. for (size_t i = 0; i < kItemCount; i++) {
  11374. items.push_back(
  11375. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11376. }
  11377. Client cli(HOST, port);
  11378. auto res = cli.Post("/upload", items);
  11379. ASSERT_TRUE(res);
  11380. EXPECT_EQ(StatusCode::OK_200, res->status);
  11381. }
  11382. TEST(MultipartFormDataTest, MakeFileProvider) {
  11383. // Verify make_file_provider sends a file's contents correctly.
  11384. const std::string file_content(4096, 'Z');
  11385. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11386. {
  11387. std::ofstream ofs(tmp_path, std::ios::binary);
  11388. ofs.write(file_content.data(),
  11389. static_cast<std::streamsize>(file_content.size()));
  11390. }
  11391. auto handled = false;
  11392. Server svr;
  11393. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11394. const ContentReader &content_reader) {
  11395. ASSERT_TRUE(req.is_multipart_form_data());
  11396. std::vector<FormData> items;
  11397. content_reader(
  11398. [&](const FormData &file) {
  11399. items.push_back(file);
  11400. return true;
  11401. },
  11402. [&](const char *data, size_t data_length) {
  11403. items.back().content.append(data, data_length);
  11404. return true;
  11405. });
  11406. ASSERT_EQ(1u, items.size());
  11407. EXPECT_EQ("myfile", items[0].name);
  11408. EXPECT_EQ("data.bin", items[0].filename);
  11409. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11410. EXPECT_EQ(file_content, items[0].content);
  11411. handled = true;
  11412. });
  11413. auto port = svr.bind_to_any_port(HOST);
  11414. auto t = thread([&] { svr.listen_after_bind(); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. ASSERT_TRUE(handled);
  11420. std::remove(tmp_path.c_str());
  11421. });
  11422. svr.wait_until_ready();
  11423. FormDataProviderItems providers;
  11424. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11425. "application/octet-stream"));
  11426. Client cli(HOST, port);
  11427. auto res = cli.Post("/upload", {}, {}, providers);
  11428. ASSERT_TRUE(res);
  11429. EXPECT_EQ(StatusCode::OK_200, res->status);
  11430. }
  11431. TEST(MakeFileBodyTest, Basic) {
  11432. const std::string file_content(4096, 'Z');
  11433. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11434. {
  11435. std::ofstream ofs(tmp_path, std::ios::binary);
  11436. ofs.write(file_content.data(),
  11437. static_cast<std::streamsize>(file_content.size()));
  11438. }
  11439. auto handled = false;
  11440. Server svr;
  11441. svr.Post("/upload", [&](const Request &req, Response &res) {
  11442. EXPECT_EQ(file_content, req.body);
  11443. handled = true;
  11444. res.status = StatusCode::OK_200;
  11445. });
  11446. auto port = svr.bind_to_any_port(HOST);
  11447. auto t = thread([&] { svr.listen_after_bind(); });
  11448. auto se = detail::scope_exit([&] {
  11449. svr.stop();
  11450. t.join();
  11451. ASSERT_FALSE(svr.is_running());
  11452. ASSERT_TRUE(handled);
  11453. std::remove(tmp_path.c_str());
  11454. });
  11455. svr.wait_until_ready();
  11456. auto fb = make_file_body(tmp_path);
  11457. ASSERT_GT(fb.first, 0u);
  11458. Client cli(HOST, port);
  11459. auto res =
  11460. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11461. ASSERT_TRUE(res);
  11462. EXPECT_EQ(StatusCode::OK_200, res->status);
  11463. }
  11464. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11465. static constexpr unsigned int number_of_tasks{1000000};
  11466. std::atomic_uint count{0};
  11467. std::unique_ptr<TaskQueue> task_queue{
  11468. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11469. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11470. auto queued = task_queue->enqueue(
  11471. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11472. EXPECT_TRUE(queued);
  11473. }
  11474. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11475. task_queue->shutdown();
  11476. #else
  11477. EXPECT_NO_THROW(task_queue->shutdown());
  11478. #endif
  11479. EXPECT_EQ(number_of_tasks, count.load());
  11480. }
  11481. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11482. static constexpr unsigned int number_of_tasks{1000000};
  11483. static constexpr unsigned int qlimit{2};
  11484. unsigned int queued_count{0};
  11485. std::atomic_uint count{0};
  11486. std::unique_ptr<TaskQueue> task_queue{
  11487. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11488. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11489. if (task_queue->enqueue(
  11490. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11491. queued_count++;
  11492. }
  11493. }
  11494. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11495. task_queue->shutdown();
  11496. #else
  11497. EXPECT_NO_THROW(task_queue->shutdown());
  11498. #endif
  11499. EXPECT_EQ(queued_count, count.load());
  11500. EXPECT_TRUE(queued_count <= number_of_tasks);
  11501. EXPECT_TRUE(queued_count >= qlimit);
  11502. }
  11503. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11504. // Use a short idle timeout so a dynamic thread spawns, times out and
  11505. // exits during the test, and the pool keeps working afterwards.
  11506. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11507. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11508. /*idle_timeout_sec=*/1}};
  11509. std::atomic_uint count{0};
  11510. std::condition_variable cv;
  11511. std::mutex mtx;
  11512. bool release = false;
  11513. // Block the base thread so the second task spawns a dynamic thread.
  11514. EXPECT_TRUE(task_queue->enqueue([&] {
  11515. std::unique_lock<std::mutex> lock(mtx);
  11516. while (!release) {
  11517. cv.wait(lock);
  11518. }
  11519. count++;
  11520. }));
  11521. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11522. // Let the dynamic thread finish its task and exceed the idle timeout.
  11523. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11524. {
  11525. std::unique_lock<std::mutex> lock(mtx);
  11526. release = true;
  11527. }
  11528. cv.notify_all();
  11529. // The pool must still accept and run tasks after the dynamic thread exited.
  11530. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11531. task_queue->shutdown();
  11532. EXPECT_EQ(3u, count.load());
  11533. }
  11534. TEST(TaskQueueTest, MaxQueuedRequests) {
  11535. static constexpr unsigned int qlimit{3};
  11536. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11537. std::condition_variable sem_cv;
  11538. std::mutex sem_mtx;
  11539. int credits = 0;
  11540. bool queued;
  11541. /* Fill up the queue with tasks that will block until we give them credits to
  11542. * complete. */
  11543. for (unsigned int n = 0; n <= qlimit;) {
  11544. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11545. std::unique_lock<std::mutex> lock(sem_mtx);
  11546. while (credits <= 0) {
  11547. sem_cv.wait(lock);
  11548. }
  11549. /* Consume the credit and signal the test code if they are all gone. */
  11550. if (--credits == 0) { sem_cv.notify_one(); }
  11551. });
  11552. if (n < qlimit) {
  11553. /* The first qlimit enqueues must succeed. */
  11554. EXPECT_TRUE(queued);
  11555. } else {
  11556. /* The last one will succeed only when the worker thread
  11557. * starts and dequeues the first blocking task. Although
  11558. * not necessary for the correctness of this test, we sleep for
  11559. * a short while to avoid busy waiting. */
  11560. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11561. }
  11562. if (queued) { n++; }
  11563. }
  11564. /* Further enqueues must fail since the queue is full. */
  11565. for (auto i = 0; i < 4; i++) {
  11566. queued = task_queue->enqueue([] {});
  11567. EXPECT_FALSE(queued);
  11568. }
  11569. /* Give the credits to allow the previous tasks to complete. */
  11570. {
  11571. std::unique_lock<std::mutex> lock(sem_mtx);
  11572. credits += qlimit + 1;
  11573. }
  11574. sem_cv.notify_all();
  11575. /* Wait for all the credits to be consumed. */
  11576. {
  11577. std::unique_lock<std::mutex> lock(sem_mtx);
  11578. while (credits > 0) {
  11579. sem_cv.wait(lock);
  11580. }
  11581. }
  11582. /* Check that we are able again to enqueue at least qlimit tasks. */
  11583. for (unsigned int i = 0; i < qlimit; i++) {
  11584. queued = task_queue->enqueue([] {});
  11585. EXPECT_TRUE(queued);
  11586. }
  11587. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11588. task_queue->shutdown();
  11589. #else
  11590. EXPECT_NO_THROW(task_queue->shutdown());
  11591. #endif
  11592. }
  11593. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11594. Server svr;
  11595. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11596. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11597. });
  11598. svr.Get("/hello", [](const Request &req, Response &res) {
  11599. res.set_content(req.get_param_value("key"), "text/plain");
  11600. });
  11601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11602. auto se = detail::scope_exit([&] {
  11603. svr.stop();
  11604. thread.join();
  11605. ASSERT_FALSE(svr.is_running());
  11606. });
  11607. svr.wait_until_ready();
  11608. {
  11609. Client cli(HOST, PORT);
  11610. cli.set_follow_location(true);
  11611. auto res = cli.Get("/");
  11612. ASSERT_TRUE(res);
  11613. EXPECT_EQ(StatusCode::OK_200, res->status);
  11614. EXPECT_EQ("val&key2=val2", res->body);
  11615. }
  11616. }
  11617. #endif
  11618. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11619. Server svr;
  11620. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11621. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11622. });
  11623. svr.Get("/hello", [](const Request &req, Response &res) {
  11624. res.set_content(req.get_param_value("key"), "text/plain");
  11625. });
  11626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11627. auto se = detail::scope_exit([&] {
  11628. svr.stop();
  11629. thread.join();
  11630. ASSERT_FALSE(svr.is_running());
  11631. });
  11632. svr.wait_until_ready();
  11633. {
  11634. Client cli(HOST, PORT);
  11635. cli.set_follow_location(true);
  11636. auto res = cli.Get("/");
  11637. ASSERT_TRUE(res);
  11638. EXPECT_EQ(StatusCode::OK_200, res->status);
  11639. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11640. }
  11641. }
  11642. TEST(RedirectTest, RedirectWithPlusInPath) {
  11643. Server svr;
  11644. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11645. res.set_redirect("/a+b");
  11646. });
  11647. // Route pattern uses regex; escape + as \\+
  11648. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11649. res.set_content(req.path, "text/plain");
  11650. });
  11651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11652. auto se = detail::scope_exit([&] {
  11653. svr.stop();
  11654. thread.join();
  11655. ASSERT_FALSE(svr.is_running());
  11656. });
  11657. svr.wait_until_ready();
  11658. {
  11659. Client cli(HOST, PORT);
  11660. cli.set_follow_location(true);
  11661. auto res = cli.Get("/");
  11662. ASSERT_TRUE(res);
  11663. EXPECT_EQ(StatusCode::OK_200, res->status);
  11664. EXPECT_EQ("/a+b", res->body);
  11665. }
  11666. }
  11667. #ifdef CPPHTTPLIB_SSL_ENABLED
  11668. TEST(RedirectTest, Issue2185_Online) {
  11669. SSLClient client("github.com");
  11670. client.set_follow_location(true);
  11671. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11672. "Coollab-Windows.zip");
  11673. ASSERT_TRUE(res);
  11674. EXPECT_EQ(StatusCode::OK_200, res->status);
  11675. EXPECT_EQ(9920427U, res->body.size());
  11676. }
  11677. #endif
  11678. TEST(VulnerabilityTest, CRLFInjection) {
  11679. Server svr;
  11680. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11681. res.set_content("Hello 1", "text/plain");
  11682. });
  11683. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11684. res.set_content("Hello 2", "text/plain");
  11685. });
  11686. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11687. res.set_content("Hello 3", "text/plain");
  11688. });
  11689. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11690. res.set_content("Hello 4", "text/plain");
  11691. });
  11692. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11693. for (const auto &x : req.headers) {
  11694. auto key = x.first;
  11695. EXPECT_STRNE("evil", key.c_str());
  11696. }
  11697. });
  11698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11699. auto se = detail::scope_exit([&] {
  11700. svr.stop();
  11701. thread.join();
  11702. ASSERT_FALSE(svr.is_running());
  11703. });
  11704. svr.wait_until_ready();
  11705. {
  11706. Client cli(HOST, PORT);
  11707. cli.Post("/test1", "A=B",
  11708. "application/x-www-form-urlencoded\r\nevil: hello1");
  11709. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11710. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11711. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11712. }
  11713. }
  11714. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11715. auto server_thread = std::thread([] {
  11716. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11717. default_socket_options(srv);
  11718. sockaddr_in addr{};
  11719. addr.sin_family = AF_INET;
  11720. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11721. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11722. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11723. ::listen(srv, 1);
  11724. sockaddr_in cli_addr{};
  11725. socklen_t cli_len = sizeof(cli_addr);
  11726. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11727. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11728. std::string buf_all;
  11729. char buf[2048];
  11730. ssize_t n;
  11731. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11732. buf_all.append(buf, static_cast<size_t>(n));
  11733. size_t pos;
  11734. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11735. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11736. auto e = request_block.find("\r\n");
  11737. if (e != std::string::npos) {
  11738. auto request_line = request_block.substr(0, e);
  11739. std::string msg =
  11740. "CRLF injection detected in request line: '" + request_line + "'";
  11741. EXPECT_FALSE(true) << msg;
  11742. }
  11743. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11744. ::send(cli,
  11745. #ifdef _WIN32
  11746. static_cast<const char *>(resp.c_str()),
  11747. static_cast<int>(resp.size()),
  11748. #else
  11749. resp.c_str(), resp.size(),
  11750. #endif
  11751. 0);
  11752. buf_all.erase(0, pos + 4);
  11753. }
  11754. }
  11755. detail::close_socket(cli);
  11756. detail::close_socket(srv);
  11757. });
  11758. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11759. auto cli = Client("127.0.0.1", PORT + 1);
  11760. auto headers = Headers{
  11761. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11762. {"Connection", "keep-alive"}};
  11763. auto res = cli.Get("/hi", headers);
  11764. EXPECT_FALSE(res);
  11765. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11766. server_thread.join();
  11767. }
  11768. TEST(PathParamsTest, StaticMatch) {
  11769. const auto pattern = "/users/all";
  11770. detail::PathParamsMatcher matcher(pattern);
  11771. Request request;
  11772. request.path = "/users/all";
  11773. ASSERT_TRUE(matcher.match(request));
  11774. std::unordered_map<std::string, std::string> expected_params = {};
  11775. EXPECT_EQ(request.path_params, expected_params);
  11776. }
  11777. TEST(PathParamsTest, StaticMismatch) {
  11778. const auto pattern = "/users/all";
  11779. detail::PathParamsMatcher matcher(pattern);
  11780. Request request;
  11781. request.path = "/users/1";
  11782. ASSERT_FALSE(matcher.match(request));
  11783. }
  11784. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11785. const auto pattern = "/users/:id/subscriptions";
  11786. detail::PathParamsMatcher matcher(pattern);
  11787. Request request;
  11788. request.path = "/users/42/subscriptions";
  11789. ASSERT_TRUE(matcher.match(request));
  11790. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11791. EXPECT_EQ(request.path_params, expected_params);
  11792. }
  11793. TEST(PathParamsTest, SingleParamInTheEnd) {
  11794. const auto pattern = "/users/:id";
  11795. detail::PathParamsMatcher matcher(pattern);
  11796. Request request;
  11797. request.path = "/users/24";
  11798. ASSERT_TRUE(matcher.match(request));
  11799. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11800. EXPECT_EQ(request.path_params, expected_params);
  11801. }
  11802. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11803. const auto pattern = "/users/:id/";
  11804. detail::PathParamsMatcher matcher(pattern);
  11805. Request request;
  11806. request.path = "/users/42/";
  11807. ASSERT_TRUE(matcher.match(request));
  11808. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11809. EXPECT_EQ(request.path_params, expected_params);
  11810. }
  11811. TEST(PathParamsTest, EmptyParam) {
  11812. const auto pattern = "/users/:id/";
  11813. detail::PathParamsMatcher matcher(pattern);
  11814. Request request;
  11815. request.path = "/users//";
  11816. ASSERT_TRUE(matcher.match(request));
  11817. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11818. EXPECT_EQ(request.path_params, expected_params);
  11819. }
  11820. TEST(PathParamsTest, FragmentMismatch) {
  11821. const auto pattern = "/users/:id/";
  11822. detail::PathParamsMatcher matcher(pattern);
  11823. Request request;
  11824. request.path = "/admins/24/";
  11825. ASSERT_FALSE(matcher.match(request));
  11826. }
  11827. TEST(PathParamsTest, ExtraFragments) {
  11828. const auto pattern = "/users/:id";
  11829. detail::PathParamsMatcher matcher(pattern);
  11830. Request request;
  11831. request.path = "/users/42/subscriptions";
  11832. ASSERT_FALSE(matcher.match(request));
  11833. }
  11834. TEST(PathParamsTest, MissingTrailingParam) {
  11835. const auto pattern = "/users/:id";
  11836. detail::PathParamsMatcher matcher(pattern);
  11837. Request request;
  11838. request.path = "/users";
  11839. ASSERT_FALSE(matcher.match(request));
  11840. }
  11841. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11842. const auto pattern = "/users/:id/subscriptions";
  11843. detail::PathParamsMatcher matcher(pattern);
  11844. Request request;
  11845. request.path = "/users/subscriptions";
  11846. ASSERT_FALSE(matcher.match(request));
  11847. }
  11848. TEST(PathParamsTest, MultipleParams) {
  11849. const auto pattern = "/users/:userid/subscriptions/:subid";
  11850. detail::PathParamsMatcher matcher(pattern);
  11851. Request request;
  11852. request.path = "/users/42/subscriptions/2";
  11853. ASSERT_TRUE(matcher.match(request));
  11854. std::unordered_map<std::string, std::string> expected_params = {
  11855. {"userid", "42"}, {"subid", "2"}};
  11856. EXPECT_EQ(request.path_params, expected_params);
  11857. }
  11858. TEST(PathParamsTest, SequenceOfParams) {
  11859. const auto pattern = "/values/:x/:y/:z";
  11860. detail::PathParamsMatcher matcher(pattern);
  11861. Request request;
  11862. request.path = "/values/1/2/3";
  11863. ASSERT_TRUE(matcher.match(request));
  11864. std::unordered_map<std::string, std::string> expected_params = {
  11865. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11866. EXPECT_EQ(request.path_params, expected_params);
  11867. }
  11868. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11869. const auto pattern = "/prefix:suffix";
  11870. detail::PathParamsMatcher matcher(pattern);
  11871. Request request;
  11872. request.path = "/prefix:suffix";
  11873. ASSERT_TRUE(matcher.match(request));
  11874. const std::unordered_map<std::string, std::string> expected_params = {};
  11875. EXPECT_EQ(request.path_params, expected_params);
  11876. }
  11877. TEST(ParseUrlTest, VariousPatterns) {
  11878. {
  11879. detail::UrlComponents uc;
  11880. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11881. EXPECT_EQ("http", uc.scheme);
  11882. EXPECT_EQ("example.com", uc.host);
  11883. EXPECT_EQ("8080", uc.port);
  11884. EXPECT_EQ("/path", uc.path);
  11885. EXPECT_EQ("?q=1", uc.query);
  11886. }
  11887. {
  11888. detail::UrlComponents uc;
  11889. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11890. EXPECT_EQ("https", uc.scheme);
  11891. EXPECT_EQ("example.com", uc.host);
  11892. EXPECT_TRUE(uc.port.empty());
  11893. EXPECT_EQ("/path", uc.path);
  11894. }
  11895. {
  11896. detail::UrlComponents uc;
  11897. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11898. EXPECT_EQ("::1", uc.host);
  11899. EXPECT_EQ("8080", uc.port);
  11900. EXPECT_EQ("/path", uc.path);
  11901. }
  11902. {
  11903. detail::UrlComponents uc;
  11904. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11905. }
  11906. {
  11907. detail::UrlComponents uc;
  11908. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11909. EXPECT_TRUE(uc.scheme.empty());
  11910. EXPECT_EQ("example.com", uc.host);
  11911. EXPECT_EQ("/path", uc.path);
  11912. EXPECT_EQ("?q=1", uc.query);
  11913. }
  11914. {
  11915. detail::UrlComponents uc;
  11916. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11917. EXPECT_TRUE(uc.host.empty());
  11918. EXPECT_EQ("/path", uc.path);
  11919. EXPECT_EQ("?q=1", uc.query);
  11920. }
  11921. {
  11922. detail::UrlComponents uc;
  11923. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11924. EXPECT_EQ("example.com", uc.host);
  11925. EXPECT_EQ("8080", uc.port);
  11926. }
  11927. {
  11928. // Unix socket path — must not be parsed as host
  11929. detail::UrlComponents uc;
  11930. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11931. EXPECT_TRUE(uc.host.empty());
  11932. }
  11933. {
  11934. detail::UrlComponents uc;
  11935. ASSERT_TRUE(detail::parse_url("", uc));
  11936. EXPECT_TRUE(uc.host.empty());
  11937. EXPECT_TRUE(uc.path.empty());
  11938. }
  11939. {
  11940. detail::UrlComponents uc;
  11941. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11942. }
  11943. {
  11944. detail::UrlComponents uc;
  11945. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11946. }
  11947. {
  11948. // Accepted by parse_url; callers restrict to http/https
  11949. detail::UrlComponents uc;
  11950. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11951. EXPECT_EQ("ftp", uc.scheme);
  11952. }
  11953. {
  11954. detail::UrlComponents uc;
  11955. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11956. }
  11957. {
  11958. detail::UrlComponents uc;
  11959. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11960. }
  11961. }
  11962. TEST(ParseUrlTest, FragmentHandling) {
  11963. {
  11964. detail::UrlComponents uc;
  11965. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11966. EXPECT_EQ("/path", uc.path);
  11967. EXPECT_TRUE(uc.query.empty());
  11968. }
  11969. {
  11970. detail::UrlComponents uc;
  11971. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11972. EXPECT_TRUE(uc.path.empty());
  11973. EXPECT_TRUE(uc.query.empty());
  11974. }
  11975. }
  11976. TEST(ParseUrlTest, UserinfoHandling) {
  11977. // Userinfo with @ but no colon — host includes @
  11978. detail::UrlComponents uc;
  11979. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11980. EXPECT_EQ("user@host.com", uc.host);
  11981. EXPECT_EQ("/path", uc.path);
  11982. }
  11983. TEST(ParseUrlTest, IPv6EdgeCases) {
  11984. {
  11985. detail::UrlComponents uc;
  11986. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11987. EXPECT_TRUE(uc.scheme.empty());
  11988. EXPECT_EQ("::1", uc.host);
  11989. EXPECT_EQ("8080", uc.port);
  11990. }
  11991. {
  11992. // Zone ID '%25' is not in [a-fA-F0-9:]
  11993. detail::UrlComponents uc;
  11994. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11995. }
  11996. }
  11997. TEST(ParseUrlTest, SchemeEdgeCases) {
  11998. {
  11999. detail::UrlComponents uc;
  12000. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12001. }
  12002. {
  12003. detail::UrlComponents uc;
  12004. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12005. }
  12006. {
  12007. detail::UrlComponents uc;
  12008. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12009. }
  12010. }
  12011. TEST(ParseUrlTest, PortEdgeCases) {
  12012. {
  12013. detail::UrlComponents uc;
  12014. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12015. EXPECT_TRUE(uc.port.empty());
  12016. EXPECT_EQ("/path", uc.path);
  12017. }
  12018. {
  12019. // parse_url accepts any port string; validation is done by parse_port
  12020. detail::UrlComponents uc;
  12021. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12022. EXPECT_EQ("abc", uc.port);
  12023. }
  12024. }
  12025. TEST(ParseUrlTest, WebSocketPatterns) {
  12026. {
  12027. detail::UrlComponents uc;
  12028. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12029. EXPECT_EQ("ws", uc.scheme);
  12030. EXPECT_EQ("echo.example.com", uc.host);
  12031. EXPECT_EQ("8080", uc.port);
  12032. EXPECT_EQ("/ws", uc.path);
  12033. }
  12034. {
  12035. detail::UrlComponents uc;
  12036. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12037. EXPECT_EQ("wss", uc.scheme);
  12038. EXPECT_EQ("echo.example.com", uc.host);
  12039. EXPECT_TRUE(uc.port.empty());
  12040. EXPECT_EQ("/ws", uc.path);
  12041. }
  12042. }
  12043. TEST(ParseUrlTest, QueryOnly) {
  12044. detail::UrlComponents uc;
  12045. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12046. EXPECT_TRUE(uc.host.empty());
  12047. EXPECT_TRUE(uc.path.empty());
  12048. EXPECT_EQ("?q=1&r=2", uc.query);
  12049. }
  12050. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12051. detail::UrlComponents uc;
  12052. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12053. EXPECT_TRUE(uc.scheme.empty());
  12054. EXPECT_EQ("example.com", uc.host);
  12055. EXPECT_EQ("443", uc.port);
  12056. EXPECT_EQ("/path", uc.path);
  12057. }
  12058. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12059. // If ipv6 regex working, regex match codepath is taken.
  12060. // else port will default to 80 in Client impl
  12061. int clientImplMagicPort = 80;
  12062. int port = 4321;
  12063. // above ports must be different to avoid false negative
  12064. EXPECT_NE(clientImplMagicPort, port);
  12065. std::string ipV6TestURL = "http://[ff06::c3]";
  12066. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12067. CLIENT_PRIVATE_KEY_FILE);
  12068. EXPECT_EQ(cli.port(), port);
  12069. }
  12070. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12071. auto file_path = "./www/dir/index.html";
  12072. auto dir_path = "./www/dir";
  12073. detail::FileStat stat_file(file_path);
  12074. EXPECT_TRUE(stat_file.is_file());
  12075. EXPECT_FALSE(stat_file.is_dir());
  12076. detail::FileStat stat_dir(dir_path);
  12077. EXPECT_FALSE(stat_dir.is_file());
  12078. EXPECT_TRUE(stat_dir.is_dir());
  12079. }
  12080. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12081. // IPv4 with default HTTP port (80)
  12082. EXPECT_EQ("example.com",
  12083. detail::make_host_and_port_string("example.com", 80, false));
  12084. // IPv4 with default HTTPS port (443)
  12085. EXPECT_EQ("example.com",
  12086. detail::make_host_and_port_string("example.com", 443, true));
  12087. // IPv4 with non-default HTTP port
  12088. EXPECT_EQ("example.com:8080",
  12089. detail::make_host_and_port_string("example.com", 8080, false));
  12090. // IPv4 with non-default HTTPS port
  12091. EXPECT_EQ("example.com:8443",
  12092. detail::make_host_and_port_string("example.com", 8443, true));
  12093. // IPv6 with default HTTP port (80)
  12094. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12095. // IPv6 with default HTTPS port (443)
  12096. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12097. // IPv6 with non-default HTTP port
  12098. EXPECT_EQ("[::1]:8080",
  12099. detail::make_host_and_port_string("::1", 8080, false));
  12100. // IPv6 with non-default HTTPS port
  12101. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12102. // IPv6 full address with default port
  12103. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12104. detail::make_host_and_port_string(
  12105. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12106. // IPv6 full address with non-default port
  12107. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12108. detail::make_host_and_port_string(
  12109. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12110. // IPv6 localhost with non-default port
  12111. EXPECT_EQ("[::1]:3000",
  12112. detail::make_host_and_port_string("::1", 3000, false));
  12113. // IPv6 with zone ID (link-local address) with default port
  12114. EXPECT_EQ("[fe80::1%eth0]",
  12115. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12116. // IPv6 with zone ID (link-local address) with non-default port
  12117. EXPECT_EQ("[fe80::1%eth0]:8080",
  12118. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12119. // Edge case: Port 443 with is_ssl=false (should add port)
  12120. EXPECT_EQ("example.com:443",
  12121. detail::make_host_and_port_string("example.com", 443, false));
  12122. // Edge case: Port 80 with is_ssl=true (should add port)
  12123. EXPECT_EQ("example.com:80",
  12124. detail::make_host_and_port_string("example.com", 80, true));
  12125. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12126. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12127. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12128. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12129. // Security fix: Already bracketed IPv6 should not get double brackets
  12130. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12131. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12132. EXPECT_EQ("[::1]:8080",
  12133. detail::make_host_and_port_string("[::1]", 8080, false));
  12134. EXPECT_EQ("[2001:db8::1]:8080",
  12135. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12136. EXPECT_EQ("[fe80::1%eth0]",
  12137. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12138. EXPECT_EQ("[fe80::1%eth0]:8080",
  12139. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12140. // Edge case: Empty host (should return as-is)
  12141. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12142. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12143. // This is a known limitation but shouldn't crash
  12144. EXPECT_EQ("[host:name]",
  12145. detail::make_host_and_port_string("host:name", 80, false));
  12146. // Port number edge cases (no validation, but should not crash)
  12147. EXPECT_EQ("example.com:0",
  12148. detail::make_host_and_port_string("example.com", 0, false));
  12149. EXPECT_EQ("example.com:-1",
  12150. detail::make_host_and_port_string("example.com", -1, false));
  12151. EXPECT_EQ("example.com:65535",
  12152. detail::make_host_and_port_string("example.com", 65535, false));
  12153. EXPECT_EQ("example.com:65536",
  12154. detail::make_host_and_port_string("example.com", 65536, false));
  12155. }
  12156. #ifdef CPPHTTPLIB_SSL_ENABLED
  12157. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12158. httplib::SSLClient cli("roblox.com", 443);
  12159. cli.set_follow_location(true);
  12160. auto res = cli.Get("/");
  12161. ASSERT_TRUE(res);
  12162. EXPECT_EQ(StatusCode::OK_200, res->status);
  12163. }
  12164. #endif
  12165. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12166. Server svr;
  12167. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12168. EXPECT_EQ(res.status, 400);
  12169. });
  12170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12171. auto se = detail::scope_exit([&] {
  12172. svr.stop();
  12173. thread.join();
  12174. ASSERT_FALSE(svr.is_running());
  12175. });
  12176. svr.wait_until_ready();
  12177. Client cli(HOST, PORT);
  12178. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12179. }
  12180. TEST(InvalidHeaderCharsTest, is_field_name) {
  12181. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12182. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12183. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12184. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12185. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12186. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12187. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12188. EXPECT_FALSE(detail::fields::is_field_name(""));
  12189. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12190. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12191. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12192. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12193. }
  12194. TEST(InvalidHeaderCharsTest, is_field_value) {
  12195. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12196. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12197. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12198. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12199. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12200. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12201. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12202. EXPECT_TRUE(detail::fields::is_field_value(""));
  12203. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12204. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12205. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12206. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12207. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12208. }
  12209. TEST(InvalidHeaderCharsTest, OnServer) {
  12210. Server svr;
  12211. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12212. std::string header = "Not Set";
  12213. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12214. res.set_header(header, "value");
  12215. res.set_content("Page Content Page Content", "text/plain");
  12216. });
  12217. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12218. std::string header = "Not Set";
  12219. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12220. res.set_header("X-Test", header);
  12221. res.set_content("Page Content Page Content", "text/plain");
  12222. });
  12223. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12224. auto se = detail::scope_exit([&] {
  12225. svr.stop();
  12226. thread.join();
  12227. ASSERT_FALSE(svr.is_running());
  12228. });
  12229. svr.wait_until_ready();
  12230. Client cli(HOST, PORT);
  12231. {
  12232. auto res = cli.Get(
  12233. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12234. ASSERT_TRUE(res);
  12235. EXPECT_EQ("Page Content Page Content", res->body);
  12236. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12237. }
  12238. {
  12239. auto res = cli.Get(
  12240. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12241. ASSERT_TRUE(res);
  12242. EXPECT_EQ("Page Content Page Content", res->body);
  12243. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12244. }
  12245. }
  12246. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12247. auto handled = false;
  12248. Server svr;
  12249. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12250. thread t = thread([&] { svr.listen(HOST, PORT); });
  12251. auto se = detail::scope_exit([&] {
  12252. svr.stop();
  12253. t.join();
  12254. ASSERT_FALSE(svr.is_running());
  12255. ASSERT_FALSE(handled);
  12256. });
  12257. svr.wait_until_ready();
  12258. auto req = "POST /test HTTP/1.1\r\n"
  12259. "Content-Length: x\r\n"
  12260. "\r\n";
  12261. std::string response;
  12262. ASSERT_TRUE(send_request(1, req, &response));
  12263. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12264. response.substr(0, response.find("\r\n")));
  12265. }
  12266. #ifndef _WIN32
  12267. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12268. static constexpr char reject[] = "Unauthorized";
  12269. static constexpr char accept[] = "Upload accepted";
  12270. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12271. Server svr;
  12272. svr.set_expect_100_continue_handler(
  12273. [](const Request & /*req*/, Response &res) {
  12274. res.status = StatusCode::Unauthorized_401;
  12275. res.set_content(reject, "text/plain");
  12276. return res.status;
  12277. });
  12278. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12279. res.set_content(accept, "text/plain");
  12280. });
  12281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12282. auto se = detail::scope_exit([&] {
  12283. svr.stop();
  12284. thread.join();
  12285. ASSERT_FALSE(svr.is_running());
  12286. });
  12287. svr.wait_until_ready();
  12288. {
  12289. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12290. curl_easy_init(), &curl_easy_cleanup};
  12291. ASSERT_NE(curl, nullptr);
  12292. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12293. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12294. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12295. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12296. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12297. &curl_slist_free_all};
  12298. ASSERT_NE(list, nullptr);
  12299. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12300. struct read_data {
  12301. size_t read_size;
  12302. size_t total_size;
  12303. } data = {0, total_size};
  12304. using read_callback_t =
  12305. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12306. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12307. void *userdata) -> size_t {
  12308. read_data *d = (read_data *)userdata;
  12309. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12310. std::fill_n(ptr, size * nmemb, 'A');
  12311. d->read_size += size * nmemb;
  12312. return size * nmemb;
  12313. };
  12314. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12315. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12316. std::vector<char> buffer;
  12317. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12318. using write_callback_t =
  12319. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12320. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12321. void *userdata) -> size_t {
  12322. std::vector<char> *buf = (std::vector<char> *)userdata;
  12323. buf->reserve(buf->size() + size * nmemb + 1);
  12324. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12325. return size * nmemb;
  12326. };
  12327. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12328. {
  12329. const auto res = curl_easy_perform(curl.get());
  12330. ASSERT_EQ(res, CURLE_OK);
  12331. }
  12332. {
  12333. auto response_code = long{};
  12334. const auto res =
  12335. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12336. ASSERT_EQ(res, CURLE_OK);
  12337. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12338. }
  12339. {
  12340. auto dl = curl_off_t{};
  12341. const auto res =
  12342. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12343. ASSERT_EQ(res, CURLE_OK);
  12344. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12345. }
  12346. {
  12347. buffer.push_back('\0');
  12348. ASSERT_STRCASEEQ(buffer.data(), reject);
  12349. }
  12350. }
  12351. }
  12352. #endif
  12353. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12354. // Regression test for #2458.
  12355. //
  12356. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12357. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12358. // ticket can make the client socket spuriously readable during the
  12359. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12360. // the client withholds the body and then blocks reading a response that never
  12361. // comes, failing with `Failed to read connection`.
  12362. //
  12363. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12364. // within the timeout. This raw OpenSSL server deliberately never sends
  12365. // `100 Continue`; the client must still deliver the body and receive 200.
  12366. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12367. signal(SIGPIPE, SIG_IGN);
  12368. const auto port = PORT + 4;
  12369. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12370. ASSERT_NE(srv, INVALID_SOCKET);
  12371. int opt = 1;
  12372. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12373. sockaddr_in addr{};
  12374. addr.sin_family = AF_INET;
  12375. addr.sin_port = htons(static_cast<uint16_t>(port));
  12376. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12377. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12378. ASSERT_EQ(0, ::listen(srv, 1));
  12379. std::atomic<size_t> server_body_bytes{0};
  12380. auto server_thread = std::thread([&] {
  12381. sockaddr_in cli_addr{};
  12382. socklen_t cli_len = sizeof(cli_addr);
  12383. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12384. if (cli == INVALID_SOCKET) { return; }
  12385. // Bound the lifetime of the server side so a buggy client (which never
  12386. // sends the body) cannot make this thread block forever on join.
  12387. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12388. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12389. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12390. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12391. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12392. SSL *ssl = SSL_new(ctx);
  12393. SSL_set_fd(ssl, static_cast<int>(cli));
  12394. if (SSL_accept(ssl) > 0) {
  12395. // Read the request headers. Reading here also flushes the TLS 1.3
  12396. // session tickets to the client. Deliberately do NOT send
  12397. // `100 Continue`.
  12398. std::string buf;
  12399. char tmp[1024];
  12400. while (buf.find("\r\n\r\n") == std::string::npos) {
  12401. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12402. if (n <= 0) { break; }
  12403. buf.append(tmp, static_cast<size_t>(n));
  12404. }
  12405. // A correct client sends the body now; count what arrives.
  12406. auto pos = buf.find("\r\n\r\n");
  12407. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12408. while (body < 4096) {
  12409. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12410. if (n <= 0) { break; }
  12411. body += static_cast<size_t>(n);
  12412. }
  12413. server_body_bytes = body;
  12414. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12415. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12416. SSL_shutdown(ssl);
  12417. }
  12418. SSL_free(ssl);
  12419. detail::close_socket(cli);
  12420. SSL_CTX_free(ctx);
  12421. });
  12422. auto se = detail::scope_exit([&] {
  12423. server_thread.join();
  12424. detail::close_socket(srv);
  12425. });
  12426. SSLClient cli("127.0.0.1", port);
  12427. cli.enable_server_certificate_verification(false);
  12428. cli.set_connection_timeout(5, 0);
  12429. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12430. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12431. std::string body(4096, 'A');
  12432. auto res = cli.Put("/api/test", body, "application/json");
  12433. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12434. EXPECT_EQ(StatusCode::OK_200, res->status);
  12435. EXPECT_EQ(body.size(), server_body_bytes.load());
  12436. }
  12437. #endif
  12438. template <typename S, typename C>
  12439. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12440. svr.Get("/stream", [&](const Request &, Response &res) {
  12441. auto data = new std::string("01234567890123456789");
  12442. res.set_content_provider(
  12443. data->size(), "text/plain",
  12444. [&, data](size_t offset, size_t length, DataSink &sink) {
  12445. const size_t DATA_CHUNK_SIZE = 4;
  12446. const auto &d = *data;
  12447. std::this_thread::sleep_for(std::chrono::seconds(1));
  12448. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12449. return true;
  12450. },
  12451. [data](bool success) {
  12452. EXPECT_FALSE(success);
  12453. delete data;
  12454. });
  12455. });
  12456. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12457. auto i = new size_t(0);
  12458. res.set_content_provider(
  12459. "text/plain",
  12460. [i](size_t, DataSink &sink) {
  12461. if (*i < 5) {
  12462. std::this_thread::sleep_for(std::chrono::seconds(1));
  12463. sink.write("abcd", 4);
  12464. (*i)++;
  12465. } else {
  12466. sink.done();
  12467. }
  12468. return true;
  12469. },
  12470. [i](bool success) {
  12471. EXPECT_FALSE(success);
  12472. delete i;
  12473. });
  12474. });
  12475. svr.Get("/chunked", [&](const Request &, Response &res) {
  12476. auto i = new size_t(0);
  12477. res.set_chunked_content_provider(
  12478. "text/plain",
  12479. [i](size_t, DataSink &sink) {
  12480. if (*i < 5) {
  12481. std::this_thread::sleep_for(std::chrono::seconds(1));
  12482. sink.os << "abcd";
  12483. (*i)++;
  12484. } else {
  12485. sink.done();
  12486. }
  12487. return true;
  12488. },
  12489. [i](bool success) {
  12490. EXPECT_FALSE(success);
  12491. delete i;
  12492. });
  12493. });
  12494. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12495. auto se = detail::scope_exit([&] {
  12496. svr.stop();
  12497. listen_thread.join();
  12498. ASSERT_FALSE(svr.is_running());
  12499. });
  12500. svr.wait_until_ready();
  12501. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12502. {
  12503. auto start = std::chrono::steady_clock::now();
  12504. auto res = cli.Get("/stream");
  12505. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12506. std::chrono::steady_clock::now() - start)
  12507. .count();
  12508. ASSERT_FALSE(res);
  12509. EXPECT_EQ(Error::Read, res.error());
  12510. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12511. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12512. }
  12513. {
  12514. auto start = std::chrono::steady_clock::now();
  12515. auto res = cli.Get("/stream_without_length");
  12516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12517. std::chrono::steady_clock::now() - start)
  12518. .count();
  12519. ASSERT_FALSE(res);
  12520. EXPECT_EQ(Error::Read, res.error());
  12521. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12522. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12523. }
  12524. {
  12525. auto start = std::chrono::steady_clock::now();
  12526. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12527. EXPECT_EQ("abcd", string(data, data_length));
  12528. return true;
  12529. });
  12530. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12531. std::chrono::steady_clock::now() - start)
  12532. .count();
  12533. ASSERT_FALSE(res);
  12534. EXPECT_EQ(Error::Read, res.error());
  12535. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12536. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12537. }
  12538. }
  12539. TEST(MaxTimeoutTest, ContentStream) {
  12540. time_t timeout = 2000;
  12541. time_t threshold = 200;
  12542. Server svr;
  12543. Client cli("localhost", PORT);
  12544. max_timeout_test(svr, cli, timeout, threshold);
  12545. }
  12546. #ifdef CPPHTTPLIB_SSL_ENABLED
  12547. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12548. time_t timeout = 2000;
  12549. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12551. SSLClient cli("localhost", PORT);
  12552. cli.enable_server_certificate_verification(false);
  12553. max_timeout_test(svr, cli, timeout, threshold);
  12554. }
  12555. #endif
  12556. class EventDispatcher {
  12557. public:
  12558. EventDispatcher() {}
  12559. bool wait_event(DataSink *sink) {
  12560. unique_lock<mutex> lk(m_);
  12561. int id = id_;
  12562. // Wait with timeout to prevent hanging if client disconnects
  12563. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12564. [&] { return cid_ == id; })) {
  12565. return false; // Timeout occurred
  12566. }
  12567. sink->write(message_.data(), message_.size());
  12568. return true;
  12569. }
  12570. void send_event(const string &message) {
  12571. lock_guard<mutex> lk(m_);
  12572. cid_ = id_++;
  12573. message_ = message;
  12574. cv_.notify_all();
  12575. }
  12576. private:
  12577. mutex m_;
  12578. condition_variable cv_;
  12579. atomic_int id_{0};
  12580. atomic_int cid_{-1};
  12581. string message_;
  12582. };
  12583. TEST(ClientInThreadTest, Issue2068) {
  12584. EventDispatcher ed;
  12585. Server svr;
  12586. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12587. res.set_chunked_content_provider("text/event-stream",
  12588. [&](size_t /*offset*/, DataSink &sink) {
  12589. return ed.wait_event(&sink);
  12590. });
  12591. });
  12592. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12593. svr.wait_until_ready();
  12594. thread event_thread([&] {
  12595. int id = 0;
  12596. while (svr.is_running()) {
  12597. this_thread::sleep_for(chrono::milliseconds(500));
  12598. std::stringstream ss;
  12599. ss << "data: " << id << "\n\n";
  12600. ed.send_event(ss.str());
  12601. id++;
  12602. }
  12603. });
  12604. auto se = detail::scope_exit([&] {
  12605. svr.stop();
  12606. listen_thread.join();
  12607. event_thread.join();
  12608. ASSERT_FALSE(svr.is_running());
  12609. });
  12610. {
  12611. auto client = detail::make_unique<Client>(HOST, PORT);
  12612. client->set_read_timeout(std::chrono::minutes(10));
  12613. std::atomic<bool> stop{false};
  12614. std::thread t([&] {
  12615. client->Get("/event1",
  12616. [&](const char *, size_t) -> bool { return !stop; });
  12617. });
  12618. std::this_thread::sleep_for(std::chrono::seconds(2));
  12619. stop = true;
  12620. client->stop();
  12621. t.join();
  12622. // Reset client after thread has finished
  12623. client.reset();
  12624. }
  12625. }
  12626. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12627. auto handled = false;
  12628. Server svr;
  12629. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12631. auto se = detail::scope_exit([&] {
  12632. svr.stop();
  12633. t.join();
  12634. ASSERT_FALSE(svr.is_running());
  12635. ASSERT_FALSE(handled);
  12636. });
  12637. svr.wait_until_ready();
  12638. // Two Content-Length headers with different values — must be rejected
  12639. auto req = "POST /test HTTP/1.1\r\n"
  12640. "Content-Length: 5\r\n"
  12641. "Content-Length: 10\r\n"
  12642. "\r\n"
  12643. "hello";
  12644. std::string response;
  12645. ASSERT_TRUE(send_request(1, req, &response));
  12646. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12647. response.substr(0, response.find("\r\n")));
  12648. }
  12649. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12650. auto handled = false;
  12651. Server svr;
  12652. svr.Post("/test", [&](const Request &, Response &res) {
  12653. handled = true;
  12654. res.set_content("ok", "text/plain");
  12655. });
  12656. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12657. auto se = detail::scope_exit([&] {
  12658. svr.stop();
  12659. t.join();
  12660. ASSERT_FALSE(svr.is_running());
  12661. ASSERT_TRUE(handled);
  12662. });
  12663. svr.wait_until_ready();
  12664. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12665. auto req = "POST /test HTTP/1.1\r\n"
  12666. "Content-Length: 5\r\n"
  12667. "Content-Length: 5\r\n"
  12668. "\r\n"
  12669. "hello";
  12670. std::string response;
  12671. ASSERT_TRUE(send_request(1, req, &response));
  12672. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12673. }
  12674. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12675. Server svr;
  12676. svr.Get("/", [](const Request &req, Response &res) {
  12677. EXPECT_EQ(2U, req.trailers.size());
  12678. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12679. // Denied
  12680. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12681. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12682. // Accepted
  12683. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12684. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12685. EXPECT_TRUE(req.has_trailer("X-World"));
  12686. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12687. res.set_content("ok", "text/plain");
  12688. });
  12689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12690. auto se = detail::scope_exit([&] {
  12691. svr.stop();
  12692. t.join();
  12693. ASSERT_FALSE(svr.is_running());
  12694. });
  12695. svr.wait_until_ready();
  12696. const std::string req = "GET / HTTP/1.1\r\n"
  12697. "Transfer-Encoding: chunked\r\n"
  12698. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12699. "\r\n"
  12700. "0\r\n"
  12701. "Content-Length: 10\r\n"
  12702. "Host: internal.local\r\n"
  12703. "Content-Type: malicious/content\r\n"
  12704. "Cookie: any\r\n"
  12705. "Set-Cookie: any\r\n"
  12706. "X-Forwarded-For: attacker.com\r\n"
  12707. "X-Real-Ip: 1.1.1.1\r\n"
  12708. "X-Hello: hello\r\n"
  12709. "X-World: world\r\n"
  12710. "\r\n";
  12711. std::string res;
  12712. ASSERT_TRUE(send_request(1, req, &res));
  12713. }
  12714. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12715. Server svr;
  12716. std::string observed_remote_addr;
  12717. std::string observed_xff;
  12718. svr.Get("/ip", [&](const Request &req, Response &res) {
  12719. observed_remote_addr = req.remote_addr;
  12720. observed_xff = req.get_header_value("X-Forwarded-For");
  12721. res.set_content("ok", "text/plain");
  12722. });
  12723. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12724. auto se = detail::scope_exit([&] {
  12725. svr.stop();
  12726. t.join();
  12727. ASSERT_FALSE(svr.is_running());
  12728. });
  12729. svr.wait_until_ready();
  12730. Client cli(HOST, PORT);
  12731. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12732. ASSERT_TRUE(res);
  12733. EXPECT_EQ(StatusCode::OK_200, res->status);
  12734. EXPECT_EQ(observed_xff, "203.0.113.66");
  12735. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12736. observed_remote_addr == "127.0.0.1");
  12737. }
  12738. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12739. Server svr;
  12740. svr.set_trusted_proxies({"203.0.113.66"});
  12741. std::string observed_remote_addr;
  12742. std::string observed_xff;
  12743. svr.Get("/ip", [&](const Request &req, Response &res) {
  12744. observed_remote_addr = req.remote_addr;
  12745. observed_xff = req.get_header_value("X-Forwarded-For");
  12746. res.set_content("ok", "text/plain");
  12747. });
  12748. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12749. auto se = detail::scope_exit([&] {
  12750. svr.stop();
  12751. t.join();
  12752. ASSERT_FALSE(svr.is_running());
  12753. });
  12754. svr.wait_until_ready();
  12755. Client cli(HOST, PORT);
  12756. auto res = cli.Get("/ip");
  12757. ASSERT_TRUE(res);
  12758. EXPECT_EQ(StatusCode::OK_200, res->status);
  12759. EXPECT_EQ(observed_xff, "");
  12760. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12761. observed_remote_addr == "127.0.0.1");
  12762. }
  12763. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12764. Server svr;
  12765. svr.set_trusted_proxies({"203.0.113.66"});
  12766. std::string observed_remote_addr;
  12767. std::string observed_xff;
  12768. svr.Get("/ip", [&](const Request &req, Response &res) {
  12769. observed_remote_addr = req.remote_addr;
  12770. observed_xff = req.get_header_value("X-Forwarded-For");
  12771. res.set_content("ok", "text/plain");
  12772. });
  12773. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12774. auto se = detail::scope_exit([&] {
  12775. svr.stop();
  12776. t.join();
  12777. ASSERT_FALSE(svr.is_running());
  12778. });
  12779. svr.wait_until_ready();
  12780. Client cli(HOST, PORT);
  12781. auto res = cli.Get(
  12782. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12783. ASSERT_TRUE(res);
  12784. EXPECT_EQ(StatusCode::OK_200, res->status);
  12785. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12786. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12787. }
  12788. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12789. Server svr;
  12790. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12791. std::string observed_remote_addr;
  12792. std::string observed_xff;
  12793. svr.Get("/ip", [&](const Request &req, Response &res) {
  12794. observed_remote_addr = req.remote_addr;
  12795. observed_xff = req.get_header_value("X-Forwarded-For");
  12796. res.set_content("ok", "text/plain");
  12797. });
  12798. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. ASSERT_FALSE(svr.is_running());
  12803. });
  12804. svr.wait_until_ready();
  12805. Client cli(HOST, PORT);
  12806. auto res = cli.Get(
  12807. "/ip",
  12808. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12809. ASSERT_TRUE(res);
  12810. EXPECT_EQ(StatusCode::OK_200, res->status);
  12811. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12812. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12813. }
  12814. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12815. Server svr;
  12816. svr.set_trusted_proxies({"192.0.2.45"});
  12817. std::string observed_remote_addr;
  12818. std::string observed_xff;
  12819. svr.Get("/ip", [&](const Request &req, Response &res) {
  12820. observed_remote_addr = req.remote_addr;
  12821. observed_xff = req.get_header_value("X-Forwarded-For");
  12822. res.set_content("ok", "text/plain");
  12823. });
  12824. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12825. auto se = detail::scope_exit([&] {
  12826. svr.stop();
  12827. t.join();
  12828. ASSERT_FALSE(svr.is_running());
  12829. });
  12830. svr.wait_until_ready();
  12831. Client cli(HOST, PORT);
  12832. auto res = cli.Get(
  12833. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12834. ASSERT_TRUE(res);
  12835. EXPECT_EQ(StatusCode::OK_200, res->status);
  12836. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12837. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12838. }
  12839. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12840. Server svr;
  12841. svr.set_trusted_proxies({"192.0.2.45"});
  12842. std::string observed_remote_addr;
  12843. std::string observed_xff;
  12844. svr.Get("/ip", [&](const Request &req, Response &res) {
  12845. observed_remote_addr = req.remote_addr;
  12846. observed_xff = req.get_header_value("X-Forwarded-For");
  12847. res.set_content("ok", "text/plain");
  12848. });
  12849. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12850. auto se = detail::scope_exit([&] {
  12851. svr.stop();
  12852. t.join();
  12853. ASSERT_FALSE(svr.is_running());
  12854. });
  12855. svr.wait_until_ready();
  12856. Client cli(HOST, PORT);
  12857. auto res = cli.Get(
  12858. "/ip",
  12859. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12860. ASSERT_TRUE(res);
  12861. EXPECT_EQ(StatusCode::OK_200, res->status);
  12862. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12863. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12864. }
  12865. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12866. Server svr;
  12867. svr.set_trusted_proxies({"192.0.2.45"});
  12868. std::string observed_remote_addr;
  12869. std::string observed_xff;
  12870. svr.Get("/ip", [&](const Request &req, Response &res) {
  12871. observed_remote_addr = req.remote_addr;
  12872. observed_xff = req.get_header_value("X-Forwarded-For");
  12873. res.set_content("ok", "text/plain");
  12874. });
  12875. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12876. auto se = detail::scope_exit([&] {
  12877. svr.stop();
  12878. t.join();
  12879. ASSERT_FALSE(svr.is_running());
  12880. });
  12881. svr.wait_until_ready();
  12882. std::string raw_req =
  12883. "GET /ip HTTP/1.1\r\n"
  12884. "Host: localhost\r\n"
  12885. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12886. "Connection: close\r\n"
  12887. "\r\n";
  12888. std::string out;
  12889. ASSERT_TRUE(send_request(5, raw_req, &out));
  12890. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12891. // Header parser trims surrounding whitespace of the header value
  12892. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12893. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12894. }
  12895. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12896. // crash the server (it used to call front() on an empty vector inside
  12897. // get_client_ip). The connection-level remote address must be retained instead.
  12898. static void run_malformed_xff_test(const std::string &xff_value) {
  12899. Server svr;
  12900. svr.set_trusted_proxies({"192.0.2.45"});
  12901. std::string observed_remote_addr;
  12902. svr.Get("/ip", [&](const Request &req, Response &res) {
  12903. observed_remote_addr = req.remote_addr;
  12904. res.set_content("ok", "text/plain");
  12905. });
  12906. int port = 0;
  12907. thread t = thread([&]() {
  12908. port = svr.bind_to_any_port(HOST);
  12909. svr.listen_after_bind();
  12910. });
  12911. auto se = detail::scope_exit([&] {
  12912. svr.stop();
  12913. t.join();
  12914. ASSERT_FALSE(svr.is_running());
  12915. });
  12916. svr.wait_until_ready();
  12917. Client cli(HOST, port);
  12918. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12919. ASSERT_TRUE(res);
  12920. EXPECT_EQ(StatusCode::OK_200, res->status);
  12921. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12922. observed_remote_addr == "127.0.0.1");
  12923. }
  12924. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12925. run_malformed_xff_test("");
  12926. }
  12927. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12928. run_malformed_xff_test(",");
  12929. }
  12930. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12931. run_malformed_xff_test(", , ,");
  12932. }
  12933. #ifndef _WIN32
  12934. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12935. Server svr;
  12936. svr.Post("/post", [&](const Request &req, Response &res) {
  12937. res.set_content(req.body, "text/plain");
  12938. });
  12939. svr.Put("/put", [&](const Request &req, Response &res) {
  12940. res.set_content(req.body, "text/plain");
  12941. });
  12942. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12943. res.set_content(req.body, "text/plain");
  12944. });
  12945. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12946. res.set_content(req.body, "text/plain");
  12947. });
  12948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12949. auto se = detail::scope_exit([&] {
  12950. svr.stop();
  12951. t.join();
  12952. ASSERT_FALSE(svr.is_running());
  12953. });
  12954. svr.wait_until_ready();
  12955. std::string resp;
  12956. // POST without Content-Length
  12957. ASSERT_TRUE(send_request(5,
  12958. "POST /post HTTP/1.1\r\n"
  12959. "Host: localhost\r\n"
  12960. "Connection: close\r\n"
  12961. "\r\n",
  12962. &resp));
  12963. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12964. // PUT without Content-Length
  12965. resp.clear();
  12966. ASSERT_TRUE(send_request(5,
  12967. "PUT /put HTTP/1.1\r\n"
  12968. "Host: localhost\r\n"
  12969. "Connection: close\r\n"
  12970. "\r\n",
  12971. &resp));
  12972. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12973. // PATCH without Content-Length
  12974. resp.clear();
  12975. ASSERT_TRUE(send_request(5,
  12976. "PATCH /patch HTTP/1.1\r\n"
  12977. "Host: localhost\r\n"
  12978. "Connection: close\r\n"
  12979. "\r\n",
  12980. &resp));
  12981. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12982. // DELETE without Content-Length
  12983. resp.clear();
  12984. ASSERT_TRUE(send_request(5,
  12985. "DELETE /delete HTTP/1.1\r\n"
  12986. "Host: localhost\r\n"
  12987. "Connection: close\r\n"
  12988. "\r\n",
  12989. &resp));
  12990. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12991. }
  12992. #endif
  12993. //==============================================================================
  12994. // open_stream() Tests
  12995. //==============================================================================
  12996. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12997. std::string result;
  12998. char buf[8192];
  12999. ssize_t n;
  13000. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13001. result.append(buf, static_cast<size_t>(n));
  13002. }
  13003. return result;
  13004. }
  13005. // Mock stream for unit tests
  13006. class MockStream : public Stream {
  13007. public:
  13008. std::string data;
  13009. size_t pos = 0;
  13010. ssize_t error_after = -1; // -1 = no error
  13011. explicit MockStream(const std::string &d, ssize_t err = -1)
  13012. : data(d), error_after(err) {}
  13013. bool is_readable() const override { return true; }
  13014. bool wait_readable() const override { return true; }
  13015. bool wait_writable() const override { return true; }
  13016. ssize_t read(char *ptr, size_t size) override {
  13017. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13018. if (pos >= data.size()) return 0;
  13019. size_t limit =
  13020. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13021. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13022. std::memcpy(ptr, data.data() + pos, to_read);
  13023. pos += to_read;
  13024. return static_cast<ssize_t>(to_read);
  13025. }
  13026. ssize_t write(const char *, size_t) override { return -1; }
  13027. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13028. ip = "127.0.0.1";
  13029. port = 0;
  13030. }
  13031. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13032. ip = "127.0.0.1";
  13033. port = 0;
  13034. }
  13035. socket_t socket() const override { return INVALID_SOCKET; }
  13036. time_t duration() const override { return 0; }
  13037. };
  13038. TEST(StreamHandleTest, Basic) {
  13039. ClientImpl::StreamHandle handle;
  13040. EXPECT_FALSE(handle.is_valid());
  13041. handle.response = detail::make_unique<Response>();
  13042. handle.error = Error::Connection;
  13043. EXPECT_FALSE(handle.is_valid());
  13044. handle.error = Error::Success;
  13045. EXPECT_TRUE(handle.is_valid());
  13046. }
  13047. TEST(BodyReaderTest, Basic) {
  13048. MockStream stream("Hello, World!");
  13049. detail::BodyReader reader;
  13050. reader.stream = &stream;
  13051. reader.content_length = 13;
  13052. char buf[32];
  13053. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13054. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13055. EXPECT_TRUE(reader.eof);
  13056. }
  13057. TEST(BodyReaderTest, NoStream) {
  13058. detail::BodyReader reader;
  13059. char buf[32];
  13060. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13061. EXPECT_EQ(Error::Connection, reader.last_error);
  13062. }
  13063. TEST(BodyReaderTest, Error) {
  13064. MockStream stream("Hello, World!", 5);
  13065. detail::BodyReader reader;
  13066. reader.stream = &stream;
  13067. reader.content_length = 13;
  13068. char buf[32];
  13069. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13070. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13071. EXPECT_EQ(Error::Read, reader.last_error);
  13072. }
  13073. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13074. // Mock-based StreamHandle tests relying on private internals are removed.
  13075. class OpenStreamTest : public ::testing::Test {
  13076. protected:
  13077. void SetUp() override {
  13078. svr_.Get("/hello", [](const Request &, Response &res) {
  13079. res.set_content("Hello World!", "text/plain");
  13080. });
  13081. svr_.Get("/large", [](const Request &, Response &res) {
  13082. res.set_content(std::string(10000, 'X'), "text/plain");
  13083. });
  13084. svr_.Get("/chunked", [](const Request &, Response &res) {
  13085. res.set_chunked_content_provider("text/plain",
  13086. [](size_t offset, DataSink &sink) {
  13087. if (offset < 15) {
  13088. sink.write("chunk", 5);
  13089. return true;
  13090. }
  13091. sink.done();
  13092. return true;
  13093. });
  13094. });
  13095. svr_.Get("/compressible", [](const Request &, Response &res) {
  13096. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13097. DataSink &sink) {
  13098. if (offset < 100 * 1024) {
  13099. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13100. sink.write(chunk.data(), chunk.size());
  13101. return true;
  13102. }
  13103. sink.done();
  13104. return true;
  13105. });
  13106. });
  13107. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13108. [](const Request & /*req*/, Response &res) {
  13109. auto i = new int(0);
  13110. res.set_header("Trailer", "Content-Length, X-Allowed");
  13111. res.set_chunked_content_provider(
  13112. "text/plain",
  13113. [i](size_t /*offset*/, DataSink &sink) {
  13114. switch (*i) {
  13115. case 0: sink.os << "123"; break;
  13116. case 1: sink.os << "456"; break;
  13117. case 2: sink.os << "789"; break;
  13118. case 3: {
  13119. sink.done_with_trailer(
  13120. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13121. } break;
  13122. }
  13123. (*i)++;
  13124. return true;
  13125. },
  13126. [i](bool success) {
  13127. EXPECT_TRUE(success);
  13128. delete i;
  13129. });
  13130. });
  13131. // Echo headers endpoint for header-related tests
  13132. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13133. std::string body;
  13134. for (const auto &h : req.headers) {
  13135. body.append(h.first);
  13136. body.push_back(':');
  13137. body.append(h.second);
  13138. body.push_back('\n');
  13139. }
  13140. res.set_content(body, "text/plain");
  13141. });
  13142. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13143. std::string body;
  13144. for (const auto &h : req.headers) {
  13145. body.append(h.first);
  13146. body.push_back(':');
  13147. body.append(h.second);
  13148. body.push_back('\n');
  13149. }
  13150. res.set_content(body, "text/plain");
  13151. });
  13152. port_ = svr_.bind_to_any_port("127.0.0.1");
  13153. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13154. svr_.wait_until_ready();
  13155. }
  13156. void TearDown() override {
  13157. svr_.stop();
  13158. if (thread_.joinable()) thread_.join();
  13159. }
  13160. Server svr_;
  13161. std::thread thread_;
  13162. int port_ = 0;
  13163. };
  13164. TEST_F(OpenStreamTest, Basic) {
  13165. Client cli("127.0.0.1", port_);
  13166. auto handle = cli.open_stream("GET", "/hello");
  13167. EXPECT_TRUE(handle.is_valid());
  13168. EXPECT_EQ("Hello World!", read_all(handle));
  13169. }
  13170. TEST_F(OpenStreamTest, SmallBuffer) {
  13171. Client cli("127.0.0.1", port_);
  13172. auto handle = cli.open_stream("GET", "/hello");
  13173. std::string result;
  13174. char buf[4];
  13175. ssize_t n;
  13176. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13177. result.append(buf, static_cast<size_t>(n));
  13178. EXPECT_EQ("Hello World!", result);
  13179. }
  13180. TEST_F(OpenStreamTest, DefaultHeaders) {
  13181. Client cli("127.0.0.1", port_);
  13182. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13183. {
  13184. auto handle = cli.open_stream("GET", "/echo-headers");
  13185. ASSERT_TRUE(handle.is_valid());
  13186. auto body = read_all(handle);
  13187. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13188. std::string::npos);
  13189. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13190. std::string::npos);
  13191. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13192. }
  13193. // open_stream POST with body and no explicit content_type should NOT add
  13194. // text/plain Content-Type (behavior differs from non-streaming path), but
  13195. // should include Content-Length
  13196. {
  13197. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13198. ASSERT_TRUE(handle.is_valid());
  13199. auto body = read_all(handle);
  13200. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13201. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13202. }
  13203. // open_stream POST with explicit Content-Type should preserve it
  13204. {
  13205. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13206. {{"Content-Type", "application/custom"}},
  13207. "{}", "application/custom");
  13208. ASSERT_TRUE(handle.is_valid());
  13209. auto body = read_all(handle);
  13210. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13211. }
  13212. // User-specified User-Agent must not be overwritten for stream API
  13213. {
  13214. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13215. {{"User-Agent", "MyAgent/1.2"}});
  13216. ASSERT_TRUE(handle.is_valid());
  13217. auto body = read_all(handle);
  13218. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13219. }
  13220. }
  13221. TEST_F(OpenStreamTest, Large) {
  13222. Client cli("127.0.0.1", port_);
  13223. auto handle = cli.open_stream("GET", "/large");
  13224. EXPECT_EQ(10000u, read_all(handle).size());
  13225. }
  13226. TEST_F(OpenStreamTest, ConnectionError) {
  13227. Client cli("127.0.0.1", 9999);
  13228. auto handle = cli.open_stream("GET", "/hello");
  13229. EXPECT_FALSE(handle.is_valid());
  13230. }
  13231. TEST_F(OpenStreamTest, Chunked) {
  13232. Client cli("127.0.0.1", port_);
  13233. auto handle = cli.open_stream("GET", "/chunked");
  13234. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13235. "Transfer-Encoding") == "chunked");
  13236. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13237. }
  13238. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13239. Client cli("127.0.0.1", port_);
  13240. auto handle =
  13241. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13242. ASSERT_TRUE(handle.is_valid());
  13243. // Consume body to allow trailers to be received/parsed
  13244. auto body = read_all(handle);
  13245. // Explicitly parse trailers (ensure trailers are available for assertion)
  13246. handle.parse_trailers_if_needed();
  13247. EXPECT_EQ(std::string("123456789"), body);
  13248. // The response should include a Trailer header declaring both names
  13249. ASSERT_TRUE(handle.response);
  13250. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13251. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13252. handle.response->get_header_value("Trailer"));
  13253. // Prohibited trailer must not be present
  13254. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13255. // Allowed trailer should be present
  13256. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13257. EXPECT_EQ(std::string("yes"),
  13258. handle.response->get_trailer_value("X-Allowed"));
  13259. // Verify trailers are NOT present as regular headers
  13260. EXPECT_EQ(std::string(""),
  13261. handle.response->get_header_value("Content-Length"));
  13262. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13263. }
  13264. static std::thread serve_single_response(std::promise<int> &port_promise,
  13265. const std::string &response) {
  13266. return std::thread([&port_promise, response] {
  13267. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13268. default_socket_options(srv);
  13269. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13270. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13271. sockaddr_in addr{};
  13272. addr.sin_family = AF_INET;
  13273. addr.sin_port = htons(0); // Let OS assign a free port
  13274. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13275. int opt = 1;
  13276. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13277. #ifdef _WIN32
  13278. reinterpret_cast<const char *>(&opt),
  13279. #else
  13280. &opt,
  13281. #endif
  13282. sizeof(opt));
  13283. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13284. ::listen(srv, 1) != 0) {
  13285. port_promise.set_value(-1);
  13286. detail::close_socket(srv);
  13287. return;
  13288. }
  13289. socklen_t addr_len = sizeof(addr);
  13290. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13291. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13292. sockaddr_in cli_addr{};
  13293. socklen_t cli_len = sizeof(cli_addr);
  13294. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13295. if (cli != INVALID_SOCKET) {
  13296. // Read the complete HTTP request (until the blank line that terminates
  13297. // headers) before sending the response. If the server closes the socket
  13298. // while the client's request data is still unread in the kernel receive
  13299. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13300. // connection on both sides: it discards the client's receive buffer
  13301. // (which already holds our response) and causes any in-progress write on
  13302. // the client to fail with ECONNRESET. Reading all request data first
  13303. // ensures close() emits a graceful FIN.
  13304. {
  13305. char rbuf[256];
  13306. std::string req;
  13307. while (req.find("\r\n\r\n") == std::string::npos) {
  13308. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13309. if (n <= 0) { break; }
  13310. req.append(rbuf, static_cast<size_t>(n));
  13311. }
  13312. }
  13313. ::send(cli,
  13314. #ifdef _WIN32
  13315. static_cast<const char *>(response.c_str()),
  13316. static_cast<int>(response.size()),
  13317. #else
  13318. response.c_str(), response.size(),
  13319. #endif
  13320. 0);
  13321. detail::close_socket(cli);
  13322. }
  13323. detail::close_socket(srv);
  13324. });
  13325. }
  13326. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13327. #ifndef _WIN32
  13328. signal(SIGPIPE, SIG_IGN);
  13329. #endif
  13330. std::promise<int> port_promise;
  13331. auto port_future = port_promise.get_future();
  13332. auto server_thread =
  13333. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13334. "Content-Type: text/plain\r\n"
  13335. "Content-Length: not-a-number\r\n"
  13336. "Connection: close\r\n"
  13337. "\r\n"
  13338. "hello");
  13339. auto port = port_future.get();
  13340. ASSERT_GT(port, 0);
  13341. Client cli("127.0.0.1", port);
  13342. auto handle = cli.open_stream("GET", "/");
  13343. EXPECT_FALSE(handle.is_valid());
  13344. server_thread.join();
  13345. }
  13346. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13347. #ifndef _WIN32
  13348. signal(SIGPIPE, SIG_IGN);
  13349. #endif
  13350. std::promise<int> port_promise;
  13351. auto port_future = port_promise.get_future();
  13352. auto server_thread = serve_single_response(
  13353. port_promise, "HTTP/1.1 200 OK\r\n"
  13354. "Content-Type: text/plain\r\n"
  13355. "Content-Length: 99999999999999999999999999\r\n"
  13356. "Connection: close\r\n"
  13357. "\r\n"
  13358. "hello");
  13359. auto port = port_future.get();
  13360. ASSERT_GT(port, 0);
  13361. // Before the fix, std::stoull would throw std::out_of_range here and
  13362. // crash the process. After the fix, strtoull silently clamps to
  13363. // ULLONG_MAX so the stream opens without crashing. The important thing
  13364. // is that the process does NOT terminate.
  13365. Client cli("127.0.0.1", port);
  13366. auto handle = cli.open_stream("GET", "/");
  13367. EXPECT_TRUE(handle.is_valid());
  13368. server_thread.join();
  13369. }
  13370. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13371. TEST_F(OpenStreamTest, Gzip) {
  13372. Client cli("127.0.0.1", port_);
  13373. auto handle = cli.open_stream("GET", "/compressible", {},
  13374. {{"Accept-Encoding", "gzip"}});
  13375. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13376. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13377. }
  13378. #endif
  13379. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13380. TEST_F(OpenStreamTest, Brotli) {
  13381. Client cli("127.0.0.1", port_);
  13382. auto handle =
  13383. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13384. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13385. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13386. }
  13387. #endif
  13388. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13389. TEST_F(OpenStreamTest, Zstd) {
  13390. Client cli("127.0.0.1", port_);
  13391. auto handle = cli.open_stream("GET", "/compressible", {},
  13392. {{"Accept-Encoding", "zstd"}});
  13393. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13394. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13395. }
  13396. #endif
  13397. #ifdef CPPHTTPLIB_SSL_ENABLED
  13398. class SSLOpenStreamTest : public ::testing::Test {
  13399. protected:
  13400. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13401. void SetUp() override {
  13402. svr_.Get("/hello", [](const Request &, Response &res) {
  13403. res.set_content("Hello SSL World!", "text/plain");
  13404. });
  13405. svr_.Get("/chunked", [](const Request &, Response &res) {
  13406. res.set_chunked_content_provider("text/plain",
  13407. [](size_t offset, DataSink &sink) {
  13408. if (offset < 15) {
  13409. sink.write("chunk", 5);
  13410. return true;
  13411. }
  13412. sink.done();
  13413. return true;
  13414. });
  13415. });
  13416. svr_.Post("/echo", [](const Request &req, Response &res) {
  13417. res.set_content(req.body, req.get_header_value("Content-Type"));
  13418. });
  13419. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13420. std::string body = req.body;
  13421. res.set_chunked_content_provider(
  13422. "text/plain", [body](size_t offset, DataSink &sink) {
  13423. if (offset < body.size()) {
  13424. sink.write(body.data() + offset, body.size() - offset);
  13425. }
  13426. sink.done();
  13427. return true;
  13428. });
  13429. });
  13430. port_ = svr_.bind_to_any_port("127.0.0.1");
  13431. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13432. svr_.wait_until_ready();
  13433. }
  13434. void TearDown() override {
  13435. svr_.stop();
  13436. if (thread_.joinable()) thread_.join();
  13437. }
  13438. SSLServer svr_;
  13439. std::thread thread_;
  13440. int port_ = 0;
  13441. };
  13442. TEST_F(SSLOpenStreamTest, Basic) {
  13443. SSLClient cli("127.0.0.1", port_);
  13444. cli.enable_server_certificate_verification(false);
  13445. auto handle = cli.open_stream("GET", "/hello");
  13446. ASSERT_TRUE(handle.is_valid());
  13447. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13448. }
  13449. TEST_F(SSLOpenStreamTest, Chunked) {
  13450. SSLClient cli("127.0.0.1", port_);
  13451. cli.enable_server_certificate_verification(false);
  13452. auto handle = cli.open_stream("GET", "/chunked");
  13453. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13454. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13455. "Transfer-Encoding") == "chunked");
  13456. auto body = read_all(handle);
  13457. EXPECT_EQ("chunkchunkchunk", body);
  13458. }
  13459. TEST_F(SSLOpenStreamTest, Post) {
  13460. SSLClient cli("127.0.0.1", port_);
  13461. cli.enable_server_certificate_verification(false);
  13462. auto handle =
  13463. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13464. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13465. EXPECT_EQ(200, handle.response->status);
  13466. auto body = read_all(handle);
  13467. EXPECT_EQ("Hello SSL POST", body);
  13468. }
  13469. TEST_F(SSLOpenStreamTest, PostChunked) {
  13470. SSLClient cli("127.0.0.1", port_);
  13471. cli.enable_server_certificate_verification(false);
  13472. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13473. "Chunked SSL Data", "text/plain");
  13474. ASSERT_TRUE(handle.is_valid());
  13475. EXPECT_EQ(200, handle.response->status);
  13476. auto body = read_all(handle);
  13477. EXPECT_EQ("Chunked SSL Data", body);
  13478. }
  13479. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13480. // Content-Length is terminated by the server closing the connection. When the
  13481. // SSL peer sends a close_notify after the body, the client must treat it as a
  13482. // clean EOF and return a successful response rather than an error.
  13483. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13485. ASSERT_TRUE(svr.is_valid());
  13486. svr.set_keep_alive_max_count(1);
  13487. const std::string expected_body = "Hello from connection-close response!";
  13488. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13489. res.set_content_provider("text/plain",
  13490. [&](size_t offset, DataSink &sink) -> bool {
  13491. if (offset < expected_body.size()) {
  13492. sink.write(expected_body.data() + offset,
  13493. expected_body.size() - offset);
  13494. }
  13495. sink.done();
  13496. return true;
  13497. });
  13498. });
  13499. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13500. auto se = detail::scope_exit([&] {
  13501. svr.stop();
  13502. listen_thread.join();
  13503. ASSERT_FALSE(svr.is_running());
  13504. });
  13505. svr.wait_until_ready();
  13506. SSLClient cli(HOST, PORT);
  13507. cli.enable_server_certificate_verification(false);
  13508. auto res = cli.Get("/no-content-length");
  13509. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13510. EXPECT_EQ(StatusCode::OK_200, res->status);
  13511. EXPECT_EQ(expected_body, res->body);
  13512. }
  13513. #endif // CPPHTTPLIB_SSL_ENABLED
  13514. //==============================================================================
  13515. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13516. // results for various scenarios.
  13517. //==============================================================================
  13518. TEST(ParityTest, GetVsOpenStream) {
  13519. Server svr;
  13520. const std::string path = "/parity";
  13521. const std::string content = "Parity test content: hello world";
  13522. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13523. res.set_content(content, "text/plain");
  13524. });
  13525. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. Client cli(HOST, PORT);
  13533. // Non-stream path
  13534. auto r1 = cli.Get(path);
  13535. ASSERT_TRUE(r1);
  13536. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13537. // Stream path
  13538. auto h = cli.open_stream("GET", path);
  13539. ASSERT_TRUE(h.is_valid());
  13540. EXPECT_EQ(r1->body, read_all(h));
  13541. }
  13542. // Helper to compress data with provided compressor type T
  13543. template <typename Compressor>
  13544. static std::string compress_payload_for_parity(const std::string &in) {
  13545. std::string out;
  13546. Compressor compressor;
  13547. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13548. [&](const char *data, size_t n) {
  13549. out.append(data, n);
  13550. return true;
  13551. });
  13552. EXPECT_TRUE(ok);
  13553. return out;
  13554. }
  13555. // Helper function for compression parity tests
  13556. template <typename Compressor>
  13557. static void test_compression_parity(const std::string &original,
  13558. const std::string &path,
  13559. const std::string &encoding) {
  13560. const std::string compressed =
  13561. compress_payload_for_parity<Compressor>(original);
  13562. Server svr;
  13563. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13564. res.set_content(compressed, "application/octet-stream");
  13565. res.set_header("Content-Encoding", encoding);
  13566. });
  13567. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13568. auto se = detail::scope_exit([&] {
  13569. svr.stop();
  13570. t.join();
  13571. ASSERT_FALSE(svr.is_running());
  13572. });
  13573. svr.wait_until_ready();
  13574. Client cli(HOST, PORT);
  13575. // Non-streaming
  13576. {
  13577. auto res = cli.Get(path);
  13578. ASSERT_TRUE(res);
  13579. EXPECT_EQ(StatusCode::OK_200, res->status);
  13580. EXPECT_EQ(original, res->body);
  13581. }
  13582. // Streaming
  13583. {
  13584. auto h = cli.open_stream("GET", path);
  13585. ASSERT_TRUE(h.is_valid());
  13586. EXPECT_EQ(original, read_all(h));
  13587. }
  13588. }
  13589. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13590. TEST(ParityTest, Gzip) {
  13591. test_compression_parity<detail::gzip_compressor>(
  13592. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13593. }
  13594. #endif
  13595. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13596. TEST(ParityTest, Brotli) {
  13597. test_compression_parity<detail::brotli_compressor>(
  13598. "Hello, brotli parity test payload", "/parity-br", "br");
  13599. }
  13600. #endif
  13601. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13602. TEST(ParityTest, Zstd) {
  13603. test_compression_parity<detail::zstd_compressor>(
  13604. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13605. }
  13606. #endif
  13607. //==============================================================================
  13608. // New Stream API Tests
  13609. //==============================================================================
  13610. inline std::string read_body(httplib::stream::Result &result) {
  13611. std::string body;
  13612. while (result.next()) {
  13613. body.append(result.data(), result.size());
  13614. }
  13615. return body;
  13616. }
  13617. TEST(ClientConnectionTest, Basic) {
  13618. httplib::ClientConnection conn;
  13619. EXPECT_FALSE(conn.is_open());
  13620. conn.sock = 1;
  13621. EXPECT_TRUE(conn.is_open());
  13622. httplib::ClientConnection conn2(std::move(conn));
  13623. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13624. conn2.sock = INVALID_SOCKET;
  13625. }
  13626. // Unified test server for all stream::* tests
  13627. class StreamApiTest : public ::testing::Test {
  13628. protected:
  13629. void SetUp() override {
  13630. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13631. res.set_content("Hello World!", "text/plain");
  13632. });
  13633. svr_.Get("/echo-params",
  13634. [](const httplib::Request &req, httplib::Response &res) {
  13635. std::string r;
  13636. for (const auto &p : req.params) {
  13637. if (!r.empty()) r += "&";
  13638. r += p.first + "=" + p.second;
  13639. }
  13640. res.set_content(r, "text/plain");
  13641. });
  13642. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13643. res.set_content(req.body, req.get_header_value("Content-Type"));
  13644. });
  13645. svr_.Post("/echo-headers",
  13646. [](const httplib::Request &req, httplib::Response &res) {
  13647. std::string r;
  13648. for (const auto &h : req.headers)
  13649. r += h.first + ": " + h.second + "\n";
  13650. res.set_content(r, "text/plain");
  13651. });
  13652. svr_.Post("/echo-params",
  13653. [](const httplib::Request &req, httplib::Response &res) {
  13654. std::string r = "params:";
  13655. for (const auto &p : req.params)
  13656. r += p.first + "=" + p.second + ";";
  13657. res.set_content(r + " body:" + req.body, "text/plain");
  13658. });
  13659. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13660. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13661. });
  13662. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13663. res.set_content("PUT:" + req.body, "text/plain");
  13664. });
  13665. svr_.Patch("/echo",
  13666. [](const httplib::Request &req, httplib::Response &res) {
  13667. res.set_content("PATCH:" + req.body, "text/plain");
  13668. });
  13669. svr_.Delete(
  13670. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13671. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13672. "text/plain");
  13673. });
  13674. svr_.Get("/head-test",
  13675. [](const httplib::Request &, httplib::Response &res) {
  13676. res.set_content("body for HEAD", "text/plain");
  13677. });
  13678. svr_.Options("/options",
  13679. [](const httplib::Request &, httplib::Response &res) {
  13680. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13681. });
  13682. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13683. svr_.wait_until_ready();
  13684. }
  13685. void TearDown() override {
  13686. svr_.stop();
  13687. if (thread_.joinable()) thread_.join();
  13688. }
  13689. httplib::Server svr_;
  13690. std::thread thread_;
  13691. };
  13692. // stream::Get tests
  13693. TEST_F(StreamApiTest, GetBasic) {
  13694. httplib::Client cli(HOST, PORT);
  13695. auto result = httplib::stream::Get(cli, "/hello");
  13696. ASSERT_TRUE(result.is_valid());
  13697. EXPECT_EQ(200, result.status());
  13698. EXPECT_EQ("Hello World!", read_body(result));
  13699. }
  13700. TEST_F(StreamApiTest, GetWithParams) {
  13701. httplib::Client cli(HOST, PORT);
  13702. httplib::Params params{{"foo", "bar"}};
  13703. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13704. ASSERT_TRUE(result.is_valid());
  13705. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13706. }
  13707. TEST_F(StreamApiTest, GetConnectionError) {
  13708. httplib::Client cli(HOST, 9999);
  13709. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13710. }
  13711. TEST_F(StreamApiTest, Get404) {
  13712. httplib::Client cli(HOST, PORT);
  13713. auto result = httplib::stream::Get(cli, "/nonexistent");
  13714. EXPECT_TRUE(result.is_valid());
  13715. EXPECT_EQ(404, result.status());
  13716. }
  13717. // stream::Post tests
  13718. TEST_F(StreamApiTest, PostBasic) {
  13719. httplib::Client cli(HOST, PORT);
  13720. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13721. "application/json");
  13722. ASSERT_TRUE(result.is_valid());
  13723. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13724. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13725. }
  13726. TEST_F(StreamApiTest, PostWithHeaders) {
  13727. httplib::Client cli(HOST, PORT);
  13728. httplib::Headers headers{{"X-Custom", "value"}};
  13729. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13730. "text/plain");
  13731. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13732. }
  13733. TEST_F(StreamApiTest, PostWithParams) {
  13734. httplib::Client cli(HOST, PORT);
  13735. httplib::Params params{{"k", "v"}};
  13736. auto result =
  13737. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13738. auto body = read_body(result);
  13739. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13740. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13741. }
  13742. TEST_F(StreamApiTest, PostLarge) {
  13743. httplib::Client cli(HOST, PORT);
  13744. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13745. size_t total = 0;
  13746. while (result.next()) {
  13747. total += result.size();
  13748. }
  13749. EXPECT_EQ(100u * 1024u, total);
  13750. }
  13751. // stream::Put/Patch tests
  13752. TEST_F(StreamApiTest, PutAndPatch) {
  13753. httplib::Client cli(HOST, PORT);
  13754. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13755. EXPECT_EQ("PUT:test", read_body(put));
  13756. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13757. EXPECT_EQ("PATCH:test", read_body(patch));
  13758. }
  13759. // stream::Delete tests
  13760. TEST_F(StreamApiTest, Delete) {
  13761. httplib::Client cli(HOST, PORT);
  13762. auto del1 = httplib::stream::Delete(cli, "/resource");
  13763. EXPECT_EQ("Deleted", read_body(del1));
  13764. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13765. EXPECT_EQ("Deleted:data", read_body(del2));
  13766. }
  13767. // stream::Head/Options tests
  13768. TEST_F(StreamApiTest, HeadAndOptions) {
  13769. httplib::Client cli(HOST, PORT);
  13770. auto head = httplib::stream::Head(cli, "/head-test");
  13771. EXPECT_TRUE(head.is_valid());
  13772. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13773. auto opts = httplib::stream::Options(cli, "/options");
  13774. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13775. }
  13776. // SSL stream::* tests
  13777. #ifdef CPPHTTPLIB_SSL_ENABLED
  13778. class SSLStreamApiTest : public ::testing::Test {
  13779. protected:
  13780. void SetUp() override {
  13781. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13782. res.set_content("Hello SSL!", "text/plain");
  13783. });
  13784. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13785. res.set_content(req.body, "text/plain");
  13786. });
  13787. port_ = svr_.bind_to_any_port("127.0.0.1");
  13788. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13789. svr_.wait_until_ready();
  13790. }
  13791. void TearDown() override {
  13792. svr_.stop();
  13793. if (thread_.joinable()) thread_.join();
  13794. }
  13795. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13796. std::thread thread_;
  13797. int port_ = 0;
  13798. };
  13799. TEST_F(SSLStreamApiTest, GetAndPost) {
  13800. httplib::SSLClient cli("127.0.0.1", port_);
  13801. cli.enable_server_certificate_verification(false);
  13802. auto get = httplib::stream::Get(cli, "/hello");
  13803. EXPECT_EQ("Hello SSL!", read_body(get));
  13804. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13805. EXPECT_EQ("test", read_body(post));
  13806. }
  13807. #endif
  13808. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13809. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13810. // BodyReader
  13811. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13812. // Test that read timeout during streaming is detected
  13813. // Use a large content-length response where server delays mid-stream
  13814. Server svr;
  13815. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13816. // Send a large response with delay in the middle
  13817. res.set_content_provider(
  13818. 1000, // content_length
  13819. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13820. if (offset < 100) {
  13821. // Send first 100 bytes immediately
  13822. std::string data(100, 'A');
  13823. sink.write(data.c_str(), data.size());
  13824. return true;
  13825. }
  13826. // Then delay longer than client timeout
  13827. std::this_thread::sleep_for(std::chrono::seconds(3));
  13828. std::string data(900, 'B');
  13829. sink.write(data.c_str(), data.size());
  13830. return true;
  13831. });
  13832. });
  13833. auto port = 8091;
  13834. std::thread t([&]() { svr.listen("localhost", port); });
  13835. svr.wait_until_ready();
  13836. Client cli("localhost", port);
  13837. cli.set_read_timeout(1, 0); // 1 second timeout
  13838. auto handle = cli.open_stream("GET", "/slow-stream");
  13839. ASSERT_TRUE(handle.is_valid());
  13840. char buf[256];
  13841. ssize_t total = 0;
  13842. ssize_t n;
  13843. bool got_error = false;
  13844. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13845. total += n;
  13846. }
  13847. if (n < 0) {
  13848. got_error = true;
  13849. // Should be timeout or read error
  13850. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13851. handle.get_read_error() == Error::Read)
  13852. << "Actual error: " << to_string(handle.get_read_error());
  13853. }
  13854. // Either we got an error, or we got less data than expected
  13855. EXPECT_TRUE(got_error || total < 1000)
  13856. << "Expected timeout but got all " << total << " bytes";
  13857. svr.stop();
  13858. t.join();
  13859. }
  13860. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13861. // Test connection closed detection via BodyReader
  13862. Server svr;
  13863. std::atomic<bool> close_now{false};
  13864. svr.Get("/will-close", [&](const Request &, Response &res) {
  13865. res.set_content_provider(
  13866. 10000, // Large content_length that we won't fully send
  13867. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13868. if (offset < 100) {
  13869. std::string data(100, 'X');
  13870. sink.write(data.c_str(), data.size());
  13871. return true;
  13872. }
  13873. // Wait for signal then abort
  13874. while (!close_now) {
  13875. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13876. }
  13877. return false; // Abort - server will close connection
  13878. });
  13879. });
  13880. auto port = 8092;
  13881. std::thread t([&]() { svr.listen("localhost", port); });
  13882. svr.wait_until_ready();
  13883. Client cli("localhost", port);
  13884. auto handle = cli.open_stream("GET", "/will-close");
  13885. ASSERT_TRUE(handle.is_valid());
  13886. char buf[256];
  13887. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13888. EXPECT_GT(n, 0) << "First read should succeed";
  13889. // Signal server to close
  13890. close_now = true;
  13891. // Keep reading until error or EOF
  13892. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13893. // Keep reading
  13894. }
  13895. // Should get an error since content_length wasn't satisfied
  13896. if (n < 0) {
  13897. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13898. handle.get_read_error() == Error::Read)
  13899. << "Actual error: " << to_string(handle.get_read_error());
  13900. }
  13901. svr.stop();
  13902. t.join();
  13903. }
  13904. #ifdef CPPHTTPLIB_SSL_ENABLED
  13905. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13906. // Test that read timeout during SSL streaming is detected
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13908. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13909. res.set_content_provider(
  13910. 1000, "text/plain",
  13911. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13912. if (offset < 100) {
  13913. std::string data(100, 'A');
  13914. sink.write(data.c_str(), data.size());
  13915. return true;
  13916. }
  13917. std::this_thread::sleep_for(std::chrono::seconds(3));
  13918. std::string data(900, 'B');
  13919. sink.write(data.c_str(), data.size());
  13920. return true;
  13921. });
  13922. });
  13923. auto port = 8093;
  13924. std::thread t([&]() { svr.listen("localhost", port); });
  13925. svr.wait_until_ready();
  13926. SSLClient cli("localhost", port);
  13927. cli.enable_server_certificate_verification(false);
  13928. cli.set_read_timeout(1, 0); // 1 second timeout
  13929. auto handle = cli.open_stream("GET", "/slow-stream");
  13930. ASSERT_TRUE(handle.is_valid());
  13931. char buf[256];
  13932. ssize_t total = 0;
  13933. ssize_t n;
  13934. bool got_error = false;
  13935. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13936. total += n;
  13937. }
  13938. if (n < 0) {
  13939. got_error = true;
  13940. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13941. handle.get_read_error() == Error::Read)
  13942. << "Actual error: " << to_string(handle.get_read_error());
  13943. }
  13944. EXPECT_TRUE(got_error || total < 1000)
  13945. << "Expected timeout but got all " << total << " bytes";
  13946. svr.stop();
  13947. t.join();
  13948. }
  13949. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13950. // Test SSL connection closed detection
  13951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13952. std::atomic<bool> close_now{false};
  13953. svr.Get("/will-close", [&](const Request &, Response &res) {
  13954. res.set_content_provider(
  13955. 10000, "text/plain",
  13956. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13957. if (offset < 100) {
  13958. std::string data(100, 'X');
  13959. sink.write(data.c_str(), data.size());
  13960. return true;
  13961. }
  13962. while (!close_now) {
  13963. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13964. }
  13965. return false;
  13966. });
  13967. });
  13968. auto port = 8094;
  13969. std::thread t([&]() { svr.listen("localhost", port); });
  13970. svr.wait_until_ready();
  13971. SSLClient cli("localhost", port);
  13972. cli.enable_server_certificate_verification(false);
  13973. auto handle = cli.open_stream("GET", "/will-close");
  13974. ASSERT_TRUE(handle.is_valid());
  13975. char buf[256];
  13976. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13977. EXPECT_GT(n, 0);
  13978. // Signal server to close
  13979. close_now = true;
  13980. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13981. // Keep reading
  13982. }
  13983. if (n < 0) {
  13984. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13985. handle.get_read_error() == Error::Read)
  13986. << "Actual error: " << to_string(handle.get_read_error());
  13987. }
  13988. svr.stop();
  13989. t.join();
  13990. }
  13991. #endif
  13992. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13993. using namespace httplib;
  13994. // Create a test file
  13995. const char *fname = "etag_testfile.txt";
  13996. const char *content = "etag-content";
  13997. {
  13998. std::ofstream ofs(fname);
  13999. ofs << content;
  14000. ASSERT_TRUE(ofs.good());
  14001. }
  14002. Server svr;
  14003. svr.set_mount_point("/static", ".");
  14004. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14005. svr.wait_until_ready();
  14006. Client cli(HOST, PORT);
  14007. // First request: should get 200 with ETag header
  14008. auto res1 = cli.Get("/static/etag_testfile.txt");
  14009. ASSERT_TRUE(res1);
  14010. ASSERT_EQ(200, res1->status);
  14011. ASSERT_TRUE(res1->has_header("ETag"));
  14012. std::string etag = res1->get_header_value("ETag");
  14013. EXPECT_FALSE(etag.empty());
  14014. // Verify ETag format: W/"hex-hex"
  14015. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14016. EXPECT_EQ('W', etag[0]);
  14017. EXPECT_EQ('/', etag[1]);
  14018. EXPECT_EQ('"', etag[2]);
  14019. EXPECT_EQ('"', etag.back());
  14020. // Exact match: expect 304 Not Modified
  14021. Headers h2 = {{"If-None-Match", etag}};
  14022. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14023. ASSERT_TRUE(res2);
  14024. EXPECT_EQ(304, res2->status);
  14025. // Wildcard match: expect 304 Not Modified
  14026. Headers h3 = {{"If-None-Match", "*"}};
  14027. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14028. ASSERT_TRUE(res3);
  14029. EXPECT_EQ(304, res3->status);
  14030. // Non-matching ETag: expect 200
  14031. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14032. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14033. ASSERT_TRUE(res4);
  14034. EXPECT_EQ(200, res4->status);
  14035. // Multiple ETags with one matching: expect 304
  14036. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14037. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14038. ASSERT_TRUE(res5);
  14039. EXPECT_EQ(304, res5->status);
  14040. svr.stop();
  14041. t.join();
  14042. std::remove(fname);
  14043. }
  14044. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14045. using namespace httplib;
  14046. Server svr;
  14047. svr.set_mount_point("/static", ".");
  14048. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14049. svr.wait_until_ready();
  14050. Client cli(HOST, PORT);
  14051. // Send If-None-Match: * to a non-existent file
  14052. Headers h = {{"If-None-Match", "*"}};
  14053. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14054. ASSERT_TRUE(res);
  14055. EXPECT_EQ(404, res->status);
  14056. svr.stop();
  14057. t.join();
  14058. }
  14059. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14060. using namespace httplib;
  14061. // Create a test file
  14062. const char *fname = "etag_boundary_testfile.txt";
  14063. const char *content = "boundary-test";
  14064. {
  14065. std::ofstream ofs(fname);
  14066. ofs << content;
  14067. ASSERT_TRUE(ofs.good());
  14068. }
  14069. Server svr;
  14070. svr.set_mount_point("/static", ".");
  14071. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14072. svr.wait_until_ready();
  14073. Client cli(HOST, PORT);
  14074. // Get the actual ETag
  14075. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14076. ASSERT_TRUE(res1);
  14077. ASSERT_EQ(200, res1->status);
  14078. ASSERT_TRUE(res1->has_header("ETag"));
  14079. std::string etag = res1->get_header_value("ETag");
  14080. // Test 1: Very long ETag value (longer than actual ETag)
  14081. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14082. Headers h1 = {{"If-None-Match", "W/"
  14083. "\"very-long-etag-value-that-is-much-longer-"
  14084. "than-the-actual-etag-value\""}};
  14085. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14086. ASSERT_TRUE(res2);
  14087. EXPECT_EQ(200, res2->status); // Should not match
  14088. // Test 2: Long string followed by wildcard
  14089. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14090. // string)
  14091. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14092. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14093. ASSERT_TRUE(res3);
  14094. EXPECT_EQ(304, res3->status); // Should match on "*"
  14095. // Test 3: Wildcard followed by long string
  14096. // Should match on "*" immediately and return 304
  14097. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14098. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14099. ASSERT_TRUE(res4);
  14100. EXPECT_EQ(304, res4->status); // Should match on "*"
  14101. // Test 4: Multiple long non-matching values
  14102. // Should NOT match and return 200 (test that all comparisons are safe)
  14103. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14104. "W/\"second-long-non-matching-value\", "
  14105. "W/\"third-long-non-matching-value\""}};
  14106. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14107. ASSERT_TRUE(res5);
  14108. EXPECT_EQ(200, res5->status); // Should not match
  14109. // Test 5: Single character that is not "*" (edge case)
  14110. Headers h5 = {{"If-None-Match", "X"}};
  14111. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14112. ASSERT_TRUE(res6);
  14113. EXPECT_EQ(200, res6->status); // Should not match
  14114. svr.stop();
  14115. t.join();
  14116. std::remove(fname);
  14117. }
  14118. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14119. using namespace httplib;
  14120. // Create a test file
  14121. const char *fname = "ims_testfile.txt";
  14122. const char *content = "if-modified-since-test";
  14123. {
  14124. std::ofstream ofs(fname);
  14125. ofs << content;
  14126. ASSERT_TRUE(ofs.good());
  14127. }
  14128. Server svr;
  14129. svr.set_mount_point("/static", ".");
  14130. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14131. svr.wait_until_ready();
  14132. Client cli(HOST, PORT);
  14133. // First request: should get 200 with Last-Modified header
  14134. auto res1 = cli.Get("/static/ims_testfile.txt");
  14135. ASSERT_TRUE(res1);
  14136. ASSERT_EQ(200, res1->status);
  14137. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14138. std::string last_modified = res1->get_header_value("Last-Modified");
  14139. EXPECT_FALSE(last_modified.empty());
  14140. // If-Modified-Since with same time: expect 304
  14141. Headers h2 = {{"If-Modified-Since", last_modified}};
  14142. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14143. ASSERT_TRUE(res2);
  14144. EXPECT_EQ(304, res2->status);
  14145. // If-Modified-Since with future time: expect 304
  14146. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14147. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14148. ASSERT_TRUE(res3);
  14149. EXPECT_EQ(304, res3->status);
  14150. // If-Modified-Since with past time: expect 200
  14151. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14152. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14153. ASSERT_TRUE(res4);
  14154. EXPECT_EQ(200, res4->status);
  14155. // If-None-Match takes precedence over If-Modified-Since
  14156. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14157. ASSERT_TRUE(res1->has_header("ETag"));
  14158. std::string etag = res1->get_header_value("ETag");
  14159. Headers h5 = {{"If-None-Match", etag},
  14160. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14161. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14162. ASSERT_TRUE(res5);
  14163. EXPECT_EQ(304, res5->status);
  14164. svr.stop();
  14165. t.join();
  14166. std::remove(fname);
  14167. }
  14168. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14169. using namespace httplib;
  14170. Server svr;
  14171. // Endpoint that returns compressible content
  14172. svr.Get("/compressible", [](const Request &, Response &res) {
  14173. // Return a large enough body to trigger compression
  14174. std::string body(1000, 'a');
  14175. res.set_content(body, "text/plain");
  14176. });
  14177. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14178. svr.wait_until_ready();
  14179. Client cli(HOST, PORT);
  14180. // Request with gzip support: should get Vary header when compressed
  14181. cli.set_compress(true);
  14182. auto res1 = cli.Get("/compressible");
  14183. ASSERT_TRUE(res1);
  14184. EXPECT_EQ(200, res1->status);
  14185. // If Content-Encoding is set, Vary should also be set
  14186. if (res1->has_header("Content-Encoding")) {
  14187. EXPECT_TRUE(res1->has_header("Vary"));
  14188. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14189. }
  14190. // Request without Accept-Encoding header: should not have compression
  14191. Headers h_no_compress;
  14192. auto res2 = cli.Get("/compressible", h_no_compress);
  14193. ASSERT_TRUE(res2);
  14194. EXPECT_EQ(200, res2->status);
  14195. // Verify Vary header is present when compression is applied
  14196. // (the exact behavior depends on server configuration)
  14197. svr.stop();
  14198. t.join();
  14199. }
  14200. TEST(ETagTest, IfRangeWithETag) {
  14201. using namespace httplib;
  14202. // Create a test file with known content
  14203. const char *fname = "if_range_testfile.txt";
  14204. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14205. {
  14206. std::ofstream ofs(fname);
  14207. ofs << content;
  14208. ASSERT_TRUE(ofs.good());
  14209. }
  14210. Server svr;
  14211. svr.set_mount_point("/static", ".");
  14212. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14213. svr.wait_until_ready();
  14214. Client cli(HOST, PORT);
  14215. // First request: get ETag
  14216. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14217. ASSERT_TRUE(res1);
  14218. ASSERT_EQ(200, res1->status);
  14219. ASSERT_TRUE(res1->has_header("ETag"));
  14220. std::string etag = res1->get_header_value("ETag");
  14221. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14222. // Since our server generates weak ETags (W/"..."), If-Range with our
  14223. // ETag should NOT result in partial content - it should return full content.
  14224. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14225. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14226. ASSERT_TRUE(res2);
  14227. // Weak ETag in If-Range -> full content (200), not partial (206)
  14228. EXPECT_EQ(200, res2->status);
  14229. EXPECT_EQ(content, res2->body);
  14230. EXPECT_FALSE(res2->has_header("Content-Range"));
  14231. // Range request with non-matching If-Range (ETag): should get 200 (full
  14232. // content)
  14233. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14234. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14235. ASSERT_TRUE(res3);
  14236. EXPECT_EQ(200, res3->status);
  14237. EXPECT_EQ(content, res3->body);
  14238. EXPECT_FALSE(res3->has_header("Content-Range"));
  14239. // Range request with strong ETag (hypothetical - our server doesn't generate
  14240. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14241. // should return full content)
  14242. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14243. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14244. ASSERT_TRUE(res4);
  14245. EXPECT_EQ(200, res4->status);
  14246. EXPECT_EQ(content, res4->body);
  14247. EXPECT_FALSE(res4->has_header("Content-Range"));
  14248. svr.stop();
  14249. t.join();
  14250. std::remove(fname);
  14251. }
  14252. TEST(ETagTest, IfRangeWithDate) {
  14253. using namespace httplib;
  14254. // Create a test file
  14255. const char *fname = "if_range_date_testfile.txt";
  14256. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14257. {
  14258. std::ofstream ofs(fname);
  14259. ofs << content;
  14260. ASSERT_TRUE(ofs.good());
  14261. }
  14262. Server svr;
  14263. svr.set_mount_point("/static", ".");
  14264. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14265. svr.wait_until_ready();
  14266. Client cli(HOST, PORT);
  14267. // First request: get Last-Modified
  14268. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14269. ASSERT_TRUE(res1);
  14270. ASSERT_EQ(200, res1->status);
  14271. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14272. std::string last_modified = res1->get_header_value("Last-Modified");
  14273. // Range request with matching If-Range (date): should get 206
  14274. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14275. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14276. ASSERT_TRUE(res2);
  14277. EXPECT_EQ(206, res2->status);
  14278. EXPECT_EQ("FGHIJ", res2->body);
  14279. // Range request with old If-Range date: should get 200 (full content)
  14280. Headers h3 = {{"Range", "bytes=5-9"},
  14281. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14282. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14283. ASSERT_TRUE(res3);
  14284. EXPECT_EQ(200, res3->status);
  14285. EXPECT_EQ(content, res3->body);
  14286. // Range request with future If-Range date: should get 206
  14287. Headers h4 = {{"Range", "bytes=0-4"},
  14288. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14289. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14290. ASSERT_TRUE(res4);
  14291. EXPECT_EQ(206, res4->status);
  14292. EXPECT_EQ("ABCDE", res4->body);
  14293. svr.stop();
  14294. t.join();
  14295. std::remove(fname);
  14296. }
  14297. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14298. using namespace httplib;
  14299. const char *fname = "etag_malformed.txt";
  14300. const char *content = "malformed-etag";
  14301. {
  14302. std::ofstream ofs(fname);
  14303. ofs << content;
  14304. ASSERT_TRUE(ofs.good());
  14305. }
  14306. Server svr;
  14307. svr.set_mount_point("/static", ".");
  14308. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14309. svr.wait_until_ready();
  14310. Client cli(HOST, PORT);
  14311. // baseline: should get 200 and an ETag
  14312. auto res1 = cli.Get("/static/etag_malformed.txt");
  14313. ASSERT_TRUE(res1);
  14314. ASSERT_EQ(200, res1->status);
  14315. ASSERT_TRUE(res1->has_header("ETag"));
  14316. // Malformed ETag value (missing quotes) should be treated as non-matching
  14317. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14318. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14319. ASSERT_TRUE(res_bad);
  14320. EXPECT_EQ(200, res_bad->status);
  14321. // Whitespace-only header value should be considered invalid / non-matching
  14322. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14323. "Host: localhost\r\n"
  14324. "If-None-Match: \r\n"
  14325. "Connection: close\r\n"
  14326. "\r\n";
  14327. std::string out;
  14328. ASSERT_TRUE(send_request(5, raw_req, &out));
  14329. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14330. svr.stop();
  14331. t.join();
  14332. std::remove(fname);
  14333. }
  14334. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14335. using namespace httplib;
  14336. const char *fname = "ims_invalid_format.txt";
  14337. const char *content = "ims-bad-format";
  14338. {
  14339. std::ofstream ofs(fname);
  14340. ofs << content;
  14341. ASSERT_TRUE(ofs.good());
  14342. }
  14343. Server svr;
  14344. svr.set_mount_point("/static", ".");
  14345. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14346. svr.wait_until_ready();
  14347. Client cli(HOST, PORT);
  14348. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14349. ASSERT_TRUE(res1);
  14350. ASSERT_EQ(200, res1->status);
  14351. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14352. // If-Modified-Since with invalid format should not result in 304
  14353. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14354. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14355. ASSERT_TRUE(res_bad);
  14356. EXPECT_EQ(200, res_bad->status);
  14357. // If-Range with invalid date format should be treated as mismatch -> full
  14358. // content (200)
  14359. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14360. {"If-Range", "invalid-date"}};
  14361. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14362. ASSERT_TRUE(res_ifrange);
  14363. EXPECT_EQ(200, res_ifrange->status);
  14364. svr.stop();
  14365. t.join();
  14366. std::remove(fname);
  14367. }
  14368. TEST(ETagTest, IfRangeWithMalformedETag) {
  14369. using namespace httplib;
  14370. const char *fname = "ifrange_malformed.txt";
  14371. const std::string content = "0123456789";
  14372. {
  14373. std::ofstream ofs(fname);
  14374. ofs << content;
  14375. ASSERT_TRUE(ofs.good());
  14376. }
  14377. Server svr;
  14378. svr.set_mount_point("/static", ".");
  14379. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14380. svr.wait_until_ready();
  14381. Client cli(HOST, PORT);
  14382. // First request: get ETag
  14383. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14384. ASSERT_TRUE(res1);
  14385. ASSERT_EQ(200, res1->status);
  14386. ASSERT_TRUE(res1->has_header("ETag"));
  14387. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14388. // full content (200)
  14389. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14390. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14391. ASSERT_TRUE(res2);
  14392. EXPECT_EQ(200, res2->status);
  14393. EXPECT_EQ(content, res2->body);
  14394. svr.stop();
  14395. t.join();
  14396. std::remove(fname);
  14397. }
  14398. TEST(ETagTest, ExtremeLargeDateValues) {
  14399. using namespace httplib;
  14400. const char *fname = "ims_extreme_date.txt";
  14401. const char *content = "ims-extreme-date";
  14402. {
  14403. std::ofstream ofs(fname);
  14404. ofs << content;
  14405. ASSERT_TRUE(ofs.good());
  14406. }
  14407. Server svr;
  14408. svr.set_mount_point("/static", ".");
  14409. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14410. svr.wait_until_ready();
  14411. Client cli(HOST, PORT);
  14412. auto res1 = cli.Get(std::string("/static/") + fname);
  14413. ASSERT_TRUE(res1);
  14414. ASSERT_EQ(200, res1->status);
  14415. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14416. // Extremely large year that may overflow date parsing routines.
  14417. Headers h_large_date = {
  14418. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14419. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14420. ASSERT_TRUE(res_bad);
  14421. // Expect server to treat this as invalid/mismatch and return full content
  14422. EXPECT_EQ(200, res_bad->status);
  14423. // If-Range with extremely large date should be treated as mismatch -> full
  14424. // content (200)
  14425. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14426. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14427. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14428. ASSERT_TRUE(res_ifrange);
  14429. EXPECT_EQ(200, res_ifrange->status);
  14430. svr.stop();
  14431. t.join();
  14432. std::remove(fname);
  14433. }
  14434. TEST(ETagTest, NegativeFileModificationTime) {
  14435. using namespace httplib;
  14436. const char *fname = "ims_negative_mtime.txt";
  14437. const std::string content = "negative-mtime";
  14438. {
  14439. std::ofstream ofs(fname);
  14440. ofs << content;
  14441. ASSERT_TRUE(ofs.good());
  14442. }
  14443. // Try to set file mtime to a negative value. This may fail on some
  14444. // platforms/filesystems; if it fails, the test will still verify server
  14445. // behaves safely by performing a regular conditional request.
  14446. #if defined(__APPLE__) || defined(__linux__)
  14447. bool set_negative = false;
  14448. do {
  14449. struct timeval times[2];
  14450. // access time: now
  14451. times[0].tv_sec = time(nullptr);
  14452. times[0].tv_usec = 0;
  14453. // modification time: negative (e.g., -1)
  14454. times[1].tv_sec = -1;
  14455. times[1].tv_usec = 0;
  14456. if (utimes(fname, times) == 0) { set_negative = true; }
  14457. } while (0);
  14458. #else
  14459. bool set_negative = false;
  14460. #endif
  14461. Server svr;
  14462. svr.set_mount_point("/static", ".");
  14463. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14464. svr.wait_until_ready();
  14465. Client cli(HOST, PORT);
  14466. auto res1 = cli.Get(std::string("/static/") + fname);
  14467. ASSERT_TRUE(res1);
  14468. ASSERT_EQ(200, res1->status);
  14469. bool has_last_modified = res1->has_header("Last-Modified");
  14470. std::string last_modified;
  14471. if (has_last_modified) {
  14472. last_modified = res1->get_header_value("Last-Modified");
  14473. }
  14474. if (set_negative) {
  14475. // If we successfully set a negative mtime, ensure server returns a
  14476. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14477. // with an old date and ensure server handles it without crash.
  14478. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14479. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14480. ASSERT_TRUE(res2);
  14481. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14482. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14483. } else {
  14484. // Could not set negative mtime on this platform; fall back to verifying
  14485. // that normal invalid/malformed dates are treated safely (non-304).
  14486. Headers h_bad_date = {
  14487. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14488. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14489. ASSERT_TRUE(res_bad);
  14490. EXPECT_EQ(200, res_bad->status);
  14491. }
  14492. svr.stop();
  14493. t.join();
  14494. std::remove(fname);
  14495. }
  14496. //==============================================================================
  14497. // SSE Parsing Tests
  14498. //==============================================================================
  14499. class SSEParsingTest : public ::testing::Test {
  14500. protected:
  14501. // Test helper that mimics SSE parsing behavior
  14502. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14503. int &retry_ms) {
  14504. // Blank line signals end of event
  14505. if (line.empty() || line == "\r") { return true; }
  14506. // Lines starting with ':' are comments (ignored)
  14507. if (!line.empty() && line[0] == ':') { return false; }
  14508. // Find the colon separator
  14509. auto colon_pos = line.find(':');
  14510. if (colon_pos == std::string::npos) {
  14511. // Line with no colon is treated as field name with empty value
  14512. return false;
  14513. }
  14514. std::string field = line.substr(0, colon_pos);
  14515. std::string value;
  14516. // Value starts after colon, skip optional single space
  14517. if (colon_pos + 1 < line.size()) {
  14518. size_t value_start = colon_pos + 1;
  14519. if (line[value_start] == ' ') { value_start++; }
  14520. value = line.substr(value_start);
  14521. // Remove trailing \r if present
  14522. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14523. }
  14524. // Handle known fields
  14525. if (field == "event") {
  14526. msg.event = value;
  14527. } else if (field == "data") {
  14528. // Multiple data lines are concatenated with newlines
  14529. if (!msg.data.empty()) { msg.data += "\n"; }
  14530. msg.data += value;
  14531. } else if (field == "id") {
  14532. // Empty id is valid (clears the last event ID)
  14533. msg.id = value;
  14534. } else if (field == "retry") {
  14535. // Parse retry interval in milliseconds
  14536. {
  14537. int v = 0;
  14538. auto res =
  14539. detail::from_chars(value.data(), value.data() + value.size(), v);
  14540. if (res.ec == std::errc{}) { retry_ms = v; }
  14541. }
  14542. }
  14543. // Unknown fields are ignored per SSE spec
  14544. return false;
  14545. }
  14546. };
  14547. // Test: Single-line data
  14548. TEST_F(SSEParsingTest, SingleLineData) {
  14549. sse::SSEMessage msg;
  14550. int retry_ms = 3000;
  14551. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14552. EXPECT_EQ(msg.data, "hello");
  14553. EXPECT_EQ(msg.event, "message");
  14554. // Blank line ends event
  14555. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14556. }
  14557. // Test: Multi-line data
  14558. TEST_F(SSEParsingTest, MultiLineData) {
  14559. sse::SSEMessage msg;
  14560. int retry_ms = 3000;
  14561. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14562. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14563. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14564. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14565. }
  14566. // Test: Custom event types
  14567. TEST_F(SSEParsingTest, CustomEventType) {
  14568. sse::SSEMessage msg;
  14569. int retry_ms = 3000;
  14570. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14571. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14572. EXPECT_EQ(msg.event, "update");
  14573. EXPECT_EQ(msg.data, "payload");
  14574. }
  14575. // Test: Event ID handling
  14576. TEST_F(SSEParsingTest, EventIdHandling) {
  14577. sse::SSEMessage msg;
  14578. int retry_ms = 3000;
  14579. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14580. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14581. EXPECT_EQ(msg.id, "12345");
  14582. }
  14583. // Test: Empty event ID (clears last event ID)
  14584. TEST_F(SSEParsingTest, EmptyEventId) {
  14585. sse::SSEMessage msg;
  14586. msg.id = "previous";
  14587. int retry_ms = 3000;
  14588. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14589. EXPECT_EQ(msg.id, "");
  14590. }
  14591. // Test: Retry field parsing
  14592. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14593. sse::SSEMessage msg;
  14594. int retry_ms = 3000;
  14595. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14596. EXPECT_EQ(retry_ms, 5000);
  14597. }
  14598. // Test: Invalid retry value
  14599. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14600. sse::SSEMessage msg;
  14601. int retry_ms = 3000;
  14602. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14603. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14604. }
  14605. // Test: Comments (lines starting with :)
  14606. TEST_F(SSEParsingTest, CommentsIgnored) {
  14607. sse::SSEMessage msg;
  14608. int retry_ms = 3000;
  14609. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14610. EXPECT_EQ(msg.data, "");
  14611. EXPECT_EQ(msg.event, "message");
  14612. }
  14613. // Test: Colon in value
  14614. TEST_F(SSEParsingTest, ColonInValue) {
  14615. sse::SSEMessage msg;
  14616. int retry_ms = 3000;
  14617. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14618. EXPECT_EQ(msg.data, "hello:world:test");
  14619. }
  14620. // Test: Line with no colon (field name only)
  14621. TEST_F(SSEParsingTest, FieldNameOnly) {
  14622. sse::SSEMessage msg;
  14623. int retry_ms = 3000;
  14624. // According to SSE spec, this is treated as field name with empty value
  14625. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14626. // Since we don't recognize "data" without colon, data should be empty
  14627. EXPECT_EQ(msg.data, "");
  14628. }
  14629. // Test: Trailing \r handling
  14630. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14631. sse::SSEMessage msg;
  14632. int retry_ms = 3000;
  14633. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14634. EXPECT_EQ(msg.data, "hello");
  14635. }
  14636. // Test: Unknown fields ignored
  14637. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14638. sse::SSEMessage msg;
  14639. int retry_ms = 3000;
  14640. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14641. EXPECT_EQ(msg.data, "");
  14642. EXPECT_EQ(msg.event, "message");
  14643. }
  14644. // Test: Space after colon is optional
  14645. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14646. sse::SSEMessage msg1, msg2;
  14647. int retry_ms = 3000;
  14648. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14649. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14650. EXPECT_EQ(msg1.data, "hello");
  14651. EXPECT_EQ(msg2.data, "hello");
  14652. }
  14653. // Test: SSEMessage clear
  14654. TEST_F(SSEParsingTest, MessageClear) {
  14655. sse::SSEMessage msg;
  14656. msg.event = "custom";
  14657. msg.data = "some data";
  14658. msg.id = "123";
  14659. msg.clear();
  14660. EXPECT_EQ(msg.event, "message");
  14661. EXPECT_EQ(msg.data, "");
  14662. EXPECT_EQ(msg.id, "");
  14663. }
  14664. // Test: Complete event parsing
  14665. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14666. sse::SSEMessage msg;
  14667. int retry_ms = 3000;
  14668. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14669. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14670. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14671. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14672. // Blank line ends event
  14673. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14674. EXPECT_EQ(msg.event, "notification");
  14675. EXPECT_EQ(msg.id, "evt-42");
  14676. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14677. EXPECT_EQ(retry_ms, 1000);
  14678. }
  14679. //==============================================================================
  14680. // Integration Tests with Server
  14681. //==============================================================================
  14682. class SSEIntegrationTest : public ::testing::Test {
  14683. protected:
  14684. void SetUp() override {
  14685. stop_server_.store(false);
  14686. events_.clear();
  14687. server_ = httplib::detail::make_unique<Server>();
  14688. setup_server();
  14689. start_server();
  14690. }
  14691. void TearDown() override {
  14692. stop_server_.store(true);
  14693. event_cv_.notify_all();
  14694. server_->stop();
  14695. if (server_thread_.joinable()) { server_thread_.join(); }
  14696. }
  14697. void setup_server() {
  14698. // Simple SSE endpoint
  14699. server_->Get("/events", [this](const Request &req, Response &res) {
  14700. auto last_id = req.get_header_value("Last-Event-ID");
  14701. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14702. res.set_chunked_content_provider(
  14703. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14704. std::unique_lock<std::mutex> lock(event_mutex_);
  14705. if (event_cv_.wait_for(
  14706. lock, std::chrono::milliseconds(200), [this] {
  14707. return !events_.empty() || stop_server_.load();
  14708. })) {
  14709. if (stop_server_.load()) { return false; }
  14710. if (!events_.empty()) {
  14711. std::string event = events_.front();
  14712. events_.erase(events_.begin());
  14713. sink.write(event.data(), event.size());
  14714. return true;
  14715. }
  14716. }
  14717. return !stop_server_.load();
  14718. });
  14719. });
  14720. // Endpoint that returns error
  14721. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14722. res.status = 500;
  14723. res.set_content("Internal Server Error", "text/plain");
  14724. });
  14725. // Endpoint for custom event types
  14726. server_->Get("/custom-events", [](const Request &, Response &res) {
  14727. res.set_chunked_content_provider(
  14728. "text/event-stream", [](size_t offset, DataSink &sink) {
  14729. if (offset == 0) {
  14730. std::string event = "event: update\ndata: updated\n\n"
  14731. "event: delete\ndata: deleted\n\n";
  14732. sink.write(event.data(), event.size());
  14733. }
  14734. return false; // End stream after sending
  14735. });
  14736. });
  14737. }
  14738. void start_server() {
  14739. port_ = server_->bind_to_any_port(HOST);
  14740. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14741. // Wait for server to start
  14742. while (!server_->is_running()) {
  14743. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14744. }
  14745. }
  14746. int get_port() const { return port_; }
  14747. void send_event(const std::string &event) {
  14748. std::lock_guard<std::mutex> lock(event_mutex_);
  14749. events_.push_back(event);
  14750. event_cv_.notify_all();
  14751. }
  14752. std::unique_ptr<Server> server_;
  14753. std::thread server_thread_;
  14754. std::mutex event_mutex_;
  14755. std::condition_variable event_cv_;
  14756. std::vector<std::string> events_;
  14757. std::atomic<bool> stop_server_{false};
  14758. std::string last_received_event_id_;
  14759. int port_ = 0;
  14760. };
  14761. // Test: Successful connection and on_open callback
  14762. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14763. // Add a simple endpoint that sends one event and closes
  14764. server_->Get("/simple-event", [](const Request &, Response &res) {
  14765. res.set_chunked_content_provider(
  14766. "text/event-stream", [](size_t offset, DataSink &sink) {
  14767. if (offset == 0) {
  14768. std::string event = "data: hello\n\n";
  14769. sink.write(event.data(), event.size());
  14770. }
  14771. return false; // Close stream after sending
  14772. });
  14773. });
  14774. Client client("localhost", get_port());
  14775. sse::SSEClient sse(client, "/simple-event");
  14776. std::atomic<bool> open_called{false};
  14777. std::atomic<bool> message_received{false};
  14778. sse.on_open([&open_called]() { open_called.store(true); });
  14779. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14780. if (msg.data == "hello") { message_received.store(true); }
  14781. });
  14782. sse.set_reconnect_interval(100);
  14783. sse.set_max_reconnect_attempts(1);
  14784. // Start async
  14785. sse.start_async();
  14786. // Wait for message to be processed
  14787. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14788. sse.stop();
  14789. EXPECT_TRUE(open_called.load());
  14790. EXPECT_TRUE(message_received.load());
  14791. }
  14792. // Test: on_message callback
  14793. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14794. // Endpoint that sends multiple events then closes
  14795. server_->Get("/multi-event", [](const Request &, Response &res) {
  14796. res.set_chunked_content_provider(
  14797. "text/event-stream", [](size_t offset, DataSink &sink) {
  14798. if (offset == 0) {
  14799. std::string events = "data: message1\n\ndata: message2\n\n";
  14800. sink.write(events.data(), events.size());
  14801. }
  14802. return false;
  14803. });
  14804. });
  14805. Client client("localhost", get_port());
  14806. sse::SSEClient sse(client, "/multi-event");
  14807. std::vector<std::string> received_messages;
  14808. std::mutex messages_mutex;
  14809. sse.on_message([&](const sse::SSEMessage &msg) {
  14810. std::lock_guard<std::mutex> lock(messages_mutex);
  14811. received_messages.push_back(msg.data);
  14812. });
  14813. sse.set_reconnect_interval(100);
  14814. sse.set_max_reconnect_attempts(1);
  14815. sse.start_async();
  14816. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14817. sse.stop();
  14818. std::lock_guard<std::mutex> lock(messages_mutex);
  14819. EXPECT_GE(received_messages.size(), 2u);
  14820. if (received_messages.size() >= 2) {
  14821. EXPECT_EQ(received_messages[0], "message1");
  14822. EXPECT_EQ(received_messages[1], "message2");
  14823. }
  14824. }
  14825. // Test: on_event for specific types
  14826. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14827. Client client("localhost", get_port());
  14828. sse::SSEClient sse(client, "/custom-events");
  14829. std::atomic<bool> update_received{false};
  14830. std::atomic<bool> delete_received{false};
  14831. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14832. if (msg.data == "updated") { update_received.store(true); }
  14833. });
  14834. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14835. if (msg.data == "deleted") { delete_received.store(true); }
  14836. });
  14837. sse.set_max_reconnect_attempts(1);
  14838. sse.start_async();
  14839. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14840. sse.stop();
  14841. EXPECT_TRUE(update_received.load());
  14842. EXPECT_TRUE(delete_received.load());
  14843. }
  14844. // Test: on_error callback on connection failure
  14845. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14846. // Connect to a non-existent port
  14847. Client client("localhost", 59999);
  14848. sse::SSEClient sse(client, "/events");
  14849. std::atomic<bool> error_called{false};
  14850. Error received_error = Error::Success;
  14851. sse.on_error([&](Error err) {
  14852. error_called.store(true);
  14853. received_error = err;
  14854. });
  14855. sse.set_reconnect_interval(50);
  14856. sse.set_max_reconnect_attempts(1);
  14857. sse.start_async();
  14858. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14859. sse.stop();
  14860. EXPECT_TRUE(error_called.load());
  14861. EXPECT_NE(received_error, Error::Success);
  14862. }
  14863. // Test: Last-Event-ID header sent on reconnect
  14864. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14865. // Endpoint that sends event with ID
  14866. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14867. res.set_chunked_content_provider(
  14868. "text/event-stream", [](size_t offset, DataSink &sink) {
  14869. if (offset == 0) {
  14870. std::string event = "id: evt-123\ndata: test\n\n";
  14871. sink.write(event.data(), event.size());
  14872. }
  14873. return false;
  14874. });
  14875. });
  14876. Client client("localhost", get_port());
  14877. sse::SSEClient sse(client, "/event-with-id");
  14878. std::atomic<bool> id_received{false};
  14879. sse.on_message([&](const sse::SSEMessage &msg) {
  14880. if (!msg.id.empty()) { id_received.store(true); }
  14881. });
  14882. sse.set_reconnect_interval(100);
  14883. sse.set_max_reconnect_attempts(1);
  14884. sse.start_async();
  14885. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14886. sse.stop();
  14887. EXPECT_TRUE(id_received.load());
  14888. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14889. }
  14890. // Test: Manual stop
  14891. TEST_F(SSEIntegrationTest, ManualStop) {
  14892. // Endpoint that sends one event and stays open briefly
  14893. std::atomic<bool> handler_running{true};
  14894. server_->Get("/stay-open", [&handler_running](const Request &,
  14895. Response &res) {
  14896. res.set_chunked_content_provider(
  14897. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14898. if (offset == 0) {
  14899. std::string event = "data: connected\n\n";
  14900. sink.write(event.data(), event.size());
  14901. }
  14902. // Keep connection open while handler_running is true
  14903. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14904. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14905. }
  14906. return false;
  14907. });
  14908. });
  14909. Client client("localhost", get_port());
  14910. sse::SSEClient sse(client, "/stay-open");
  14911. std::atomic<bool> connected{false};
  14912. sse.on_open([&connected]() { connected.store(true); });
  14913. sse.set_reconnect_interval(100);
  14914. sse.set_max_reconnect_attempts(1);
  14915. sse.start_async();
  14916. // Wait for connection to establish
  14917. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14918. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14919. }
  14920. EXPECT_TRUE(connected.load());
  14921. EXPECT_TRUE(sse.is_connected());
  14922. // Signal handler to stop
  14923. handler_running.store(false);
  14924. // Stop SSE client
  14925. sse.stop();
  14926. EXPECT_FALSE(sse.is_connected());
  14927. }
  14928. // Test: SSEClient with custom headers
  14929. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14930. // Setup a server endpoint that checks for custom header
  14931. std::atomic<bool> header_received{false};
  14932. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14933. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14934. header_received.store(true);
  14935. }
  14936. res.set_chunked_content_provider("text/event-stream",
  14937. [](size_t, DataSink &) { return false; });
  14938. });
  14939. Client client("localhost", get_port());
  14940. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14941. sse::SSEClient sse(client, "/header-check", headers);
  14942. sse.set_max_reconnect_attempts(1);
  14943. sse.start_async();
  14944. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14945. sse.stop();
  14946. EXPECT_TRUE(header_received.load());
  14947. }
  14948. // Test: Reconnect interval configuration
  14949. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14950. Client client("localhost", get_port());
  14951. sse::SSEClient sse(client, "/events");
  14952. auto &result = sse.set_reconnect_interval(500);
  14953. // Builder pattern should return reference to self
  14954. EXPECT_EQ(&result, &sse);
  14955. }
  14956. // Test: Max reconnect attempts
  14957. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14958. // Connect to non-existent port to force reconnects
  14959. Client client("localhost", 59998);
  14960. sse::SSEClient sse(client, "/events");
  14961. std::atomic<int> error_count{0};
  14962. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14963. sse.set_reconnect_interval(50);
  14964. sse.set_max_reconnect_attempts(2);
  14965. auto start = std::chrono::steady_clock::now();
  14966. sse.start(); // Blocking call
  14967. auto end = std::chrono::steady_clock::now();
  14968. // Should have stopped after 2 failed attempts
  14969. EXPECT_GE(error_count.load(), 2);
  14970. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14971. auto duration =
  14972. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14973. #ifdef _WIN32
  14974. // Windows is much slower for socket connection failures
  14975. EXPECT_LT(duration.count(), 7000);
  14976. #else
  14977. EXPECT_LT(duration.count(), 1000);
  14978. #endif
  14979. }
  14980. // Test: Multi-line data in integration
  14981. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14982. // Endpoint with multi-line data
  14983. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14984. res.set_chunked_content_provider(
  14985. "text/event-stream", [](size_t offset, DataSink &sink) {
  14986. if (offset == 0) {
  14987. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14988. sink.write(event.data(), event.size());
  14989. }
  14990. return false;
  14991. });
  14992. });
  14993. Client client("localhost", get_port());
  14994. sse::SSEClient sse(client, "/multiline-data");
  14995. std::string received_data;
  14996. std::mutex data_mutex;
  14997. sse.on_message([&](const sse::SSEMessage &msg) {
  14998. std::lock_guard<std::mutex> lock(data_mutex);
  14999. received_data = msg.data;
  15000. });
  15001. sse.set_reconnect_interval(100);
  15002. sse.set_max_reconnect_attempts(1);
  15003. sse.start_async();
  15004. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15005. sse.stop();
  15006. std::lock_guard<std::mutex> lock(data_mutex);
  15007. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15008. }
  15009. // Test: Auto-reconnect after server disconnection
  15010. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15011. std::atomic<int> connection_count{0};
  15012. std::atomic<int> message_count{0};
  15013. // Endpoint that sends one event and closes, forcing reconnect
  15014. server_->Get("/reconnect-test",
  15015. [&connection_count](const Request &, Response &res) {
  15016. connection_count.fetch_add(1);
  15017. res.set_chunked_content_provider(
  15018. "text/event-stream", [](size_t offset, DataSink &sink) {
  15019. if (offset == 0) {
  15020. std::string event = "data: hello\n\n";
  15021. sink.write(event.data(), event.size());
  15022. }
  15023. return false; // Close connection after sending
  15024. });
  15025. });
  15026. Client client("localhost", get_port());
  15027. sse::SSEClient sse(client, "/reconnect-test");
  15028. sse.on_message([&message_count](const sse::SSEMessage &) {
  15029. message_count.fetch_add(1);
  15030. });
  15031. sse.set_reconnect_interval(100);
  15032. sse.set_max_reconnect_attempts(3);
  15033. sse.start_async();
  15034. // Wait long enough for multiple reconnects
  15035. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15036. sse.stop();
  15037. // Should have connected multiple times (initial + reconnects)
  15038. EXPECT_GE(connection_count.load(), 2);
  15039. // Should have received messages from multiple connections
  15040. EXPECT_GE(message_count.load(), 2);
  15041. }
  15042. // Test: Last-Event-ID sent on reconnect
  15043. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15044. std::atomic<int> connection_count{0};
  15045. std::vector<std::string> received_last_event_ids;
  15046. std::mutex id_mutex;
  15047. // Endpoint that checks Last-Event-ID header and sends event with ID
  15048. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15049. int conn = connection_count.fetch_add(1);
  15050. // Capture the Last-Event-ID header from each connection
  15051. {
  15052. std::lock_guard<std::mutex> lock(id_mutex);
  15053. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15054. }
  15055. res.set_chunked_content_provider(
  15056. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15057. if (offset == 0) {
  15058. std::string event =
  15059. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15060. sink.write(event.data(), event.size());
  15061. }
  15062. return false;
  15063. });
  15064. });
  15065. Client client("localhost", get_port());
  15066. sse::SSEClient sse(client, "/reconnect-with-id");
  15067. sse.set_reconnect_interval(100);
  15068. sse.set_max_reconnect_attempts(3);
  15069. sse.start_async();
  15070. // Wait for at least 2 connections
  15071. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15072. sse.stop();
  15073. // Verify behavior
  15074. std::lock_guard<std::mutex> lock(id_mutex);
  15075. EXPECT_GE(received_last_event_ids.size(), 2u);
  15076. // First connection should have no Last-Event-ID
  15077. if (!received_last_event_ids.empty()) {
  15078. EXPECT_EQ(received_last_event_ids[0], "");
  15079. }
  15080. // Second connection should have Last-Event-ID from first connection
  15081. if (received_last_event_ids.size() >= 2) {
  15082. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15083. }
  15084. }
  15085. // Test: set_headers updates headers used on reconnect
  15086. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15087. std::vector<std::string> received_tokens;
  15088. std::mutex token_mutex;
  15089. // Endpoint that captures Authorization header
  15090. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15091. {
  15092. std::lock_guard<std::mutex> lock(token_mutex);
  15093. received_tokens.push_back(req.get_header_value("Authorization"));
  15094. }
  15095. res.set_chunked_content_provider(
  15096. "text/event-stream", [](size_t offset, DataSink &sink) {
  15097. if (offset == 0) {
  15098. std::string event = "data: hello\n\n";
  15099. sink.write(event.data(), event.size());
  15100. }
  15101. return false; // Close connection to trigger reconnect
  15102. });
  15103. });
  15104. Client client("localhost", get_port());
  15105. Headers headers = {{"Authorization", "Bearer old-token"}};
  15106. sse::SSEClient sse(client, "/auth-check", headers);
  15107. // Update headers on each successful connection
  15108. sse.on_open(
  15109. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15110. sse.set_reconnect_interval(100);
  15111. sse.set_max_reconnect_attempts(3);
  15112. sse.start_async();
  15113. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15114. sse.stop();
  15115. std::lock_guard<std::mutex> lock(token_mutex);
  15116. ASSERT_GE(received_tokens.size(), 2u);
  15117. // First connection uses original header
  15118. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15119. // Second connection uses updated header from set_headers
  15120. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15121. }
  15122. // Test: 401 allows reconnection (so on_error can refresh headers)
  15123. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15124. std::atomic<int> connection_count{0};
  15125. // Endpoint: returns 401 on first attempt, 200 on second
  15126. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15127. int conn = connection_count.fetch_add(1);
  15128. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15129. res.status = StatusCode::Unauthorized_401;
  15130. res.set_content("Unauthorized", "text/plain");
  15131. return;
  15132. }
  15133. res.set_chunked_content_provider(
  15134. "text/event-stream", [](size_t offset, DataSink &sink) {
  15135. if (offset == 0) {
  15136. std::string event = "data: authenticated\n\n";
  15137. sink.write(event.data(), event.size());
  15138. }
  15139. return false;
  15140. });
  15141. });
  15142. Client client("localhost", get_port());
  15143. Headers headers = {{"Authorization", "Bearer expired"}};
  15144. sse::SSEClient sse(client, "/auth-retry", headers);
  15145. std::atomic<bool> message_received{false};
  15146. // Refresh token on error
  15147. sse.on_error(
  15148. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15149. sse.on_message([&](const sse::SSEMessage &msg) {
  15150. if (msg.data == "authenticated") { message_received.store(true); }
  15151. });
  15152. sse.set_reconnect_interval(100);
  15153. sse.set_max_reconnect_attempts(3);
  15154. sse.start_async();
  15155. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15156. sse.stop();
  15157. // Should have reconnected after 401 and succeeded with new token
  15158. EXPECT_GE(connection_count.load(), 2);
  15159. EXPECT_TRUE(message_received.load());
  15160. }
  15161. TEST(Issue2318Test, EmptyHostString) {
  15162. {
  15163. httplib::Client cli_empty("", PORT);
  15164. auto res = cli_empty.Get("/");
  15165. ASSERT_FALSE(res);
  15166. EXPECT_EQ(httplib::Error::Connection, res.error());
  15167. }
  15168. {
  15169. httplib::Client cli(" ", PORT);
  15170. auto res = cli.Get("/");
  15171. ASSERT_FALSE(res);
  15172. EXPECT_EQ(httplib::Error::Connection, res.error());
  15173. }
  15174. }
  15175. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15176. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15177. Server svr;
  15178. // Set a small payload limit (1KB)
  15179. svr.set_payload_max_length(1024);
  15180. svr.Post("/test", [&](const Request &req, Response &res) {
  15181. res.set_content("Body size: " + std::to_string(req.body.size()),
  15182. "text/plain");
  15183. });
  15184. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15185. auto se = detail::scope_exit([&] {
  15186. svr.stop();
  15187. listen_thread.join();
  15188. });
  15189. svr.wait_until_ready();
  15190. // Create data that compresses well but exceeds limit when decompressed
  15191. // 8KB of repeated null bytes compresses to a very small size
  15192. std::string original_data(8 * 1024, '\0');
  15193. // Compress the data using gzip
  15194. std::string compressed_data;
  15195. detail::gzip_compressor compressor;
  15196. compressor.compress(original_data.data(), original_data.size(), true,
  15197. [&](const char *data, size_t size) {
  15198. compressed_data.append(data, size);
  15199. return true;
  15200. });
  15201. // Verify compression worked (compressed should be much smaller)
  15202. ASSERT_LT(compressed_data.size(), original_data.size());
  15203. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15204. // Send compressed data with Content-Encoding: gzip
  15205. Client cli(HOST, PORT);
  15206. Headers headers = {{"Content-Encoding", "gzip"}};
  15207. auto res =
  15208. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15209. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15210. ASSERT_TRUE(res);
  15211. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15212. }
  15213. #endif
  15214. // ============================================================================
  15215. // OpenSSL-Specific Tests
  15216. // ============================================================================
  15217. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15218. X509 *readCertificate(const std::string &strFileName) {
  15219. std::ifstream inStream(strFileName);
  15220. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15221. std::istreambuf_iterator<char>());
  15222. if (strCertPEM.empty()) return (nullptr);
  15223. BIO *pbCert = BIO_new(BIO_s_mem());
  15224. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15225. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15226. BIO_free(pbCert);
  15227. return (pCert);
  15228. }
  15229. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15230. std::ifstream inStream(strFileName);
  15231. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15232. std::istreambuf_iterator<char>());
  15233. if (strPrivateKeyPEM.empty()) return (nullptr);
  15234. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15235. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15236. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15237. BIO_free(pbPrivKey);
  15238. return (pPrivateKey);
  15239. }
  15240. TEST(BindServerTest, UpdateCerts) {
  15241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15242. int port = svr.bind_to_any_port("0.0.0.0");
  15243. ASSERT_TRUE(svr.is_valid());
  15244. ASSERT_TRUE(port > 0);
  15245. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15246. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15247. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15248. ASSERT_TRUE(cert != nullptr);
  15249. ASSERT_TRUE(ca_cert != nullptr);
  15250. ASSERT_TRUE(key != nullptr);
  15251. X509_STORE *cert_store = X509_STORE_new();
  15252. X509_STORE_add_cert(cert_store, ca_cert);
  15253. // svr.update_certs(cert, key, cert_store); // deprecated
  15254. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15255. CLIENT_CA_CERT_FILE);
  15256. ASSERT_TRUE(svr.is_valid());
  15257. svr.stop();
  15258. X509_STORE_free(cert_store);
  15259. X509_free(cert);
  15260. X509_free(ca_cert);
  15261. EVP_PKEY_free(key);
  15262. }
  15263. // Test that update_certs() updates client CA list correctly
  15264. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15265. // Start with file-based constructor
  15266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15267. ASSERT_TRUE(svr.is_valid());
  15268. // Initially no client CA list should be set
  15269. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15270. ASSERT_TRUE(ssl_ctx != nullptr);
  15271. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15272. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15273. EXPECT_EQ(0, count_before);
  15274. // Now update with client CA (PEM string)
  15275. std::string cert_pem, key_pem, ca_pem;
  15276. read_file(SERVER_CERT_FILE, cert_pem);
  15277. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15278. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15279. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15280. ASSERT_TRUE(svr.is_valid());
  15281. // Now client CA list should be set
  15282. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15283. ASSERT_TRUE(ca_list_after != nullptr);
  15284. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15285. }
  15286. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15287. // Test that the file-path SSLServer constructor properly sets the client CA
  15288. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15290. ASSERT_TRUE(svr.is_valid());
  15291. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15292. ASSERT_TRUE(ssl_ctx != nullptr);
  15293. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15294. ASSERT_TRUE(ca_list != nullptr);
  15295. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15296. }
  15297. #endif
  15298. // ============================================================================
  15299. // MbedTLS-Specific Tests
  15300. // ============================================================================
  15301. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15302. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15303. using namespace httplib::tls;
  15304. // Track if callback was invoked
  15305. bool callback_invoked = false;
  15306. // The callback receives void* ctx which is actually MbedTlsContext*
  15307. // We can access the mbedtls_ssl_config via the context
  15308. auto setup_callback = [&callback_invoked](void *ctx) {
  15309. callback_invoked = true;
  15310. // Cast to MbedTlsContext* to access the ssl config
  15311. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15312. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15313. // Use static variables to hold certificate data (simplified for test)
  15314. static mbedtls_x509_crt own_cert;
  15315. static mbedtls_pk_context own_key;
  15316. static mbedtls_x509_crt ca_chain;
  15317. static bool initialized = false;
  15318. if (!initialized) {
  15319. mbedtls_x509_crt_init(&own_cert);
  15320. mbedtls_pk_init(&own_key);
  15321. mbedtls_x509_crt_init(&ca_chain);
  15322. // Load server certificate
  15323. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15324. return false;
  15325. }
  15326. // Load server private key
  15327. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15328. #if MBEDTLS_VERSION_MAJOR >= 3
  15329. ,
  15330. mbedtls_ctr_drbg_random, nullptr
  15331. #endif
  15332. ) != 0) {
  15333. return false;
  15334. }
  15335. // Load CA chain for client verification
  15336. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15337. return false;
  15338. }
  15339. initialized = true;
  15340. }
  15341. // Configure the SSL config
  15342. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15343. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15344. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15345. // Set minimum TLS version using mbedTLS native API
  15346. #if MBEDTLS_VERSION_MAJOR >= 3
  15347. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15348. #else
  15349. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15350. MBEDTLS_SSL_MINOR_VERSION_3);
  15351. #endif
  15352. return true;
  15353. };
  15354. SSLServer svr(setup_callback);
  15355. ASSERT_TRUE(svr.is_valid());
  15356. ASSERT_TRUE(callback_invoked);
  15357. svr.Get("/test", [&](const Request &req, Response &res) {
  15358. res.set_content("test", "text/plain");
  15359. auto cert = req.peer_cert();
  15360. ASSERT_TRUE(static_cast<bool>(cert));
  15361. auto common_name = cert.subject_cn();
  15362. EXPECT_EQ("Common Name", common_name);
  15363. });
  15364. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15365. auto se = detail::scope_exit([&] {
  15366. svr.stop();
  15367. t.join();
  15368. ASSERT_FALSE(svr.is_running());
  15369. });
  15370. svr.wait_until_ready();
  15371. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15372. cli.enable_server_certificate_verification(false);
  15373. cli.set_connection_timeout(30);
  15374. auto res = cli.Get("/test");
  15375. ASSERT_TRUE(res);
  15376. ASSERT_EQ(StatusCode::OK_200, res->status);
  15377. }
  15378. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15379. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15380. // keep-alive SSL session, which reads through that config in
  15381. // mbedtls_ssl_close_notify.
  15382. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15384. ASSERT_TRUE(svr.is_valid());
  15385. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15386. res.set_content("test", "text/plain");
  15387. });
  15388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15389. auto se = detail::scope_exit([&] {
  15390. svr.stop();
  15391. t.join();
  15392. ASSERT_FALSE(svr.is_running());
  15393. });
  15394. svr.wait_until_ready();
  15395. {
  15396. SSLClient cli(HOST, PORT);
  15397. cli.enable_server_certificate_verification(false);
  15398. cli.set_keep_alive(true);
  15399. auto res = cli.Get("/test");
  15400. ASSERT_TRUE(res);
  15401. ASSERT_EQ(StatusCode::OK_200, res->status);
  15402. // cli is destructed here with the keep-alive SSL session still open.
  15403. }
  15404. }
  15405. #endif
  15406. // WebSocket Tests
  15407. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15408. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15409. // defining the meaning of these bits has been negotiated.
  15410. auto make_frame = [](uint8_t first_byte) {
  15411. std::string frame;
  15412. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15413. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15414. frame += "Hello";
  15415. return frame;
  15416. };
  15417. // RSV1 set (0x40)
  15418. {
  15419. detail::BufferStream strm;
  15420. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15421. ws::Opcode opcode;
  15422. std::string payload;
  15423. bool fin;
  15424. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15425. false, 1024));
  15426. }
  15427. // RSV2 set (0x20)
  15428. {
  15429. detail::BufferStream strm;
  15430. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15431. ws::Opcode opcode;
  15432. std::string payload;
  15433. bool fin;
  15434. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15435. false, 1024));
  15436. }
  15437. // RSV3 set (0x10)
  15438. {
  15439. detail::BufferStream strm;
  15440. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15441. ws::Opcode opcode;
  15442. std::string payload;
  15443. bool fin;
  15444. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15445. false, 1024));
  15446. }
  15447. // No RSV bits set - should succeed
  15448. {
  15449. detail::BufferStream strm;
  15450. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15451. ws::Opcode opcode;
  15452. std::string payload;
  15453. bool fin;
  15454. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15455. false, 1024));
  15456. EXPECT_EQ(ws::Opcode::Text, opcode);
  15457. EXPECT_EQ("Hello", payload);
  15458. EXPECT_TRUE(fin);
  15459. }
  15460. }
  15461. TEST(WebSocketTest, ControlFrameValidation) {
  15462. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15463. // payload length <= 125.
  15464. // Ping with FIN=0 - must be rejected
  15465. {
  15466. detail::BufferStream strm;
  15467. std::string frame;
  15468. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15469. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15470. strm.write(frame.data(), frame.size());
  15471. ws::Opcode opcode;
  15472. std::string payload;
  15473. bool fin;
  15474. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15475. false, 1024));
  15476. }
  15477. // Close with FIN=0 - must be rejected
  15478. {
  15479. detail::BufferStream strm;
  15480. std::string frame;
  15481. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15482. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15483. strm.write(frame.data(), frame.size());
  15484. ws::Opcode opcode;
  15485. std::string payload;
  15486. bool fin;
  15487. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15488. false, 1024));
  15489. }
  15490. // Ping with payload_len=126 (extended length) - must be rejected
  15491. {
  15492. detail::BufferStream strm;
  15493. std::string frame;
  15494. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15495. frame += static_cast<char>(126); // payload_len=126 (>125)
  15496. frame += static_cast<char>(0x00); // extended length high byte
  15497. frame += static_cast<char>(126); // extended length low byte
  15498. frame += std::string(126, 'x');
  15499. strm.write(frame.data(), frame.size());
  15500. ws::Opcode opcode;
  15501. std::string payload;
  15502. bool fin;
  15503. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15504. false, 1024));
  15505. }
  15506. // Ping with FIN=1 and payload_len=125 - should succeed
  15507. {
  15508. detail::BufferStream strm;
  15509. std::string frame;
  15510. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15511. frame += static_cast<char>(125); // payload_len=125
  15512. frame += std::string(125, 'x');
  15513. strm.write(frame.data(), frame.size());
  15514. ws::Opcode opcode;
  15515. std::string payload;
  15516. bool fin;
  15517. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15518. false, 1024));
  15519. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15520. EXPECT_EQ(125u, payload.size());
  15521. EXPECT_TRUE(fin);
  15522. }
  15523. }
  15524. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15525. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15526. // length MUST be 0.
  15527. // MSB set - must be rejected
  15528. {
  15529. detail::BufferStream strm;
  15530. std::string frame;
  15531. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15532. frame += static_cast<char>(127); // 64-bit extended length
  15533. frame += static_cast<char>(0x80); // MSB set (invalid)
  15534. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15535. strm.write(frame.data(), frame.size());
  15536. ws::Opcode opcode;
  15537. std::string payload;
  15538. bool fin;
  15539. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15540. false, 1024));
  15541. }
  15542. // MSB clear - should pass length parsing (will be rejected by max_len,
  15543. // but that's a different check; use a small length to verify)
  15544. {
  15545. detail::BufferStream strm;
  15546. std::string frame;
  15547. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15548. frame += static_cast<char>(127); // 64-bit extended length
  15549. frame += std::string(7, '\0'); // high bytes = 0
  15550. frame += static_cast<char>(0x03); // length = 3
  15551. frame += "abc";
  15552. strm.write(frame.data(), frame.size());
  15553. ws::Opcode opcode;
  15554. std::string payload;
  15555. bool fin;
  15556. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15557. false, 1024));
  15558. EXPECT_EQ(ws::Opcode::Text, opcode);
  15559. EXPECT_EQ("abc", payload);
  15560. }
  15561. }
  15562. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15563. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15564. // Valid UTF-8
  15565. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15566. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15567. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15568. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15569. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15570. // Invalid UTF-8
  15571. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15572. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15573. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15574. EXPECT_FALSE(
  15575. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15576. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15577. }
  15578. TEST(WebSocketTest, ConnectAndDisconnect) {
  15579. Server svr;
  15580. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15581. std::string msg;
  15582. while (ws.read(msg)) {}
  15583. });
  15584. auto port = svr.bind_to_any_port(HOST);
  15585. std::thread t([&]() { svr.listen_after_bind(); });
  15586. svr.wait_until_ready();
  15587. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15588. ASSERT_TRUE(client.connect());
  15589. EXPECT_TRUE(client.is_open());
  15590. client.close();
  15591. EXPECT_FALSE(client.is_open());
  15592. svr.stop();
  15593. t.join();
  15594. }
  15595. TEST(WebSocketTest, ValidURL) {
  15596. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15597. EXPECT_TRUE(ws1.is_valid());
  15598. ws::WebSocketClient ws2("ws://example.com/path");
  15599. EXPECT_TRUE(ws2.is_valid());
  15600. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15601. EXPECT_TRUE(ws3.is_valid());
  15602. #ifdef CPPHTTPLIB_SSL_ENABLED
  15603. ws::WebSocketClient wss1("wss://example.com/path");
  15604. EXPECT_TRUE(wss1.is_valid());
  15605. ws::WebSocketClient wss2("wss://example.com:443/path");
  15606. EXPECT_TRUE(wss2.is_valid());
  15607. #endif
  15608. }
  15609. TEST(WebSocketTest, InvalidURL) {
  15610. // No scheme
  15611. ws::WebSocketClient ws1("localhost:8080/path");
  15612. EXPECT_FALSE(ws1.is_valid());
  15613. // No path
  15614. ws::WebSocketClient ws2("ws://localhost:8080");
  15615. EXPECT_FALSE(ws2.is_valid());
  15616. // Empty string
  15617. ws::WebSocketClient ws3("");
  15618. EXPECT_FALSE(ws3.is_valid());
  15619. // Missing host
  15620. ws::WebSocketClient ws4("ws://:8080/path");
  15621. EXPECT_FALSE(ws4.is_valid());
  15622. // Port number overflow — should not crash
  15623. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15624. EXPECT_FALSE(ws5.is_valid());
  15625. // Port out of range
  15626. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15627. EXPECT_FALSE(ws6.is_valid());
  15628. }
  15629. TEST(WebSocketTest, UnsupportedScheme) {
  15630. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15631. ws::WebSocketClient ws1("http://localhost:8080/path");
  15632. EXPECT_FALSE(ws1.is_valid());
  15633. ws::WebSocketClient ws2("https://localhost:8080/path");
  15634. EXPECT_FALSE(ws2.is_valid());
  15635. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15636. EXPECT_FALSE(ws3.is_valid());
  15637. #else
  15638. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15639. std::invalid_argument);
  15640. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15641. std::invalid_argument);
  15642. #endif
  15643. }
  15644. TEST(WebSocketTest, ConnectWhenInvalid) {
  15645. ws::WebSocketClient ws("not a valid url");
  15646. EXPECT_FALSE(ws.is_valid());
  15647. EXPECT_FALSE(ws.connect());
  15648. }
  15649. TEST(WebSocketTest, DefaultPort) {
  15650. ws::WebSocketClient ws1("ws://example.com/path");
  15651. EXPECT_TRUE(ws1.is_valid());
  15652. // ws:// defaults to port 80 (verified by successful parse)
  15653. #ifdef CPPHTTPLIB_SSL_ENABLED
  15654. ws::WebSocketClient ws2("wss://example.com/path");
  15655. EXPECT_TRUE(ws2.is_valid());
  15656. // wss:// defaults to port 443 (verified by successful parse)
  15657. #endif
  15658. }
  15659. TEST(WebSocketTest, IPv6LiteralAddress) {
  15660. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15661. EXPECT_TRUE(ws1.is_valid());
  15662. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15663. EXPECT_TRUE(ws2.is_valid());
  15664. }
  15665. TEST(WebSocketTest, ComplexPath) {
  15666. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15667. EXPECT_TRUE(ws1.is_valid());
  15668. ws::WebSocketClient ws2("ws://localhost:8080/");
  15669. EXPECT_TRUE(ws2.is_valid());
  15670. }
  15671. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15672. Server svr;
  15673. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15674. std::string msg;
  15675. while (ws.read(msg)) {}
  15676. });
  15677. auto port = svr.bind_to_any_port(HOST);
  15678. std::thread t([&]() { svr.listen_after_bind(); });
  15679. svr.wait_until_ready();
  15680. auto another_host = "example.com";
  15681. auto wrong_ip = "192.0.2.1";
  15682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15683. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15684. ASSERT_TRUE(client.connect());
  15685. EXPECT_TRUE(client.is_open());
  15686. client.close();
  15687. svr.stop();
  15688. t.join();
  15689. }
  15690. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15691. Server svr;
  15692. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15693. std::string msg;
  15694. while (ws.read(msg)) {}
  15695. });
  15696. auto port = svr.bind_to_any_port(HOST);
  15697. std::thread t([&]() { svr.listen_after_bind(); });
  15698. svr.wait_until_ready();
  15699. auto wrong_ip = "192.0.2.1";
  15700. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15701. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15702. client.set_connection_timeout(1);
  15703. client.set_read_timeout(1);
  15704. client.set_write_timeout(1);
  15705. EXPECT_FALSE(client.connect());
  15706. EXPECT_FALSE(client.is_open());
  15707. svr.stop();
  15708. t.join();
  15709. }
  15710. class WebSocketIntegrationTest : public ::testing::Test {
  15711. protected:
  15712. void SetUp() override {
  15713. server_ = httplib::detail::make_unique<Server>();
  15714. setup_server();
  15715. start_server();
  15716. }
  15717. void TearDown() override {
  15718. server_->stop();
  15719. if (server_thread_.joinable()) { server_thread_.join(); }
  15720. }
  15721. void setup_server() {
  15722. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15723. std::string msg;
  15724. ws::ReadResult ret;
  15725. while ((ret = ws.read(msg))) {
  15726. if (ret == ws::Binary) {
  15727. ws.send(msg.data(), msg.size());
  15728. } else {
  15729. ws.send(msg);
  15730. }
  15731. }
  15732. });
  15733. server_->WebSocket("/ws-echo-string",
  15734. [](const Request &, ws::WebSocket &ws) {
  15735. std::string msg;
  15736. while (ws.read(msg)) {
  15737. ws.send("echo: " + msg);
  15738. }
  15739. });
  15740. server_->WebSocket(
  15741. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15742. // Echo back request metadata
  15743. ws.send("path:" + req.path);
  15744. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15745. std::string msg;
  15746. while (ws.read(msg)) {}
  15747. });
  15748. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15749. std::string msg;
  15750. ws.read(msg); // wait for a message
  15751. ws.close();
  15752. });
  15753. server_->WebSocket("/ws-close-status",
  15754. [](const Request &, ws::WebSocket &ws) {
  15755. std::string msg;
  15756. ws.read(msg); // wait for a message
  15757. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15758. });
  15759. server_->WebSocket(
  15760. "/ws-subprotocol",
  15761. [](const Request &, ws::WebSocket &ws) {
  15762. std::string msg;
  15763. while (ws.read(msg)) {
  15764. ws.send(msg);
  15765. }
  15766. },
  15767. [](const std::vector<std::string> &protocols) -> std::string {
  15768. for (const auto &p : protocols) {
  15769. if (p == "graphql-ws") { return p; }
  15770. }
  15771. return "";
  15772. });
  15773. }
  15774. void start_server() {
  15775. port_ = server_->bind_to_any_port(HOST);
  15776. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15777. server_->wait_until_ready();
  15778. }
  15779. std::unique_ptr<Server> server_;
  15780. std::thread server_thread_;
  15781. int port_ = 0;
  15782. };
  15783. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15785. "/ws-echo");
  15786. ASSERT_TRUE(client.connect());
  15787. ASSERT_TRUE(client.is_open());
  15788. ASSERT_TRUE(client.send("Hello WebSocket"));
  15789. std::string msg;
  15790. EXPECT_EQ(ws::Text, client.read(msg));
  15791. EXPECT_EQ("Hello WebSocket", msg);
  15792. client.close();
  15793. }
  15794. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15796. "/ws-echo");
  15797. ASSERT_TRUE(client.connect());
  15798. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15799. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15800. std::string msg;
  15801. EXPECT_EQ(ws::Binary, client.read(msg));
  15802. EXPECT_EQ(binary_data, msg);
  15803. client.close();
  15804. }
  15805. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15807. "/ws-echo");
  15808. ASSERT_TRUE(client.connect());
  15809. for (int i = 0; i < 10; i++) {
  15810. auto text = "message " + std::to_string(i);
  15811. ASSERT_TRUE(client.send(text));
  15812. std::string msg;
  15813. ASSERT_TRUE(client.read(msg));
  15814. EXPECT_EQ(text, msg);
  15815. }
  15816. client.close();
  15817. }
  15818. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15820. "/ws-close");
  15821. ASSERT_TRUE(client.connect());
  15822. // Send a message to trigger the server to close
  15823. ASSERT_TRUE(client.send("trigger close"));
  15824. // The server will close, so read should return false
  15825. std::string msg;
  15826. EXPECT_FALSE(client.read(msg));
  15827. EXPECT_FALSE(client.is_open());
  15828. }
  15829. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15831. "/ws-echo");
  15832. ASSERT_TRUE(client.connect());
  15833. // 128KB message
  15834. std::string large_data(128 * 1024, 'X');
  15835. ASSERT_TRUE(client.send(large_data));
  15836. std::string msg;
  15837. ASSERT_TRUE(client.read(msg));
  15838. EXPECT_EQ(large_data, msg);
  15839. client.close();
  15840. }
  15841. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15843. "/ws-echo");
  15844. ASSERT_TRUE(client.connect());
  15845. const int num_threads = 4;
  15846. std::vector<std::thread> threads;
  15847. std::atomic<int> send_count{0};
  15848. for (int t = 0; t < num_threads; t++) {
  15849. threads.emplace_back([&client, &send_count, t]() {
  15850. for (int i = 0; i < 5; i++) {
  15851. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15852. if (client.send(text)) { send_count++; }
  15853. }
  15854. });
  15855. }
  15856. for (auto &th : threads) {
  15857. th.join();
  15858. }
  15859. int received = 0;
  15860. std::string msg;
  15861. while (received < send_count.load()) {
  15862. if (!client.read(msg)) { break; }
  15863. received++;
  15864. }
  15865. EXPECT_EQ(send_count.load(), received);
  15866. client.close();
  15867. }
  15868. TEST_F(WebSocketIntegrationTest, ReadString) {
  15869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15870. "/ws-echo-string");
  15871. ASSERT_TRUE(client.connect());
  15872. ASSERT_TRUE(client.send("hello"));
  15873. std::string msg;
  15874. ASSERT_TRUE(client.read(msg));
  15875. EXPECT_EQ("echo: hello", msg);
  15876. ASSERT_TRUE(client.send("world"));
  15877. ASSERT_TRUE(client.read(msg));
  15878. EXPECT_EQ("echo: world", msg);
  15879. client.close();
  15880. }
  15881. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15882. Headers headers = {{"X-Test-Header", "test-value"}};
  15883. ws::WebSocketClient client(
  15884. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15885. ASSERT_TRUE(client.connect());
  15886. std::string msg;
  15887. ASSERT_TRUE(client.read(msg));
  15888. EXPECT_EQ("path:/ws-request-info", msg);
  15889. ASSERT_TRUE(client.read(msg));
  15890. EXPECT_EQ("header:test-value", msg);
  15891. client.close();
  15892. }
  15893. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15894. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15895. "/ws-echo");
  15896. client.set_read_timeout(1, 0); // 1 second
  15897. ASSERT_TRUE(client.connect());
  15898. // Don't send anything — server echo handler waits for a message,
  15899. // so read() should time out and return false.
  15900. std::string msg;
  15901. EXPECT_FALSE(client.read(msg));
  15902. }
  15903. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15905. "/ws-echo");
  15906. client.set_read_timeout(5, 0);
  15907. ASSERT_TRUE(client.connect());
  15908. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15909. // The server should reject it and close the connection.
  15910. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15911. client.send(oversized);
  15912. // The server's read() should have failed due to payload limit,
  15913. // so our read() should return false (connection closed).
  15914. std::string msg;
  15915. EXPECT_FALSE(client.read(msg));
  15916. }
  15917. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15918. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15919. "/ws-echo");
  15920. client.set_read_timeout(10, 0);
  15921. ASSERT_TRUE(client.connect());
  15922. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15923. // This should succeed.
  15924. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15925. ASSERT_TRUE(client.send(at_limit));
  15926. std::string msg;
  15927. ASSERT_TRUE(client.read(msg));
  15928. EXPECT_EQ(at_limit.size(), msg.size());
  15929. client.close();
  15930. }
  15931. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15933. "/nonexistent");
  15934. EXPECT_FALSE(client.connect());
  15935. EXPECT_FALSE(client.is_open());
  15936. }
  15937. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15939. "/ws-echo");
  15940. ASSERT_TRUE(client.connect());
  15941. ASSERT_TRUE(client.send(""));
  15942. std::string msg;
  15943. EXPECT_EQ(ws::Text, client.read(msg));
  15944. EXPECT_EQ("", msg);
  15945. client.close();
  15946. }
  15947. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15949. "/ws-echo");
  15950. // First connection
  15951. ASSERT_TRUE(client.connect());
  15952. ASSERT_TRUE(client.send("first"));
  15953. std::string msg;
  15954. ASSERT_TRUE(client.read(msg));
  15955. EXPECT_EQ("first", msg);
  15956. client.close();
  15957. EXPECT_FALSE(client.is_open());
  15958. // Reconnect using the same client object
  15959. ASSERT_TRUE(client.connect());
  15960. ASSERT_TRUE(client.is_open());
  15961. ASSERT_TRUE(client.send("second"));
  15962. ASSERT_TRUE(client.read(msg));
  15963. EXPECT_EQ("second", msg);
  15964. client.close();
  15965. }
  15966. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15968. "/ws-close-status");
  15969. ASSERT_TRUE(client.connect());
  15970. // Trigger the server to close with GoingAway status
  15971. ASSERT_TRUE(client.send("trigger"));
  15972. // read() should return false after receiving the close frame
  15973. std::string msg;
  15974. EXPECT_FALSE(client.read(msg));
  15975. EXPECT_FALSE(client.is_open());
  15976. }
  15977. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15979. "/ws-echo");
  15980. ASSERT_TRUE(client.connect());
  15981. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15982. EXPECT_FALSE(client.is_open());
  15983. }
  15984. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15985. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15986. ws::WebSocketClient client(
  15987. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15988. ASSERT_TRUE(client.connect());
  15989. // Server should have selected graphql-ws
  15990. EXPECT_EQ("graphql-ws", client.subprotocol());
  15991. client.close();
  15992. }
  15993. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15994. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15995. ws::WebSocketClient client(
  15996. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15997. ASSERT_TRUE(client.connect());
  15998. // Server should not have selected any subprotocol
  15999. EXPECT_TRUE(client.subprotocol().empty());
  16000. client.close();
  16001. }
  16002. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16003. // Connect without requesting any subprotocol
  16004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16005. "/ws-subprotocol");
  16006. ASSERT_TRUE(client.connect());
  16007. EXPECT_TRUE(client.subprotocol().empty());
  16008. client.close();
  16009. }
  16010. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16011. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16012. "/ws-echo");
  16013. client.set_tcp_nodelay(true);
  16014. client.set_connection_timeout(3, 0);
  16015. bool socket_options_called = false;
  16016. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16017. ASSERT_TRUE(client.connect());
  16018. ASSERT_TRUE(client.is_open());
  16019. EXPECT_TRUE(socket_options_called);
  16020. ASSERT_TRUE(client.send("hello"));
  16021. std::string msg;
  16022. auto result = client.read(msg);
  16023. EXPECT_EQ(result, ws::ReadResult::Text);
  16024. EXPECT_EQ(msg, "hello");
  16025. client.close();
  16026. }
  16027. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16028. Server svr;
  16029. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16030. if (!req.has_header("Authorization")) {
  16031. res.status = StatusCode::Unauthorized_401;
  16032. res.set_content("Unauthorized", "text/plain");
  16033. return Server::HandlerResponse::Handled;
  16034. }
  16035. return Server::HandlerResponse::Unhandled;
  16036. });
  16037. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16038. std::string msg;
  16039. while (ws.read(msg)) {
  16040. ws.send(msg);
  16041. }
  16042. });
  16043. auto port = svr.bind_to_any_port("localhost");
  16044. std::thread t([&]() { svr.listen_after_bind(); });
  16045. svr.wait_until_ready();
  16046. // Without Authorization header - should be rejected before upgrade
  16047. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16048. EXPECT_FALSE(client1.connect());
  16049. // With Authorization header - should succeed
  16050. Headers headers = {{"Authorization", "Bearer token123"}};
  16051. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16052. headers);
  16053. ASSERT_TRUE(client2.connect());
  16054. ASSERT_TRUE(client2.send("hello"));
  16055. std::string msg;
  16056. ASSERT_TRUE(client2.read(msg));
  16057. EXPECT_EQ("hello", msg);
  16058. client2.close();
  16059. svr.stop();
  16060. t.join();
  16061. }
  16062. TEST(WebSocketTest, QueryStringInHandshake) {
  16063. Server svr;
  16064. std::mutex mtx;
  16065. std::string received_target;
  16066. std::string received_token;
  16067. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16068. {
  16069. std::lock_guard<std::mutex> lock(mtx);
  16070. received_target = req.target;
  16071. if (req.has_param("token")) {
  16072. received_token = req.get_param_value("token");
  16073. }
  16074. }
  16075. std::string msg;
  16076. while (ws.read(msg)) {
  16077. ws.send(msg);
  16078. }
  16079. });
  16080. auto port = svr.bind_to_any_port("localhost");
  16081. std::thread t([&]() { svr.listen_after_bind(); });
  16082. svr.wait_until_ready();
  16083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16084. "/ws?token=ABC&session=123");
  16085. ASSERT_TRUE(client.connect());
  16086. // Round-trip ensures the handler has run and captured the request.
  16087. ASSERT_TRUE(client.send("hello"));
  16088. std::string msg;
  16089. ASSERT_TRUE(client.read(msg));
  16090. EXPECT_EQ("hello", msg);
  16091. client.close();
  16092. {
  16093. std::lock_guard<std::mutex> lock(mtx);
  16094. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16095. EXPECT_EQ("ABC", received_token);
  16096. }
  16097. svr.stop();
  16098. t.join();
  16099. }
  16100. TEST(WebSocketTest, HostHeaderInHandshake) {
  16101. Server svr;
  16102. std::mutex mtx;
  16103. std::string received_host;
  16104. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16105. {
  16106. std::lock_guard<std::mutex> lock(mtx);
  16107. received_host = req.get_header_value("Host");
  16108. }
  16109. std::string msg;
  16110. while (ws.read(msg)) {
  16111. ws.send(msg);
  16112. }
  16113. });
  16114. auto port = svr.bind_to_any_port("localhost");
  16115. std::thread t([&]() { svr.listen_after_bind(); });
  16116. svr.wait_until_ready();
  16117. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16118. ASSERT_TRUE(client.connect());
  16119. // Round-trip ensures the handler has run and captured the request.
  16120. ASSERT_TRUE(client.send("hello"));
  16121. std::string msg;
  16122. ASSERT_TRUE(client.read(msg));
  16123. client.close();
  16124. {
  16125. std::lock_guard<std::mutex> lock(mtx);
  16126. // Non-default port must be present in the Host header. Default ports
  16127. // (80/443) are omitted; that logic is covered by
  16128. // MakeHostAndPortStringTest.
  16129. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16130. }
  16131. svr.stop();
  16132. t.join();
  16133. }
  16134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16135. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16136. protected:
  16137. void SetUp() override {
  16138. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16139. SERVER_PRIVATE_KEY_FILE);
  16140. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16141. std::string msg;
  16142. ws::ReadResult ret;
  16143. while ((ret = ws.read(msg))) {
  16144. if (ret == ws::Binary) {
  16145. ws.send(msg.data(), msg.size());
  16146. } else {
  16147. ws.send(msg);
  16148. }
  16149. }
  16150. });
  16151. port_ = server_->bind_to_any_port(HOST);
  16152. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16153. server_->wait_until_ready();
  16154. }
  16155. void TearDown() override {
  16156. server_->stop();
  16157. if (server_thread_.joinable()) { server_thread_.join(); }
  16158. }
  16159. std::unique_ptr<SSLServer> server_;
  16160. std::thread server_thread_;
  16161. int port_ = 0;
  16162. };
  16163. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16164. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16165. "/ws-echo");
  16166. client.enable_server_certificate_verification(false);
  16167. ASSERT_TRUE(client.connect());
  16168. ASSERT_TRUE(client.is_open());
  16169. ASSERT_TRUE(client.send("Hello WSS"));
  16170. std::string msg;
  16171. EXPECT_EQ(ws::Text, client.read(msg));
  16172. EXPECT_EQ("Hello WSS", msg);
  16173. client.close();
  16174. }
  16175. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16176. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16177. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16178. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16179. // client (without calling close() first) is the only path that runs
  16180. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16181. // bug exactly.
  16182. //
  16183. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16184. // when linked against an instrumented libssl; run under Valgrind to catch it
  16185. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16186. // suite (the freed session otherwise stalls on the close handshake) — this test
  16187. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16188. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16189. {
  16190. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16191. "/ws-echo");
  16192. client.enable_server_certificate_verification(false);
  16193. client.set_read_timeout(2, 0);
  16194. client.set_write_timeout(2, 0);
  16195. ASSERT_TRUE(client.connect());
  16196. ASSERT_TRUE(client.is_open());
  16197. ASSERT_TRUE(client.send("still open"));
  16198. // Intentionally do NOT call client.close(): leaving scope runs
  16199. // shutdown_and_close() with the WebSocket still open, which must send the
  16200. // close frame while the TLS session is still alive.
  16201. }
  16202. }
  16203. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16204. // shutdown_and_close() at the start of connect(), reproducing the same
  16205. // use-after-free within the test body rather than at scope exit. The second
  16206. // connect must succeed and echo, proving the close handshake ran over a live
  16207. // session. See the note above about memory-tool requirements.
  16208. TEST_F(WebSocketSSLIntegrationTest,
  16209. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16210. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16211. "/ws-echo");
  16212. client.enable_server_certificate_verification(false);
  16213. client.set_read_timeout(2, 0);
  16214. client.set_write_timeout(2, 0);
  16215. ASSERT_TRUE(client.connect());
  16216. ASSERT_TRUE(client.is_open());
  16217. ASSERT_TRUE(client.send("still open"));
  16218. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16219. // the still-open connection, which must not touch a freed TLS session.
  16220. ASSERT_TRUE(client.connect());
  16221. ASSERT_TRUE(client.is_open());
  16222. ASSERT_TRUE(client.send("after reconnect"));
  16223. std::string msg;
  16224. EXPECT_EQ(ws::Text, client.read(msg));
  16225. EXPECT_EQ("after reconnect", msg);
  16226. client.close();
  16227. }
  16228. #endif
  16229. #ifdef CPPHTTPLIB_SSL_ENABLED
  16230. class WebSocketSSLCATest : public ::testing::Test {
  16231. protected:
  16232. void SetUp() override {
  16233. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16234. SERVER_PRIVATE_KEY_FILE);
  16235. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16236. std::string msg;
  16237. while (ws.read(msg)) {
  16238. ws.send(msg);
  16239. }
  16240. });
  16241. port_ = server_->bind_to_any_port("127.0.0.1");
  16242. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16243. server_->wait_until_ready();
  16244. }
  16245. void TearDown() override {
  16246. server_->stop();
  16247. if (server_thread_.joinable()) { server_thread_.join(); }
  16248. }
  16249. std::string url() const {
  16250. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16251. }
  16252. std::unique_ptr<SSLServer> server_;
  16253. std::thread server_thread_;
  16254. int port_ = 0;
  16255. };
  16256. // A custom CA loaded as PEM verifies the server with full certificate
  16257. // verification enabled
  16258. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16259. ws::WebSocketClient client(url());
  16260. std::string cert;
  16261. read_file(SERVER_CERT2_FILE, cert);
  16262. client.load_ca_cert_store(cert.c_str(), cert.size());
  16263. ASSERT_TRUE(client.connect());
  16264. ASSERT_TRUE(client.send("hello"));
  16265. std::string msg;
  16266. EXPECT_EQ(ws::Text, client.read(msg));
  16267. EXPECT_EQ("hello", msg);
  16268. client.close();
  16269. }
  16270. // A custom CA that does not cover the server must fail verification (the
  16271. // custom CA is exclusive; system certs are not loaded alongside it)
  16272. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16273. ws::WebSocketClient client(url());
  16274. std::string cert;
  16275. read_file(CLIENT_CA_CERT_FILE, cert);
  16276. client.load_ca_cert_store(cert.c_str(), cert.size());
  16277. ASSERT_FALSE(client.connect());
  16278. }
  16279. // Regression test: reconnecting with a native custom CA store used to reuse
  16280. // a store handle the previous TLS context had already freed (use-after-free
  16281. // under the OpenSSL backend). The context now lives as long as the client.
  16282. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16283. ws::WebSocketClient client(url());
  16284. std::string cert;
  16285. read_file(SERVER_CERT2_FILE, cert);
  16286. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16287. ASSERT_TRUE(client.connect());
  16288. client.close();
  16289. ASSERT_TRUE(client.connect());
  16290. ASSERT_TRUE(client.send("again"));
  16291. std::string msg;
  16292. EXPECT_EQ(ws::Text, client.read(msg));
  16293. EXPECT_EQ("again", msg);
  16294. client.close();
  16295. }
  16296. // Regression test: a certificate with a trusted chain but no identity match
  16297. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16298. // verification entirely for IP hosts, so this connection succeeded there.
  16299. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16300. // chain verification while the identity check must still fail.
  16301. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16303. ASSERT_TRUE(svr.is_valid());
  16304. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16305. std::string msg;
  16306. while (ws.read(msg)) {
  16307. ws.send(msg);
  16308. }
  16309. });
  16310. auto port = svr.bind_to_any_port("127.0.0.1");
  16311. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16312. auto se = detail::scope_exit([&] {
  16313. svr.stop();
  16314. t.join();
  16315. });
  16316. svr.wait_until_ready();
  16317. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16318. "/echo");
  16319. std::string cert;
  16320. read_file(SERVER_CERT_FILE, cert);
  16321. client.load_ca_cert_store(cert.c_str(), cert.size());
  16322. ASSERT_FALSE(client.connect());
  16323. }
  16324. #endif
  16325. #if !defined(_WIN32)
  16326. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16327. auto secret_dir = std::string("./symlink_test_secret");
  16328. auto served_dir = std::string("./symlink_test_served");
  16329. auto secret_file = secret_dir + "/secret.txt";
  16330. auto symlink_path = served_dir + "/escape";
  16331. // Setup: create directories and files
  16332. mkdir(secret_dir.c_str(), 0755);
  16333. mkdir(served_dir.c_str(), 0755);
  16334. {
  16335. std::ofstream ofs(secret_file);
  16336. ofs << "SECRET_DATA";
  16337. }
  16338. // Create symlink using absolute path so it resolves correctly
  16339. #ifdef PATH_MAX
  16340. char abs_secret[PATH_MAX];
  16341. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16342. #else
  16343. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16344. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16345. ASSERT_NE(nullptr, abs_secret);
  16346. #endif
  16347. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16348. auto se = detail::scope_exit([&] {
  16349. unlink(symlink_path.c_str());
  16350. unlink(secret_file.c_str());
  16351. rmdir(served_dir.c_str());
  16352. rmdir(secret_dir.c_str());
  16353. });
  16354. Server svr;
  16355. svr.set_mount_point("/", served_dir);
  16356. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16357. auto se2 = detail::scope_exit([&] {
  16358. svr.stop();
  16359. listen_thread.join();
  16360. });
  16361. svr.wait_until_ready();
  16362. Client cli("localhost", PORT);
  16363. // Symlink pointing outside base dir should be blocked
  16364. auto res = cli.Get("/escape/secret.txt");
  16365. ASSERT_TRUE(res);
  16366. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16367. }
  16368. #endif
  16369. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16370. // A GET request with Content-Length to a static file handler must have its
  16371. // body drained before the keep-alive connection is reused. Otherwise the
  16372. // unread body bytes are interpreted as the next HTTP request.
  16373. //
  16374. // The body is sent AFTER receiving the first response (as in the original
  16375. // PoC) so that the stream_line_reader cannot buffer it together with the
  16376. // headers of the first request.
  16377. Server svr;
  16378. svr.set_mount_point("/", "./www");
  16379. std::atomic<int> smuggled_count(0);
  16380. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16381. smuggled_count++;
  16382. res.set_content("oops", "text/plain");
  16383. });
  16384. auto port = svr.bind_to_any_port("localhost");
  16385. thread t = thread([&] { svr.listen_after_bind(); });
  16386. auto se = detail::scope_exit([&] {
  16387. svr.stop();
  16388. t.join();
  16389. });
  16390. svr.wait_until_ready();
  16391. auto error = Error::Success;
  16392. auto sock = detail::create_client_socket(
  16393. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16394. /*connection_timeout_sec=*/2, 0,
  16395. /*read_timeout_sec=*/2, 0,
  16396. /*write_timeout_sec=*/2, 0, std::string(), error);
  16397. ASSERT_NE(INVALID_SOCKET, sock);
  16398. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16399. // The "smuggled" request will be sent as the body of the outer GET
  16400. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16401. "Host: localhost\r\n"
  16402. "Connection: close\r\n"
  16403. "\r\n";
  16404. // Step 1: Send only the outer request headers (no body yet)
  16405. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16406. "Host: localhost\r\n"
  16407. "Content-Length: " +
  16408. std::to_string(smuggled.size()) +
  16409. "\r\n"
  16410. "\r\n";
  16411. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16412. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16413. // Step 2: Read the first response (server serves file without reading body)
  16414. std::string first_response;
  16415. char buf[4096];
  16416. for (;;) {
  16417. auto n = recv(sock, buf, sizeof(buf), 0);
  16418. if (n <= 0) break;
  16419. first_response.append(buf, static_cast<size_t>(n));
  16420. // Stop once we have a complete response (headers + body)
  16421. auto hdr_end = first_response.find("\r\n\r\n");
  16422. if (hdr_end != std::string::npos) {
  16423. // Check for Content-Length to know when the body is complete
  16424. auto cl_pos = first_response.find("Content-Length:");
  16425. if (cl_pos != std::string::npos) {
  16426. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16427. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16428. auto cl = std::stoul(
  16429. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16430. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16431. } else {
  16432. break; // No Content-Length, assume headers-only response
  16433. }
  16434. }
  16435. }
  16436. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16437. // Step 3: Now send the body, which looks like a new HTTP request.
  16438. // On a vulnerable server the keep-alive loop reads this as a second request.
  16439. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16440. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16441. // Step 4: Try to read a second response (should NOT exist after fix)
  16442. std::string second_response;
  16443. for (;;) {
  16444. auto n = recv(sock, buf, sizeof(buf), 0);
  16445. if (n <= 0) break;
  16446. second_response.append(buf, static_cast<size_t>(n));
  16447. }
  16448. // The smuggled request must NOT have been processed
  16449. EXPECT_EQ(0, smuggled_count.load());
  16450. }
  16451. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16452. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16453. // must be rejected with 400 Bad Request.
  16454. Server svr;
  16455. svr.Post("/test", [&](const Request &, Response &res) {
  16456. res.set_content("ok", "text/plain");
  16457. });
  16458. thread t = thread([&] { svr.listen(HOST, PORT); });
  16459. auto se = detail::scope_exit([&] {
  16460. svr.stop();
  16461. t.join();
  16462. ASSERT_FALSE(svr.is_running());
  16463. });
  16464. svr.wait_until_ready();
  16465. // Exact "chunked"
  16466. {
  16467. auto req = "POST /test HTTP/1.1\r\n"
  16468. "Host: localhost\r\n"
  16469. "Content-Length: 5\r\n"
  16470. "Transfer-Encoding: chunked\r\n"
  16471. "Connection: close\r\n"
  16472. "\r\n"
  16473. "hello";
  16474. std::string response;
  16475. ASSERT_TRUE(send_request(1, req, &response));
  16476. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16477. response.substr(0, response.find("\r\n")));
  16478. }
  16479. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16480. {
  16481. auto req = "POST /test HTTP/1.1\r\n"
  16482. "Host: localhost\r\n"
  16483. "Content-Length: 5\r\n"
  16484. "Transfer-Encoding: gzip, chunked\r\n"
  16485. "Connection: close\r\n"
  16486. "\r\n"
  16487. "hello";
  16488. std::string response;
  16489. ASSERT_TRUE(send_request(1, req, &response));
  16490. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16491. response.substr(0, response.find("\r\n")));
  16492. }
  16493. }
  16494. // Regression for issue #2450: a DELETE without Content-Length on a
  16495. // keep-alive connection must not let the post-response drain consume the
  16496. // next request's bytes.
  16497. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16498. Server svr;
  16499. std::atomic<int> delete_count(0);
  16500. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16501. delete_count++;
  16502. res.status = StatusCode::NoContent_204;
  16503. });
  16504. auto port = svr.bind_to_any_port(HOST);
  16505. thread t = thread([&] { svr.listen_after_bind(); });
  16506. auto se = detail::scope_exit([&] {
  16507. svr.stop();
  16508. t.join();
  16509. });
  16510. svr.wait_until_ready();
  16511. auto error = Error::Success;
  16512. auto sock = detail::create_client_socket(
  16513. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16514. /*connection_timeout_sec=*/2, 0,
  16515. /*read_timeout_sec=*/2, 0,
  16516. /*write_timeout_sec=*/2, 0, std::string(), error);
  16517. ASSERT_NE(INVALID_SOCKET, sock);
  16518. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16519. auto send_request_and_read_response = [&](const std::string &req,
  16520. std::string &out) -> bool {
  16521. auto sent = send(sock, req.data(), req.size(), 0);
  16522. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16523. char buf[4096];
  16524. for (;;) {
  16525. auto n = recv(sock, buf, sizeof(buf), 0);
  16526. if (n <= 0) { return !out.empty(); }
  16527. out.append(buf, static_cast<size_t>(n));
  16528. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16529. }
  16530. };
  16531. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16532. "Host: localhost\r\n"
  16533. "\r\n";
  16534. std::string resp1;
  16535. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16536. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16537. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16538. "Host: localhost\r\n"
  16539. "Connection: close\r\n"
  16540. "\r\n";
  16541. std::string resp2;
  16542. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16543. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16544. EXPECT_EQ(2, delete_count.load());
  16545. }
  16546. namespace no_proxy_test {
  16547. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16548. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16549. // calling listen().
  16550. class ScopedServer {
  16551. public:
  16552. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16553. ~ScopedServer() {
  16554. svr_.stop();
  16555. if (th_.joinable()) { th_.join(); }
  16556. }
  16557. Server &svr() { return svr_; }
  16558. int port() const { return port_; }
  16559. void listen() {
  16560. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16561. svr_.wait_until_ready();
  16562. }
  16563. private:
  16564. Server svr_;
  16565. std::thread th_;
  16566. int port_ = 0;
  16567. };
  16568. class ProxyAndTargetServers {
  16569. public:
  16570. ProxyAndTargetServers() {
  16571. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16572. proxy_hits_++;
  16573. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16574. res.set_content("via-proxy", "text/plain");
  16575. });
  16576. target_.Get(".*", [this](const Request &req, Response &res) {
  16577. target_hits_++;
  16578. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16579. res.set_content("direct", "text/plain");
  16580. });
  16581. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16582. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16583. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16584. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16585. proxy_mock_.wait_until_ready();
  16586. target_.wait_until_ready();
  16587. }
  16588. ~ProxyAndTargetServers() {
  16589. proxy_mock_.stop();
  16590. target_.stop();
  16591. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16592. if (target_thread_.joinable()) { target_thread_.join(); }
  16593. }
  16594. Server &proxy_mock() { return proxy_mock_; }
  16595. Server &target() { return target_; }
  16596. int proxy_port() const { return proxy_port_; }
  16597. int target_port() const { return target_port_; }
  16598. int proxy_hits() const { return proxy_hits_.load(); }
  16599. int target_hits() const { return target_hits_.load(); }
  16600. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16601. void reset_counters() {
  16602. proxy_hits_ = 0;
  16603. target_hits_ = 0;
  16604. last_had_proxy_authz_ = false;
  16605. }
  16606. private:
  16607. Server proxy_mock_;
  16608. Server target_;
  16609. std::thread proxy_thread_;
  16610. std::thread target_thread_;
  16611. int proxy_port_ = 0;
  16612. int target_port_ = 0;
  16613. std::atomic<int> proxy_hits_{0};
  16614. std::atomic<int> target_hits_{0};
  16615. std::atomic<bool> last_had_proxy_authz_{false};
  16616. };
  16617. inline std::unique_ptr<Client> make_client(const std::string &host,
  16618. ProxyAndTargetServers &s) {
  16619. auto cli = detail::make_unique<Client>(host, s.target_port());
  16620. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16621. cli->set_proxy("127.0.0.1", s.proxy_port());
  16622. return cli;
  16623. }
  16624. } // namespace no_proxy_test
  16625. using no_proxy_test::make_client;
  16626. using no_proxy_test::ProxyAndTargetServers;
  16627. TEST(NoProxyTest, ExactHostnameBypasses) {
  16628. ProxyAndTargetServers s;
  16629. auto cli = make_client("example.com", s);
  16630. cli->set_no_proxy({"example.com"});
  16631. auto res = cli->Get("/");
  16632. ASSERT_TRUE(res);
  16633. EXPECT_EQ(0, s.proxy_hits());
  16634. EXPECT_EQ(1, s.target_hits());
  16635. }
  16636. TEST(NoProxyTest, SubdomainBypasses) {
  16637. ProxyAndTargetServers s;
  16638. auto cli = make_client("foo.example.com", s);
  16639. cli->set_no_proxy({"example.com"});
  16640. auto res = cli->Get("/");
  16641. ASSERT_TRUE(res);
  16642. EXPECT_EQ(0, s.proxy_hits());
  16643. EXPECT_EQ(1, s.target_hits());
  16644. }
  16645. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16646. // Regression guard: "evilexample.com" must not be considered a subdomain
  16647. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16648. // check would let traffic bypass the proxy and leak credentials direct
  16649. // to the attacker host.
  16650. ProxyAndTargetServers s;
  16651. auto cli = make_client("evilexample.com", s);
  16652. cli->set_no_proxy({"example.com"});
  16653. auto res = cli->Get("/");
  16654. ASSERT_TRUE(res);
  16655. EXPECT_GE(s.proxy_hits(), 1);
  16656. EXPECT_EQ(0, s.target_hits());
  16657. }
  16658. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16659. ProxyAndTargetServers s;
  16660. auto cli = make_client("example.com.evil.com", s);
  16661. cli->set_no_proxy({"example.com"});
  16662. auto res = cli->Get("/");
  16663. ASSERT_TRUE(res);
  16664. EXPECT_GE(s.proxy_hits(), 1);
  16665. EXPECT_EQ(0, s.target_hits());
  16666. }
  16667. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16668. ProxyAndTargetServers s;
  16669. auto cli = make_client("example.com", s);
  16670. cli->set_no_proxy({".example.com"});
  16671. auto res = cli->Get("/");
  16672. ASSERT_TRUE(res);
  16673. EXPECT_EQ(0, s.proxy_hits());
  16674. EXPECT_EQ(1, s.target_hits());
  16675. }
  16676. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16677. ProxyAndTargetServers s;
  16678. auto cli = make_client("Example.COM", s);
  16679. cli->set_no_proxy({"EXAMPLE.com"});
  16680. auto res = cli->Get("/");
  16681. ASSERT_TRUE(res);
  16682. EXPECT_EQ(0, s.proxy_hits());
  16683. EXPECT_EQ(1, s.target_hits());
  16684. }
  16685. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16686. ProxyAndTargetServers s;
  16687. auto cli = make_client("example.com.", s);
  16688. cli->set_no_proxy({"example.com"});
  16689. auto res = cli->Get("/");
  16690. ASSERT_TRUE(res);
  16691. EXPECT_EQ(0, s.proxy_hits());
  16692. EXPECT_EQ(1, s.target_hits());
  16693. }
  16694. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16695. // Trailing dots must be normalized on BOTH sides — host and entry.
  16696. // An implementation that only strips the host-side trailing dot would
  16697. // fail to match host "example.com" against entry "example.com." because
  16698. // a literal substring search would compare 11 chars against 12.
  16699. ProxyAndTargetServers s;
  16700. auto cli = make_client("example.com", s);
  16701. cli->set_no_proxy({"example.com."});
  16702. auto res = cli->Get("/");
  16703. ASSERT_TRUE(res);
  16704. EXPECT_EQ(0, s.proxy_hits());
  16705. EXPECT_EQ(1, s.target_hits());
  16706. }
  16707. TEST(NoProxyTest, WildcardBypassesEverything) {
  16708. ProxyAndTargetServers s;
  16709. auto cli = make_client("anything.invalid.test", s);
  16710. cli->set_no_proxy({"*"});
  16711. auto res = cli->Get("/");
  16712. ASSERT_TRUE(res);
  16713. EXPECT_EQ(0, s.proxy_hits());
  16714. EXPECT_EQ(1, s.target_hits());
  16715. }
  16716. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16717. ProxyAndTargetServers s;
  16718. Client cli("127.0.0.1", s.target_port());
  16719. cli.set_proxy("127.0.0.1", s.proxy_port());
  16720. cli.set_no_proxy({"127.0.0.1"});
  16721. auto res = cli.Get("/");
  16722. ASSERT_TRUE(res);
  16723. EXPECT_EQ(0, s.proxy_hits());
  16724. EXPECT_EQ(1, s.target_hits());
  16725. }
  16726. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16727. ProxyAndTargetServers s;
  16728. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16729. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16730. cli.set_proxy("127.0.0.1", s.proxy_port());
  16731. cli.set_no_proxy({"::1"});
  16732. auto res = cli.Get("/");
  16733. ASSERT_TRUE(res);
  16734. EXPECT_EQ(0, s.proxy_hits());
  16735. EXPECT_EQ(1, s.target_hits());
  16736. }
  16737. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16738. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16739. // must still be recognized as IPv6 for CIDR matching. Implementations
  16740. // that detect IPv6 only when the host begins with '[' would parse the
  16741. // host as a hostname and miss the match.
  16742. ProxyAndTargetServers s;
  16743. Client cli("fe80::1", s.target_port());
  16744. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16745. cli.set_proxy("127.0.0.1", s.proxy_port());
  16746. cli.set_no_proxy({"fe80::/10"});
  16747. auto res = cli.Get("/");
  16748. ASSERT_TRUE(res);
  16749. EXPECT_EQ(0, s.proxy_hits());
  16750. EXPECT_EQ(1, s.target_hits());
  16751. }
  16752. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16753. ProxyAndTargetServers s;
  16754. Client cli("::1", s.target_port());
  16755. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16756. cli.set_proxy("127.0.0.1", s.proxy_port());
  16757. cli.set_no_proxy({"[::1]"});
  16758. auto res = cli.Get("/");
  16759. ASSERT_TRUE(res);
  16760. EXPECT_EQ(0, s.proxy_hits());
  16761. EXPECT_EQ(1, s.target_hits());
  16762. }
  16763. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16764. ProxyAndTargetServers s;
  16765. Client cli("fe80::1", s.target_port());
  16766. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16767. cli.set_proxy("127.0.0.1", s.proxy_port());
  16768. cli.set_no_proxy({"[fe80::]/10"});
  16769. auto res = cli.Get("/");
  16770. ASSERT_TRUE(res);
  16771. EXPECT_EQ(0, s.proxy_hits());
  16772. EXPECT_EQ(1, s.target_hits());
  16773. }
  16774. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16775. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16776. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16777. // tricks via address-family conversion.
  16778. ProxyAndTargetServers s;
  16779. Client cli("::ffff:127.0.0.1", s.target_port());
  16780. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16781. cli.set_proxy("127.0.0.1", s.proxy_port());
  16782. cli.set_no_proxy({"127.0.0.1"});
  16783. auto res = cli.Get("/");
  16784. ASSERT_TRUE(res);
  16785. EXPECT_GE(s.proxy_hits(), 1);
  16786. EXPECT_EQ(0, s.target_hits());
  16787. }
  16788. TEST(NoProxyTest, IPv4CidrMatch) {
  16789. ProxyAndTargetServers s;
  16790. Client cli("127.0.0.1", s.target_port());
  16791. cli.set_proxy("127.0.0.1", s.proxy_port());
  16792. cli.set_no_proxy({"127.0.0.0/8"});
  16793. auto res = cli.Get("/");
  16794. ASSERT_TRUE(res);
  16795. EXPECT_EQ(0, s.proxy_hits());
  16796. EXPECT_EQ(1, s.target_hits());
  16797. }
  16798. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16799. ProxyAndTargetServers s;
  16800. Client cli("127.0.0.1", s.target_port());
  16801. cli.set_proxy("127.0.0.1", s.proxy_port());
  16802. cli.set_no_proxy({"10.0.0.0/8"});
  16803. auto res = cli.Get("/");
  16804. ASSERT_TRUE(res);
  16805. EXPECT_GE(s.proxy_hits(), 1);
  16806. EXPECT_EQ(0, s.target_hits());
  16807. }
  16808. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16809. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16810. // IPv4 target matches.
  16811. ProxyAndTargetServers s;
  16812. Client cli("127.0.0.1", s.target_port());
  16813. cli.set_proxy("127.0.0.1", s.proxy_port());
  16814. cli.set_no_proxy({"0.0.0.0/0"});
  16815. auto res = cli.Get("/");
  16816. ASSERT_TRUE(res);
  16817. EXPECT_EQ(0, s.proxy_hits());
  16818. EXPECT_EQ(1, s.target_hits());
  16819. }
  16820. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16821. ProxyAndTargetServers s;
  16822. Client cli("127.0.0.1", s.target_port());
  16823. cli.set_proxy("127.0.0.1", s.proxy_port());
  16824. cli.set_no_proxy({"127.0.0.1"});
  16825. auto res = cli.Get("/");
  16826. ASSERT_TRUE(res);
  16827. EXPECT_EQ(0, s.proxy_hits());
  16828. EXPECT_EQ(1, s.target_hits());
  16829. }
  16830. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16831. ProxyAndTargetServers s;
  16832. Client cli("127.0.0.1", s.target_port());
  16833. cli.set_proxy("127.0.0.1", s.proxy_port());
  16834. cli.set_no_proxy({"127.0.0.0/33"});
  16835. auto res = cli.Get("/");
  16836. ASSERT_TRUE(res);
  16837. EXPECT_GE(s.proxy_hits(), 1);
  16838. EXPECT_EQ(0, s.target_hits());
  16839. }
  16840. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16841. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16842. ProxyAndTargetServers s;
  16843. Client cli("127.0.0.1", s.target_port());
  16844. cli.set_proxy("127.0.0.1", s.proxy_port());
  16845. cli.set_no_proxy({"127.0.0.1/"});
  16846. auto res = cli.Get("/");
  16847. ASSERT_TRUE(res);
  16848. EXPECT_GE(s.proxy_hits(), 1);
  16849. EXPECT_EQ(0, s.target_hits());
  16850. }
  16851. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16852. ProxyAndTargetServers s;
  16853. auto cli = make_client("internal.corp", s);
  16854. cli->set_proxy_basic_auth("u", "p");
  16855. cli->set_no_proxy({"internal.corp"});
  16856. auto res = cli->Get("/");
  16857. ASSERT_TRUE(res);
  16858. EXPECT_EQ(1, s.target_hits());
  16859. EXPECT_EQ(0, s.proxy_hits());
  16860. EXPECT_FALSE(s.last_had_proxy_authz())
  16861. << "Proxy-Authorization must not be sent direct to the target";
  16862. }
  16863. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16864. ProxyAndTargetServers s;
  16865. auto cli = make_client("public.example", s);
  16866. cli->set_proxy_basic_auth("u", "p");
  16867. cli->set_no_proxy({"internal.corp"}); // does not match
  16868. auto res = cli->Get("/");
  16869. ASSERT_TRUE(res);
  16870. EXPECT_GE(s.proxy_hits(), 1);
  16871. EXPECT_TRUE(s.last_had_proxy_authz());
  16872. }
  16873. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16874. ProxyAndTargetServers s;
  16875. auto cli = make_client("anything.test", s);
  16876. auto res = cli->Get("/");
  16877. ASSERT_TRUE(res);
  16878. EXPECT_GE(s.proxy_hits(), 1);
  16879. EXPECT_EQ(0, s.target_hits());
  16880. }
  16881. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16882. ProxyAndTargetServers s;
  16883. auto cli = make_client("example.com", s);
  16884. cli->set_no_proxy({"example.com:8080"});
  16885. auto res = cli->Get("/");
  16886. ASSERT_TRUE(res);
  16887. EXPECT_GE(s.proxy_hits(), 1);
  16888. EXPECT_EQ(0, s.target_hits());
  16889. }
  16890. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16891. ProxyAndTargetServers s;
  16892. auto cli = make_client("anything.test", s);
  16893. cli->set_no_proxy({"", " ", "\t"});
  16894. auto res = cli->Get("/");
  16895. ASSERT_TRUE(res);
  16896. EXPECT_GE(s.proxy_hits(), 1);
  16897. EXPECT_EQ(0, s.target_hits());
  16898. }
  16899. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16900. // An entry with leading/trailing whitespace must still match — env-style
  16901. // values are commonly pasted with stray spaces and an implementation
  16902. // that feeds the raw token directly to inet_pton would fail to match
  16903. // valid CIDRs because of the spaces.
  16904. ProxyAndTargetServers s;
  16905. Client cli("127.0.0.1", s.target_port());
  16906. cli.set_proxy("127.0.0.1", s.proxy_port());
  16907. cli.set_no_proxy({" 127.0.0.0/8 "});
  16908. auto res = cli.Get("/");
  16909. ASSERT_TRUE(res);
  16910. EXPECT_EQ(0, s.proxy_hits());
  16911. EXPECT_EQ(1, s.target_hits());
  16912. }
  16913. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16914. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16915. // go direct and must NOT carry Proxy-Authorization.
  16916. std::atomic<int> proxy_hits{0};
  16917. std::atomic<int> target_hits{0};
  16918. std::atomic<bool> target_saw_authz{false};
  16919. no_proxy_test::ScopedServer proxy_mock, target;
  16920. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16921. proxy_hits++;
  16922. res.status = 302;
  16923. res.set_header("Location", "http://127.0.0.1:" +
  16924. std::to_string(target.port()) + "/landed");
  16925. });
  16926. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16927. target_hits++;
  16928. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16929. res.set_content("direct", "text/plain");
  16930. });
  16931. proxy_mock.listen();
  16932. target.listen();
  16933. Client cli("public.example", target.port());
  16934. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16935. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16936. cli.set_proxy_basic_auth("u", "p");
  16937. cli.set_no_proxy({"127.0.0.1"});
  16938. cli.set_follow_location(true);
  16939. auto res = cli.Get("/redir");
  16940. ASSERT_TRUE(res);
  16941. EXPECT_GE(proxy_hits.load(), 1);
  16942. EXPECT_GE(target_hits.load(), 1);
  16943. EXPECT_FALSE(target_saw_authz.load());
  16944. }
  16945. #ifdef CPPHTTPLIB_SSL_ENABLED
  16946. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16947. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16948. // proxy creds would be sent to the (possibly hostile) origin.
  16949. std::atomic<int> target_hits{0};
  16950. std::atomic<bool> target_saw_proxy_authz{false};
  16951. no_proxy_test::ScopedServer target;
  16952. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16953. target_hits++;
  16954. if (req.has_header("Proxy-Authorization")) {
  16955. target_saw_proxy_authz = true;
  16956. }
  16957. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16958. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16959. "nonce=\"abc\", algorithm=MD5");
  16960. });
  16961. target.listen();
  16962. // The proxy address is set to the target's port: the bypass MUST kick in;
  16963. // if it doesn't, the test still routes "via proxy" to the same server and
  16964. // the Proxy-Authorization assertion below catches the leak.
  16965. Client cli("evil.example", target.port());
  16966. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16967. cli.set_proxy("127.0.0.1", target.port());
  16968. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16969. cli.set_no_proxy({"evil.example"});
  16970. auto res = cli.Get("/x");
  16971. ASSERT_TRUE(res);
  16972. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16973. EXPECT_EQ(1, target_hits.load());
  16974. EXPECT_FALSE(target_saw_proxy_authz.load());
  16975. }
  16976. #endif
  16977. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16978. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16979. std::atomic<int> proxy_hits{0};
  16980. std::atomic<int> bypass_hits{0};
  16981. std::atomic<bool> proxy_saw_c_url{false};
  16982. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16983. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16984. proxy_hits++;
  16985. if (req.path.find("/start") != std::string::npos) {
  16986. res.status = 302;
  16987. res.set_header("Location", "http://127.0.0.1:" +
  16988. std::to_string(bypass_server.port()) +
  16989. "/middle");
  16990. return;
  16991. }
  16992. if (req.path.find("/end") != std::string::npos) {
  16993. proxy_saw_c_url = true;
  16994. res.set_content("c-via-proxy", "text/plain");
  16995. return;
  16996. }
  16997. res.set_content("unexpected", "text/plain");
  16998. });
  16999. // public.example's "advertised" port is arbitrary (the request never lands
  17000. // there — it goes through the proxy), but use a dynamic value to stay
  17001. // friendly with sharded parallel runs.
  17002. int public_port = bypass_server.port();
  17003. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17004. bypass_hits++;
  17005. res.status = 302;
  17006. res.set_header("Location", "http://public.example:" +
  17007. std::to_string(public_port) + "/end");
  17008. });
  17009. proxy_mock.listen();
  17010. bypass_server.listen();
  17011. Client cli("public.example", public_port);
  17012. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17013. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17014. cli.set_no_proxy({"127.0.0.1"});
  17015. cli.set_follow_location(true);
  17016. auto res = cli.Get("/start");
  17017. ASSERT_TRUE(res);
  17018. EXPECT_EQ(StatusCode::OK_200, res->status);
  17019. EXPECT_EQ("c-via-proxy", res->body);
  17020. EXPECT_GE(proxy_hits.load(), 2);
  17021. EXPECT_GE(bypass_hits.load(), 1);
  17022. EXPECT_TRUE(proxy_saw_c_url.load());
  17023. }
  17024. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17025. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17026. // request reconnects to the correct endpoint.
  17027. std::atomic<int> proxy_hits{0};
  17028. std::atomic<int> target_hits{0};
  17029. no_proxy_test::ScopedServer proxy_mock, target;
  17030. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17031. proxy_hits++;
  17032. res.set_content("via-proxy", "text/plain");
  17033. });
  17034. target.svr().Get(".*", [&](const Request &, Response &res) {
  17035. target_hits++;
  17036. res.set_content("direct", "text/plain");
  17037. });
  17038. proxy_mock.listen();
  17039. target.listen();
  17040. Client cli("public.example", target.port());
  17041. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17042. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17043. cli.set_keep_alive(true);
  17044. auto res1 = cli.Get("/a");
  17045. ASSERT_TRUE(res1);
  17046. EXPECT_EQ("via-proxy", res1->body);
  17047. EXPECT_EQ(1, proxy_hits.load());
  17048. EXPECT_EQ(0, target_hits.load());
  17049. cli.set_no_proxy({"public.example"});
  17050. auto res2 = cli.Get("/b");
  17051. ASSERT_TRUE(res2);
  17052. EXPECT_EQ("direct", res2->body);
  17053. EXPECT_EQ(1, proxy_hits.load());
  17054. EXPECT_EQ(1, target_hits.load());
  17055. }
  17056. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17057. namespace proxy_tunnel_test {
  17058. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17059. class ScopedSSLServer {
  17060. public:
  17061. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17062. port_ = svr_.bind_to_any_port("127.0.0.1");
  17063. }
  17064. ~ScopedSSLServer() {
  17065. svr_.stop();
  17066. if (th_.joinable()) { th_.join(); }
  17067. }
  17068. SSLServer &svr() { return svr_; }
  17069. int port() const { return port_; }
  17070. void listen() {
  17071. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17072. svr_.wait_until_ready();
  17073. }
  17074. private:
  17075. SSLServer svr_;
  17076. std::thread th_;
  17077. int port_ = 0;
  17078. };
  17079. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17080. class ScopedConnectProxy {
  17081. public:
  17082. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17083. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17084. if (listen_fd_ < 0) { return; }
  17085. int yes = 1;
  17086. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17087. sockaddr_in a{};
  17088. a.sin_family = AF_INET;
  17089. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17090. a.sin_port = 0;
  17091. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17092. return;
  17093. }
  17094. socklen_t alen = sizeof(a);
  17095. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17096. 0) {
  17097. return;
  17098. }
  17099. port_ = ntohs(a.sin_port);
  17100. if (::listen(listen_fd_, 1) != 0) { return; }
  17101. th_ = std::thread([this] { run(); });
  17102. }
  17103. ~ScopedConnectProxy() {
  17104. stop_ = true;
  17105. if (listen_fd_ >= 0) {
  17106. ::shutdown(listen_fd_, SHUT_RDWR);
  17107. ::close(listen_fd_);
  17108. }
  17109. if (th_.joinable()) { th_.join(); }
  17110. }
  17111. int port() const { return port_; }
  17112. int connect_hits() const { return connect_hits_.load(); }
  17113. private:
  17114. void run() {
  17115. while (!stop_.load()) {
  17116. fd_set rfds;
  17117. FD_ZERO(&rfds);
  17118. FD_SET(listen_fd_, &rfds);
  17119. timeval tv{0, 100 * 1000};
  17120. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17121. if (sel <= 0) { continue; }
  17122. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17123. if (client_fd < 0) { continue; }
  17124. std::string req;
  17125. char buf[2048];
  17126. while (req.find("\r\n\r\n") == std::string::npos) {
  17127. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17128. if (n <= 0) { break; }
  17129. req.append(buf, static_cast<size_t>(n));
  17130. }
  17131. if (req.compare(0, 7, "CONNECT") != 0) {
  17132. ::close(client_fd);
  17133. continue;
  17134. }
  17135. connect_hits_++;
  17136. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17137. ::send(client_fd, ok, std::strlen(ok), 0);
  17138. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17139. sockaddr_in o{};
  17140. o.sin_family = AF_INET;
  17141. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17142. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17143. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17144. 0) {
  17145. ::close(client_fd);
  17146. ::close(origin_fd);
  17147. continue;
  17148. }
  17149. auto forward = [](int from, int to) {
  17150. char b[8192];
  17151. for (;;) {
  17152. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17153. if (n <= 0) { break; }
  17154. ssize_t off = 0;
  17155. while (off < n) {
  17156. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17157. if (s <= 0) {
  17158. off = n;
  17159. break;
  17160. }
  17161. off += s;
  17162. }
  17163. }
  17164. ::shutdown(to, SHUT_WR);
  17165. };
  17166. std::thread t1([&] { forward(client_fd, origin_fd); });
  17167. std::thread t2([&] { forward(origin_fd, client_fd); });
  17168. t1.join();
  17169. t2.join();
  17170. ::close(client_fd);
  17171. ::close(origin_fd);
  17172. }
  17173. }
  17174. int forward_port_ = -1;
  17175. int listen_fd_ = -1;
  17176. int port_ = 0;
  17177. std::thread th_;
  17178. std::atomic<bool> stop_{false};
  17179. std::atomic<int> connect_hits_{0};
  17180. };
  17181. } // namespace proxy_tunnel_test
  17182. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17183. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17184. // retry; otherwise proxy creds would be sent to the origin.
  17185. std::atomic<int> origin_hits{0};
  17186. std::atomic<bool> origin_saw_proxy_authz{false};
  17187. proxy_tunnel_test::ScopedSSLServer origin;
  17188. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17189. origin_hits++;
  17190. if (req.has_header("Proxy-Authorization")) {
  17191. origin_saw_proxy_authz = true;
  17192. }
  17193. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17194. res.set_header("Proxy-Authenticate",
  17195. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17196. "algorithm=MD5");
  17197. });
  17198. origin.listen();
  17199. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17200. ASSERT_NE(0, proxy.port());
  17201. SSLClient cli(HOST, origin.port());
  17202. cli.enable_server_certificate_verification(false);
  17203. cli.set_proxy(HOST, proxy.port());
  17204. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17205. auto res = cli.Get("/x");
  17206. ASSERT_TRUE(res);
  17207. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17208. EXPECT_EQ(1, origin_hits.load());
  17209. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17210. EXPECT_EQ(1, proxy.connect_hits());
  17211. }
  17212. #endif