test.cc 636 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592
  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: in split builds split.py strips `inline` and moves the
  361. // definition into httplib.cc, so detail::base64_encode is not visible from the
  362. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  363. // in both header-only and split builds.
  364. namespace httplib {
  365. namespace detail {
  366. std::string base64_encode(const std::string &in);
  367. } // namespace detail
  368. } // namespace httplib
  369. TEST(Base64EncodeTest, KnownAnswers) {
  370. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  371. // where the accumulator's top bit is already set before the next shift.
  372. EXPECT_EQ("", detail::base64_encode(""));
  373. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  374. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  375. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  376. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  377. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  378. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  379. // High bytes keep the top bit set across several rounds.
  380. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  381. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  382. }
  383. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  384. string unescapedCharacters = "-_.!~*'()";
  385. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  386. }
  387. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  388. string reservedCharacters = ";,/?:@&=+$";
  389. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  390. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  391. }
  392. TEST(ClientQueryOrder, PreserveOrder) {
  393. // This test reproduces Issue #2259: client may reorder query parameters
  394. // when sending a GET request. The expected behavior is that the client
  395. // preserves the original query string order when the caller supplied it
  396. // as part of the path.
  397. Server svr;
  398. svr.Get("/", [&](const Request &req, Response &res) {
  399. // Echo back the raw target so the test can assert ordering
  400. res.set_content(req.target, "text/plain");
  401. });
  402. std::thread t{[&] { svr.listen(HOST, PORT); }};
  403. auto se = detail::scope_exit([&] {
  404. svr.stop();
  405. t.join();
  406. ASSERT_FALSE(svr.is_running());
  407. });
  408. svr.wait_until_ready();
  409. Client cli(HOST, PORT);
  410. ASSERT_TRUE(cli.is_valid());
  411. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  412. auto res = cli.Get(original);
  413. ASSERT_TRUE(res);
  414. // Expect the echoed target to exactly match the original path (order
  415. // preserved)
  416. EXPECT_EQ(res->body, original);
  417. }
  418. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  425. "%D0%B4%D0%BE%D0%BC");
  426. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  427. }
  428. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$";
  434. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  435. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  436. }
  437. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  438. string chineseCharacters = U8("中国語");
  439. string russianCharacters = U8("дом");
  440. string brazilianCharacters = U8("óculos");
  441. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  442. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  443. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  444. "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  448. // Issue #2082 use case: encoding path component with ampersand
  449. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  450. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  451. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  452. }
  453. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  454. string unescapedCharacters = "-_.!~*'()";
  455. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  456. }
  457. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  458. string reservedCharacters = ";,/?:@&=+$#";
  459. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  460. }
  461. TEST(EncodeUriTest, TestUTF8Characters) {
  462. string chineseCharacters = U8("中国語");
  463. string russianCharacters = U8("дом");
  464. string brazilianCharacters = U8("óculos");
  465. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  466. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  467. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriTest, TestCompleteUri) {
  471. string uri =
  472. "https://example.com/path/to/resource?query=value&param=test#fragment";
  473. EXPECT_EQ(
  474. httplib::encode_uri(uri),
  475. "https://example.com/path/to/resource?query=value&param=test#fragment");
  476. }
  477. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  478. string uri =
  479. "https://example.com/path with spaces/file name.html?q=hello world";
  480. EXPECT_EQ(httplib::encode_uri(uri),
  481. "https://example.com/path%20with%20spaces/"
  482. "file%20name.html?q=hello%20world");
  483. }
  484. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  485. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  487. }
  488. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  489. string unescapedCharacters = "-_.!~*'()";
  490. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  491. }
  492. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  493. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  494. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  495. string encodedBrazilian = "%C3%B3culos";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  497. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  498. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  499. }
  500. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  501. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  502. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  503. "Piri Tommy Villiers - on & on");
  504. }
  505. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  506. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  507. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  508. }
  509. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  510. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  511. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  512. }
  513. TEST(DecodeUriTest, TestUTF8Characters) {
  514. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  515. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  516. string encodedBrazilian = "%C3%B3culos";
  517. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  518. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  519. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  520. }
  521. TEST(DecodeUriTest, TestCompleteUri) {
  522. string encodedUri = "https://example.com/path%20with%20spaces/"
  523. "file%20name.html?q=hello%20world";
  524. EXPECT_EQ(
  525. httplib::decode_uri(encodedUri),
  526. "https://example.com/path with spaces/file name.html?q=hello world");
  527. }
  528. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  529. string original =
  530. "https://example.com/path with spaces/file name.html?q=hello world";
  531. string encoded = httplib::encode_uri(original);
  532. string decoded = httplib::decode_uri(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  536. string original = "Piri Tommy Villiers - on & on";
  537. string encoded = httplib::encode_uri_component(original);
  538. string decoded = httplib::decode_uri_component(encoded);
  539. EXPECT_EQ(decoded, original);
  540. }
  541. TEST(TrimTests, TrimStringTests) {
  542. EXPECT_EQ("abc", detail::trim_copy("abc"));
  543. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  544. EXPECT_TRUE(detail::trim_copy("").empty());
  545. }
  546. TEST(AsciiTest, LocaleIndependentClassification) {
  547. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  548. // which consult the global C locale: std::isalnum(0xC5) can return true
  549. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  550. // helpers must classify every byte by the ASCII grammar alone.
  551. for (int i = 0; i < 256; i++) {
  552. auto c = static_cast<char>(i);
  553. auto is_digit = i >= '0' && i <= '9';
  554. auto is_upper = i >= 'A' && i <= 'Z';
  555. auto is_lower = i >= 'a' && i <= 'z';
  556. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  557. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  558. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  559. << "byte " << i;
  560. }
  561. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  562. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  563. // Non-ASCII bytes must be percent-encoded, never passed through as
  564. // alphanumeric.
  565. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  566. }
  567. TEST(FromCharsTest, Double) {
  568. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  569. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  570. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  571. auto parse = [](const std::string &s, double &v) {
  572. return detail::from_chars(s.data(), s.data() + s.size(), v);
  573. };
  574. double v = -1.0;
  575. // Representative quality values.
  576. EXPECT_EQ(parse("0", v).ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.0);
  578. EXPECT_EQ(parse("1", v).ec, std::errc{});
  579. EXPECT_DOUBLE_EQ(v, 1.0);
  580. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  581. EXPECT_DOUBLE_EQ(v, 0.8);
  582. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  583. EXPECT_DOUBLE_EQ(v, 0.001);
  584. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  585. EXPECT_DOUBLE_EQ(v, 1.0);
  586. // A missing integer or fractional part is tolerated.
  587. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  588. EXPECT_DOUBLE_EQ(v, 0.5);
  589. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  590. EXPECT_DOUBLE_EQ(v, 5.0);
  591. // Values outside [0, 1] still parse; the caller range-checks them.
  592. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  593. EXPECT_DOUBLE_EQ(v, 123.456);
  594. // Stops at the first byte that is not part of the number and reports where.
  595. std::string trailing = "0.9, text/html";
  596. auto r = parse(trailing, v);
  597. EXPECT_EQ(r.ec, std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.9);
  599. EXPECT_EQ(*r.ptr, ',');
  600. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  601. // outright, and an 'e'/'E' simply ends the number.
  602. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  603. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  604. std::string exp_input = "1.5e3";
  605. r = parse(exp_input, v);
  606. EXPECT_EQ(r.ec, std::errc{});
  607. EXPECT_DOUBLE_EQ(v, 1.5);
  608. EXPECT_EQ(*r.ptr, 'e');
  609. // Invalid inputs.
  610. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  611. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  612. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  613. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  614. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  615. // Pathological but well-formed inputs must stay bounded (no overflow, no
  616. // out-of-bounds table access) and stay within [0, 1] for the caller.
  617. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  618. std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  621. std::errc{});
  622. EXPECT_GE(v, 0.0);
  623. EXPECT_LE(v, 1.0);
  624. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  625. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  626. }
  627. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  628. // Simple case without quality values
  629. std::vector<std::string> result1;
  630. EXPECT_TRUE(detail::parse_accept_header(
  631. "text/html,application/json,text/plain", result1));
  632. EXPECT_EQ(result1.size(), 3U);
  633. EXPECT_EQ(result1[0], "text/html");
  634. EXPECT_EQ(result1[1], "application/json");
  635. EXPECT_EQ(result1[2], "text/plain");
  636. // With quality values
  637. std::vector<std::string> result2;
  638. EXPECT_TRUE(detail::parse_accept_header(
  639. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  640. EXPECT_EQ(result2.size(), 3U);
  641. EXPECT_EQ(result2[0], "application/json"); // highest q value
  642. EXPECT_EQ(result2[1], "text/html");
  643. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  644. }
  645. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  646. // Mixed with and without quality values
  647. std::vector<std::string> result;
  648. EXPECT_TRUE(detail::parse_accept_header(
  649. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  650. EXPECT_EQ(result.size(), 3U);
  651. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  652. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  653. EXPECT_EQ(result[2], "application/json"); // q=0.5
  654. }
  655. TEST(ParseAcceptHeaderTest, EdgeCases) {
  656. // Empty header
  657. std::vector<std::string> empty_result;
  658. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  659. EXPECT_TRUE(empty_result.empty());
  660. // Single type
  661. std::vector<std::string> single_result;
  662. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  663. EXPECT_EQ(single_result.size(), 1U);
  664. EXPECT_EQ(single_result[0], "application/json");
  665. // Wildcard types
  666. std::vector<std::string> wildcard_result;
  667. EXPECT_TRUE(detail::parse_accept_header(
  668. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  669. EXPECT_EQ(wildcard_result.size(), 3U);
  670. EXPECT_EQ(wildcard_result[0], "application/json");
  671. EXPECT_EQ(wildcard_result[1], "text/*");
  672. EXPECT_EQ(wildcard_result[2], "*/*");
  673. }
  674. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  675. // Common browser Accept header
  676. std::vector<std::string> browser_result;
  677. EXPECT_TRUE(
  678. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  679. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  680. browser_result));
  681. EXPECT_EQ(browser_result.size(), 6U);
  682. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  683. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  684. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  685. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  686. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  687. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  688. // API client header
  689. std::vector<std::string> api_result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  692. api_result));
  693. EXPECT_EQ(api_result.size(), 3U);
  694. EXPECT_EQ(api_result[0], "application/json");
  695. EXPECT_EQ(api_result[1], "application/xml");
  696. EXPECT_EQ(api_result[2], "text/plain");
  697. }
  698. TEST(ParseAcceptHeaderTest, SpecialCases) {
  699. // Quality value with 3 decimal places
  700. std::vector<std::string> decimal_result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  703. EXPECT_EQ(decimal_result.size(), 2U);
  704. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  705. EXPECT_EQ(decimal_result[1], "text/html");
  706. // Zero quality (should still be included but with lowest priority)
  707. std::vector<std::string> zero_q_result;
  708. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  709. zero_q_result));
  710. EXPECT_EQ(zero_q_result.size(), 2U);
  711. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  712. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  713. // No spaces around commas
  714. std::vector<std::string> no_space_result;
  715. EXPECT_TRUE(detail::parse_accept_header(
  716. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  717. no_space_result));
  718. EXPECT_EQ(no_space_result.size(), 3U);
  719. EXPECT_EQ(no_space_result[0], "text/html");
  720. EXPECT_EQ(no_space_result[1], "application/json");
  721. EXPECT_EQ(no_space_result[2], "text/plain");
  722. }
  723. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  724. // Quality values always use '.' as the decimal separator, so parsing must
  725. // not depend on the process locale. An embedding application may have
  726. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  727. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  728. std::string saved = cur ? cur : "C";
  729. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  730. "fr_FR.UTF-8"};
  731. bool switched = false;
  732. for (const auto loc : comma_locales) {
  733. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  734. std::localeconv()->decimal_point[0] == ',') {
  735. switched = true;
  736. break;
  737. }
  738. }
  739. if (!switched) {
  740. std::setlocale(LC_NUMERIC, saved.c_str());
  741. GTEST_SKIP() << "no comma-decimal locale available on this host";
  742. }
  743. // The higher-weighted type appears later in the list, so a correct parse
  744. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  745. // sensitive parse reads both weights as 0 and leaves the original order.
  746. std::vector<std::string> result;
  747. EXPECT_TRUE(detail::parse_accept_header(
  748. "application/json;q=0.1,text/html;q=0.9", result));
  749. ASSERT_EQ(result.size(), 2U);
  750. EXPECT_EQ(result[0], "text/html");
  751. EXPECT_EQ(result[1], "application/json");
  752. std::setlocale(LC_NUMERIC, saved.c_str());
  753. }
  754. TEST(ParseAcceptHeaderTest, InvalidCases) {
  755. std::vector<std::string> result;
  756. // Invalid quality value (> 1.0)
  757. EXPECT_FALSE(
  758. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  759. // Invalid quality value (< 0.0)
  760. EXPECT_FALSE(
  761. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  762. // Invalid quality value (not a number)
  763. EXPECT_FALSE(detail::parse_accept_header(
  764. "text/html;q=invalid,application/json", result));
  765. // Empty quality value
  766. EXPECT_FALSE(
  767. detail::parse_accept_header("text/html;q=,application/json", result));
  768. // Invalid media type format (no slash and not wildcard)
  769. EXPECT_FALSE(
  770. detail::parse_accept_header("invalidtype,application/json", result));
  771. // Empty media type
  772. result.clear();
  773. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  774. // Only commas
  775. result.clear();
  776. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  777. // Valid cases should still work
  778. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  779. EXPECT_EQ(result.size(), 1U);
  780. EXPECT_EQ(result[0], "*/*");
  781. EXPECT_TRUE(detail::parse_accept_header("*", result));
  782. EXPECT_EQ(result.size(), 1U);
  783. EXPECT_EQ(result[0], "*");
  784. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  785. EXPECT_EQ(result.size(), 1U);
  786. EXPECT_EQ(result[0], "text/*");
  787. }
  788. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  789. Server svr;
  790. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  791. EXPECT_EQ(req.accept_content_types.size(), 3U);
  792. EXPECT_EQ(req.accept_content_types[0], "application/json");
  793. EXPECT_EQ(req.accept_content_types[1], "text/html");
  794. EXPECT_EQ(req.accept_content_types[2], "*/*");
  795. res.set_content("ok", "text/plain");
  796. });
  797. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  798. EXPECT_TRUE(false);
  799. res.set_content("bad request", "text/plain");
  800. });
  801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  802. auto se = detail::scope_exit([&] {
  803. svr.stop();
  804. listen_thread.join();
  805. ASSERT_FALSE(svr.is_running());
  806. });
  807. svr.wait_until_ready();
  808. Client cli("localhost", PORT);
  809. {
  810. auto res = cli.Get(
  811. "/accept_ok",
  812. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  813. ASSERT_TRUE(res);
  814. EXPECT_EQ(StatusCode::OK_200, res->status);
  815. }
  816. {
  817. auto res = cli.Get("/accept_bad_request",
  818. Headers{{"Accept", "text/html;q=abc,application/json"}});
  819. ASSERT_TRUE(res);
  820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  821. }
  822. }
  823. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  824. Server svr;
  825. svr.Get("/", [](const Request & /*req*/, Response &res) {
  826. res.set_content("ok", "text/plain");
  827. });
  828. std::atomic<int> start_count{0};
  829. std::atomic<bool> running_when_called{false};
  830. svr.set_start_handler([&]() {
  831. running_when_called = svr.is_running();
  832. start_count++;
  833. });
  834. auto port = svr.bind_to_any_port(HOST);
  835. std::thread t([&]() { svr.listen_after_bind(); });
  836. auto se = detail::scope_exit([&] {
  837. svr.stop();
  838. t.join();
  839. ASSERT_FALSE(svr.is_running());
  840. });
  841. svr.wait_until_ready();
  842. // A successful request proves the accept loop is running, which the start
  843. // handler precedes; so by now the handler must have run exactly once.
  844. Client cli(HOST, port);
  845. cli.set_connection_timeout(std::chrono::seconds(5));
  846. auto res = cli.Get("/");
  847. ASSERT_TRUE(res);
  848. EXPECT_EQ(StatusCode::OK_200, res->status);
  849. EXPECT_EQ(1, start_count.load());
  850. EXPECT_TRUE(running_when_called.load());
  851. }
  852. TEST(DivideTest, DivideStringTests) {
  853. auto divide = [](const std::string &str, char d) {
  854. std::string lhs;
  855. std::string rhs;
  856. detail::divide(str, d,
  857. [&](const char *lhs_data, std::size_t lhs_size,
  858. const char *rhs_data, std::size_t rhs_size) {
  859. lhs.assign(lhs_data, lhs_size);
  860. rhs.assign(rhs_data, rhs_size);
  861. });
  862. return std::make_pair(std::move(lhs), std::move(rhs));
  863. };
  864. {
  865. const auto res = divide("", '=');
  866. EXPECT_EQ(res.first, "");
  867. EXPECT_EQ(res.second, "");
  868. }
  869. {
  870. const auto res = divide("=", '=');
  871. EXPECT_EQ(res.first, "");
  872. EXPECT_EQ(res.second, "");
  873. }
  874. {
  875. const auto res = divide(" ", '=');
  876. EXPECT_EQ(res.first, " ");
  877. EXPECT_EQ(res.second, "");
  878. }
  879. {
  880. const auto res = divide("a", '=');
  881. EXPECT_EQ(res.first, "a");
  882. EXPECT_EQ(res.second, "");
  883. }
  884. {
  885. const auto res = divide("a=", '=');
  886. EXPECT_EQ(res.first, "a");
  887. EXPECT_EQ(res.second, "");
  888. }
  889. {
  890. const auto res = divide("=b", '=');
  891. EXPECT_EQ(res.first, "");
  892. EXPECT_EQ(res.second, "b");
  893. }
  894. {
  895. const auto res = divide("a=b", '=');
  896. EXPECT_EQ(res.first, "a");
  897. EXPECT_EQ(res.second, "b");
  898. }
  899. {
  900. const auto res = divide("a=b=", '=');
  901. EXPECT_EQ(res.first, "a");
  902. EXPECT_EQ(res.second, "b=");
  903. }
  904. {
  905. const auto res = divide("a=b=c", '=');
  906. EXPECT_EQ(res.first, "a");
  907. EXPECT_EQ(res.second, "b=c");
  908. }
  909. }
  910. TEST(SplitTest, ParseQueryString) {
  911. string s = "key1=val1&key2=val2&key3=val3";
  912. Params dic;
  913. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  914. [&](const char *b, const char *e) {
  915. string key, val;
  916. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  917. if (key.empty()) {
  918. key.assign(b2, e2);
  919. } else {
  920. val.assign(b2, e2);
  921. }
  922. });
  923. dic.emplace(key, val);
  924. });
  925. EXPECT_EQ("val1", dic.find("key1")->second);
  926. EXPECT_EQ("val2", dic.find("key2")->second);
  927. EXPECT_EQ("val3", dic.find("key3")->second);
  928. }
  929. TEST(SplitTest, ParseInvalidQueryTests) {
  930. {
  931. string s = " ";
  932. Params dict;
  933. detail::parse_query_text(s, dict);
  934. EXPECT_TRUE(dict.empty());
  935. }
  936. {
  937. string s = " = =";
  938. Params dict;
  939. detail::parse_query_text(s, dict);
  940. EXPECT_TRUE(dict.empty());
  941. }
  942. }
  943. TEST(ParseQueryTest, ParseQueryString) {
  944. {
  945. std::string s = "key1=val1&key2=val2&key3=val3";
  946. Params dic;
  947. detail::parse_query_text(s, dic);
  948. EXPECT_EQ("val1", dic.find("key1")->second);
  949. EXPECT_EQ("val2", dic.find("key2")->second);
  950. EXPECT_EQ("val3", dic.find("key3")->second);
  951. }
  952. {
  953. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  954. Params dic;
  955. detail::parse_query_text(s, dic);
  956. EXPECT_EQ("", dic.find("key1")->second);
  957. EXPECT_EQ("val1", dic.find("key2")->second);
  958. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  959. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  960. }
  961. }
  962. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  963. Params dic;
  964. EXPECT_EQ(detail::params_to_query_str(dic), "");
  965. dic.emplace("key1", "val1");
  966. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  967. dic.emplace("key2", "val2");
  968. dic.emplace("key3", "val3");
  969. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  970. }
  971. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  972. string content_type = "multipart/form-data; boundary=something";
  973. string boundary;
  974. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  975. EXPECT_TRUE(ret);
  976. EXPECT_EQ(boundary, "something");
  977. }
  978. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  979. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  980. string boundary;
  981. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  982. EXPECT_TRUE(ret);
  983. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  984. }
  985. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  986. string content_type =
  987. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  988. string boundary;
  989. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  990. EXPECT_TRUE(ret);
  991. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  992. }
  993. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  994. string content_type =
  995. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  996. string boundary;
  997. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  998. EXPECT_TRUE(ret);
  999. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1000. }
  1001. TEST(GetHeaderValueTest, DefaultValue) {
  1002. Headers headers = {{"Dummy", "Dummy"}};
  1003. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1004. EXPECT_STREQ("text/plain", val);
  1005. }
  1006. TEST(GetHeaderValueTest, DefaultValueInt) {
  1007. Headers headers = {{"Dummy", "Dummy"}};
  1008. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1009. EXPECT_EQ(100ull, val);
  1010. }
  1011. TEST(GetHeaderValueTest, RegularValue) {
  1012. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1013. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1014. EXPECT_STREQ("text/html", val);
  1015. }
  1016. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1017. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1018. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1019. EXPECT_STREQ("text/html", val);
  1020. }
  1021. TEST(GetHeaderValueTest, SetContent) {
  1022. Response res;
  1023. res.set_content("html", "text/html");
  1024. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1025. res.set_content("text", "text/plain");
  1026. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1027. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1028. }
  1029. TEST(GetHeaderValueTest, RegularValueInt) {
  1030. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1031. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1032. EXPECT_EQ(100ull, val);
  1033. }
  1034. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1035. Headers headers = {{"Content-Length", "x"}};
  1036. auto is_invalid_value = false;
  1037. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1038. is_invalid_value);
  1039. EXPECT_EQ(0ull, val);
  1040. EXPECT_TRUE(is_invalid_value);
  1041. }
  1042. TEST(GetHeaderValueTest, Range) {
  1043. {
  1044. Headers headers = {make_range_header({{1, -1}})};
  1045. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1046. EXPECT_STREQ("bytes=1-", val);
  1047. }
  1048. {
  1049. Headers headers = {make_range_header({{-1, 1}})};
  1050. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1051. EXPECT_STREQ("bytes=-1", val);
  1052. }
  1053. {
  1054. Headers headers = {make_range_header({{1, 10}})};
  1055. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1056. EXPECT_STREQ("bytes=1-10", val);
  1057. }
  1058. {
  1059. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1060. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1061. EXPECT_STREQ("bytes=1-10, 100-", val);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1065. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1066. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1067. }
  1068. {
  1069. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1070. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1071. EXPECT_STREQ("bytes=0-0, -1", val);
  1072. }
  1073. }
  1074. TEST(ParseHeaderValueTest, Range) {
  1075. {
  1076. Ranges ranges;
  1077. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1078. EXPECT_TRUE(ret);
  1079. EXPECT_EQ(1u, ranges.size());
  1080. EXPECT_EQ(1u, ranges[0].first);
  1081. EXPECT_EQ(-1, ranges[0].second);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(1u, ranges.size());
  1088. EXPECT_EQ(-1, ranges[0].first);
  1089. EXPECT_EQ(1u, ranges[0].second);
  1090. }
  1091. {
  1092. Ranges ranges;
  1093. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1094. EXPECT_TRUE(ret);
  1095. EXPECT_EQ(1u, ranges.size());
  1096. EXPECT_EQ(1u, ranges[0].first);
  1097. EXPECT_EQ(10u, ranges[0].second);
  1098. }
  1099. {
  1100. Ranges ranges;
  1101. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1102. EXPECT_FALSE(ret);
  1103. }
  1104. {
  1105. Ranges ranges;
  1106. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1107. EXPECT_TRUE(ret);
  1108. EXPECT_EQ(2u, ranges.size());
  1109. EXPECT_EQ(1u, ranges[0].first);
  1110. EXPECT_EQ(10u, ranges[0].second);
  1111. EXPECT_EQ(100u, ranges[1].first);
  1112. EXPECT_EQ(-1, ranges[1].second);
  1113. }
  1114. {
  1115. Ranges ranges;
  1116. auto ret =
  1117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1118. EXPECT_TRUE(ret);
  1119. EXPECT_EQ(3u, ranges.size());
  1120. EXPECT_EQ(1u, ranges[0].first);
  1121. EXPECT_EQ(10u, ranges[0].second);
  1122. EXPECT_EQ(100u, ranges[1].first);
  1123. EXPECT_EQ(200u, ranges[1].second);
  1124. EXPECT_EQ(300u, ranges[2].first);
  1125. EXPECT_EQ(400u, ranges[2].second);
  1126. }
  1127. {
  1128. Ranges ranges;
  1129. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1130. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1131. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1132. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1133. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1134. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1135. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1136. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1137. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1138. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1139. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1140. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1141. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1142. EXPECT_TRUE(ranges.empty());
  1143. }
  1144. }
  1145. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1146. Request req;
  1147. req.set_header("Accept-Encoding", "gzip");
  1148. Response res;
  1149. res.set_header("Content-Type", "text/plain");
  1150. auto ret = detail::encoding_type(req, res);
  1151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1152. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1153. #else
  1154. EXPECT_TRUE(ret == detail::EncodingType::None);
  1155. #endif
  1156. }
  1157. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1158. Request req;
  1159. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1160. Response res;
  1161. res.set_header("Content-Type", "text/plain");
  1162. auto ret = detail::encoding_type(req, res);
  1163. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1165. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1167. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1168. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1169. #else
  1170. EXPECT_TRUE(ret == detail::EncodingType::None);
  1171. #endif
  1172. }
  1173. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1174. Request req;
  1175. req.set_header("Accept-Encoding",
  1176. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1177. Response res;
  1178. res.set_header("Content-Type", "text/plain");
  1179. auto ret = detail::encoding_type(req, res);
  1180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1182. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1184. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1185. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1186. #else
  1187. EXPECT_TRUE(ret == detail::EncodingType::None);
  1188. #endif
  1189. }
  1190. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1191. // All supported encodings rejected with q=0 should return None
  1192. Request req;
  1193. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1194. Response res;
  1195. res.set_header("Content-Type", "text/plain");
  1196. auto ret = detail::encoding_type(req, res);
  1197. EXPECT_TRUE(ret == detail::EncodingType::None);
  1198. }
  1199. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1200. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1201. Request req;
  1202. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1203. Response res;
  1204. res.set_header("Content-Type", "text/plain");
  1205. auto ret = detail::encoding_type(req, res);
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. }
  1208. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1209. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1210. Request req;
  1211. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1212. Response res;
  1213. res.set_header("Content-Type", "text/plain");
  1214. auto ret = detail::encoding_type(req, res);
  1215. EXPECT_TRUE(ret == detail::EncodingType::None);
  1216. }
  1217. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1218. // RFC 7231: Accept-Encoding values are case-insensitive
  1219. Request req;
  1220. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1221. Response res;
  1222. res.set_header("Content-Type", "text/plain");
  1223. auto ret = detail::encoding_type(req, res);
  1224. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1226. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1228. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1229. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1230. #else
  1231. EXPECT_TRUE(ret == detail::EncodingType::None);
  1232. #endif
  1233. }
  1234. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1235. // q value should determine priority, not hardcoded order
  1236. Request req;
  1237. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1238. Response res;
  1239. res.set_header("Content-Type", "text/plain");
  1240. auto ret = detail::encoding_type(req, res);
  1241. // gzip has highest q=1.0, so it should be selected even though
  1242. // br and zstd are also supported
  1243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1244. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1245. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1246. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1247. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1248. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1249. #else
  1250. EXPECT_TRUE(ret == detail::EncodingType::None);
  1251. #endif
  1252. }
  1253. TEST(BufferStreamTest, read) {
  1254. detail::BufferStream strm1;
  1255. Stream &strm = strm1;
  1256. EXPECT_EQ(5, strm.write("hello"));
  1257. char buf[512];
  1258. EXPECT_EQ(2, strm.read(buf, 2));
  1259. EXPECT_EQ('h', buf[0]);
  1260. EXPECT_EQ('e', buf[1]);
  1261. EXPECT_EQ(2, strm.read(buf, 2));
  1262. EXPECT_EQ('l', buf[0]);
  1263. EXPECT_EQ('l', buf[1]);
  1264. EXPECT_EQ(1, strm.read(buf, 1));
  1265. EXPECT_EQ('o', buf[0]);
  1266. EXPECT_EQ(0, strm.read(buf, 1));
  1267. }
  1268. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1269. auto host = "www.httpwatch.com";
  1270. auto ip = hosted_at(host);
  1271. EXPECT_EQ("23.96.13.243", ip);
  1272. std::vector<std::string> addrs;
  1273. hosted_at(host, addrs);
  1274. EXPECT_EQ(1u, addrs.size());
  1275. }
  1276. #if 0 // It depends on each test environment...
  1277. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1278. auto host = "www.youtube.com";
  1279. std::vector<std::string> addrs;
  1280. hosted_at(host, addrs);
  1281. EXPECT_EQ(20u, addrs.size());
  1282. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1283. EXPECT_TRUE(it != addrs.end());
  1284. }
  1285. #endif
  1286. class ChunkedEncodingTest : public ::testing::Test {
  1287. protected:
  1288. ChunkedEncodingTest()
  1289. : cli_(HOST, PORT)
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. ,
  1292. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1293. #endif
  1294. {
  1295. cli_.set_connection_timeout(2);
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. cli_.enable_server_certificate_verification(false);
  1298. #endif
  1299. }
  1300. virtual void SetUp() {
  1301. read_file("./image.jpg", image_data_);
  1302. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1303. res.set_content("Hello World!", "text/plain");
  1304. });
  1305. svr_.Get(
  1306. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1307. res.set_chunked_content_provider(
  1308. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1309. size_t remaining = image_data_.size() - offset;
  1310. if (remaining == 0) {
  1311. sink.done();
  1312. } else {
  1313. constexpr size_t CHUNK_SIZE = 1024;
  1314. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1315. sink.write(&image_data_[offset], send_size);
  1316. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1317. }
  1318. return true;
  1319. });
  1320. });
  1321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1322. svr_.wait_until_ready();
  1323. }
  1324. virtual void TearDown() {
  1325. svr_.stop();
  1326. if (!request_threads_.empty()) {
  1327. std::this_thread::sleep_for(std::chrono::seconds(1));
  1328. for (auto &t : request_threads_) {
  1329. t.join();
  1330. }
  1331. }
  1332. t_.join();
  1333. }
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli_;
  1336. SSLServer svr_;
  1337. #else
  1338. Client cli_;
  1339. Server svr_;
  1340. #endif
  1341. thread t_;
  1342. std::vector<thread> request_threads_;
  1343. std::string image_data_;
  1344. };
  1345. TEST_F(ChunkedEncodingTest, NormalGet) {
  1346. auto res = cli_.Get("/chunked");
  1347. ASSERT_TRUE(res);
  1348. std::string out;
  1349. read_file("./image.jpg", out);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. EXPECT_EQ(out, res->body);
  1352. }
  1353. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1354. std::string body;
  1355. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1356. body.append(data, data_length);
  1357. return true;
  1358. });
  1359. ASSERT_TRUE(res);
  1360. std::string out;
  1361. read_file("./image.jpg", out);
  1362. EXPECT_EQ(StatusCode::OK_200, res->status);
  1363. EXPECT_EQ(out, body);
  1364. }
  1365. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1366. std::string body;
  1367. auto res = cli_.Get(
  1368. "/chunked",
  1369. [&](const Response &response) {
  1370. EXPECT_EQ(StatusCode::OK_200, response.status);
  1371. return true;
  1372. },
  1373. [&](const char *data, size_t data_length) {
  1374. body.append(data, data_length);
  1375. return true;
  1376. });
  1377. ASSERT_TRUE(res);
  1378. std::string out;
  1379. read_file("./image.jpg", out);
  1380. EXPECT_EQ(StatusCode::OK_200, res->status);
  1381. EXPECT_EQ(out, body);
  1382. }
  1383. TEST(RangeTest, FromHTTPBin_Online) {
  1384. auto host = "httpbingo.org";
  1385. auto path = std::string{"/range/32"};
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(5);
  1394. {
  1395. auto res = cli.Get(path);
  1396. ASSERT_TRUE(res);
  1397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1398. EXPECT_EQ(StatusCode::OK_200, res->status);
  1399. }
  1400. {
  1401. Headers headers = {make_range_header({{1, -1}})};
  1402. auto res = cli.Get(path, headers);
  1403. ASSERT_TRUE(res);
  1404. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1406. }
  1407. {
  1408. Headers headers = {make_range_header({{1, 10}})};
  1409. auto res = cli.Get(path, headers);
  1410. ASSERT_TRUE(res);
  1411. EXPECT_EQ("bcdefghijk", res->body);
  1412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1413. }
  1414. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1415. // entire resource, while the original httpbin returned 200. Both are
  1416. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1417. {
  1418. Headers headers = {make_range_header({{0, 31}})};
  1419. auto res = cli.Get(path, headers);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1422. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1423. res->status == StatusCode::PartialContent_206);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{0, -1}})};
  1427. auto res = cli.Get(path, headers);
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1430. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1431. res->status == StatusCode::PartialContent_206);
  1432. }
  1433. // go-httpbin returns 206 with clamped range for over-range requests,
  1434. // while the original httpbin returned 416. Both behaviors are observed
  1435. // in real servers, so we only verify the request succeeds.
  1436. {
  1437. Headers headers = {make_range_header({{0, 32}})};
  1438. auto res = cli.Get(path, headers);
  1439. ASSERT_TRUE(res);
  1440. }
  1441. }
  1442. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1443. auto host = "unresolvableaddress.local";
  1444. auto path = std::string{"/"};
  1445. #ifdef CPPHTTPLIB_SSL_ENABLED
  1446. auto port = 443;
  1447. SSLClient cli(host, port);
  1448. #else
  1449. auto port = 80;
  1450. Client cli(host, port);
  1451. #endif
  1452. cli.set_connection_timeout(1);
  1453. {
  1454. auto res = cli.Get(path);
  1455. ASSERT_FALSE(res);
  1456. }
  1457. std::this_thread::sleep_for(std::chrono::seconds(8));
  1458. }
  1459. #if defined(__linux__) && defined(__GLIBC__) && \
  1460. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1461. // Forward declaration: in split builds split.py strips `inline` and moves the
  1462. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1463. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1464. // against the symbol in both header-only and split builds.
  1465. namespace httplib {
  1466. namespace detail {
  1467. int getaddrinfo_with_timeout(const char *node, const char *service,
  1468. const struct addrinfo *hints,
  1469. struct addrinfo **res, time_t timeout_sec);
  1470. } // namespace detail
  1471. } // namespace httplib
  1472. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1473. //
  1474. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1475. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1476. // gai_suspend() call hits the connection timeout the function calls
  1477. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1478. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1479. // still alive and still references the now-destroyed stack frame.
  1480. //
  1481. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1482. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1483. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1484. // and runs them in a container.
  1485. namespace {
  1486. bool should_run_issue_2431_tests() {
  1487. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1488. return v && *v && std::string(v) != "0";
  1489. }
  1490. std::string unique_unresolvable_host(int n) {
  1491. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1492. // glibc still asks the configured nameserver — which is exactly the path
  1493. // we want to exercise. A unique label per call avoids the resolver cache.
  1494. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1495. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1496. std::to_string(n) + ".invalid";
  1497. }
  1498. } // namespace
  1499. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1500. if (!should_run_issue_2431_tests()) {
  1501. GTEST_SKIP()
  1502. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1503. }
  1504. for (int i = 0; i < 8; ++i) {
  1505. struct addrinfo hints;
  1506. memset(&hints, 0, sizeof(hints));
  1507. hints.ai_family = AF_UNSPEC;
  1508. hints.ai_socktype = SOCK_STREAM;
  1509. auto host = unique_unresolvable_host(i);
  1510. struct addrinfo *result = nullptr;
  1511. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1512. &result, /*timeout_sec=*/1);
  1513. if (rc == 0 && result) { freeaddrinfo(result); }
  1514. }
  1515. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1516. // stack region they still believe holds their gaicb.
  1517. std::this_thread::sleep_for(std::chrono::seconds(3));
  1518. }
  1519. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1520. if (!should_run_issue_2431_tests()) {
  1521. GTEST_SKIP()
  1522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1523. }
  1524. std::atomic<bool> stop{false};
  1525. std::vector<std::thread> threads;
  1526. for (int t = 0; t < 8; ++t) {
  1527. threads.emplace_back([t, &stop] {
  1528. int i = 0;
  1529. while (!stop.load(std::memory_order_relaxed)) {
  1530. struct addrinfo hints;
  1531. memset(&hints, 0, sizeof(hints));
  1532. hints.ai_family = AF_UNSPEC;
  1533. hints.ai_socktype = SOCK_STREAM;
  1534. auto host = unique_unresolvable_host(t * 100000 + i++);
  1535. struct addrinfo *result = nullptr;
  1536. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1537. &result, /*timeout_sec=*/1);
  1538. if (rc == 0 && result) { freeaddrinfo(result); }
  1539. }
  1540. });
  1541. }
  1542. std::this_thread::sleep_for(std::chrono::seconds(8));
  1543. stop.store(true, std::memory_order_relaxed);
  1544. for (auto &th : threads) {
  1545. th.join();
  1546. }
  1547. std::this_thread::sleep_for(std::chrono::seconds(3));
  1548. }
  1549. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1550. if (!should_run_issue_2431_tests()) {
  1551. GTEST_SKIP()
  1552. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1553. }
  1554. std::atomic<bool> stop{false};
  1555. std::vector<std::thread> threads;
  1556. for (int t = 0; t < 8; ++t) {
  1557. threads.emplace_back([t, &stop] {
  1558. int i = 0;
  1559. while (!stop.load(std::memory_order_relaxed)) {
  1560. auto host = unique_unresolvable_host(t * 100000 + i++);
  1561. Client cli(host, 80);
  1562. cli.set_connection_timeout(1, 0);
  1563. cli.set_read_timeout(1, 0);
  1564. cli.set_write_timeout(1, 0);
  1565. (void)cli.Get("/");
  1566. }
  1567. });
  1568. }
  1569. std::this_thread::sleep_for(std::chrono::seconds(8));
  1570. stop.store(true, std::memory_order_relaxed);
  1571. for (auto &th : threads) {
  1572. th.join();
  1573. }
  1574. std::this_thread::sleep_for(std::chrono::seconds(3));
  1575. }
  1576. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1577. TEST(ConnectionErrorTest, InvalidHost) {
  1578. auto host = "-abcde.com";
  1579. #ifdef CPPHTTPLIB_SSL_ENABLED
  1580. auto port = 443;
  1581. SSLClient cli(host, port);
  1582. #else
  1583. auto port = 80;
  1584. Client cli(host, port);
  1585. #endif
  1586. cli.set_connection_timeout(std::chrono::seconds(2));
  1587. auto res = cli.Get("/");
  1588. ASSERT_TRUE(!res);
  1589. EXPECT_EQ(Error::Connection, res.error());
  1590. }
  1591. TEST(ConnectionErrorTest, InvalidHost2) {
  1592. auto host = "httpcan.org/";
  1593. #ifdef CPPHTTPLIB_SSL_ENABLED
  1594. SSLClient cli(host);
  1595. #else
  1596. Client cli(host);
  1597. #endif
  1598. cli.set_connection_timeout(std::chrono::seconds(2));
  1599. auto res = cli.Get("/");
  1600. ASSERT_TRUE(!res);
  1601. EXPECT_EQ(Error::Connection, res.error());
  1602. }
  1603. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1604. auto host = "httpcan.org/";
  1605. #ifdef CPPHTTPLIB_SSL_ENABLED
  1606. SSLClient cli(host);
  1607. #else
  1608. Client cli(host);
  1609. #endif
  1610. cli.set_connection_timeout(std::chrono::seconds(2));
  1611. auto res = cli.Get("/");
  1612. ASSERT_TRUE(!res);
  1613. stringstream s;
  1614. s << "error code: " << res.error();
  1615. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1616. }
  1617. TEST(ConnectionErrorTest, InvalidPort) {
  1618. auto host = "localhost";
  1619. auto port = 44380;
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. SSLClient cli(host, port);
  1622. #else
  1623. Client cli(host, port);
  1624. #endif
  1625. cli.set_connection_timeout(std::chrono::seconds(2));
  1626. auto res = cli.Get("/");
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_TRUE(Error::Connection == res.error() ||
  1629. Error::ConnectionTimeout == res.error());
  1630. }
  1631. TEST(ConnectionErrorTest, Timeout_Online) {
  1632. auto host = "google.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 44380;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 8080;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. // only probe one address type so that the error reason
  1642. // correlates to the timed-out IPv4, not the unsupported
  1643. // IPv6 connection attempt
  1644. cli.set_address_family(AF_INET);
  1645. auto res = cli.Get("/");
  1646. ASSERT_TRUE(!res);
  1647. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1648. }
  1649. TEST(CancelTest, NoCancel_Online) {
  1650. auto host = "httpbingo.org";
  1651. auto path = std::string{"/range/32"};
  1652. #ifdef CPPHTTPLIB_SSL_ENABLED
  1653. auto port = 443;
  1654. SSLClient cli(host, port);
  1655. #else
  1656. auto port = 80;
  1657. Client cli(host, port);
  1658. #endif
  1659. cli.set_connection_timeout(std::chrono::seconds(5));
  1660. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1666. // Use /bytes with a large payload so that the DownloadProgress callback
  1667. // (which only fires for Content-Length responses) is invoked before the
  1668. // entire body is received, giving cancellation a chance to fire.
  1669. auto host = "httpbingo.org";
  1670. auto path = std::string{"/bytes/524288"};
  1671. #ifdef CPPHTTPLIB_SSL_ENABLED
  1672. auto port = 443;
  1673. SSLClient cli(host, port);
  1674. #else
  1675. auto port = 80;
  1676. Client cli(host, port);
  1677. #endif
  1678. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1679. cli.set_connection_timeout(std::chrono::seconds(5));
  1680. ASSERT_TRUE(!res);
  1681. EXPECT_EQ(Error::Canceled, res.error());
  1682. }
  1683. TEST(CancelTest, WithCancelLargePayload_Online) {
  1684. auto host = "httpbingo.org";
  1685. auto path = std::string{"/bytes/524288"};
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. auto port = 443;
  1688. SSLClient cli(host, port);
  1689. #else
  1690. auto port = 80;
  1691. Client cli(host, port);
  1692. #endif
  1693. cli.set_connection_timeout(std::chrono::seconds(5));
  1694. uint32_t count = 0;
  1695. auto res =
  1696. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1697. ASSERT_TRUE(!res);
  1698. EXPECT_EQ(Error::Canceled, res.error());
  1699. }
  1700. TEST(CancelTest, NoCancelPost) {
  1701. Server svr;
  1702. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1703. res.set_content("Hello World!", "text/plain");
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. Client cli(HOST, PORT);
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res =
  1715. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1716. "application/json", [](uint64_t, uint64_t) { return true; });
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ("Hello World!", res->body);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. }
  1721. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1722. Server svr;
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content("Hello World!", "text/plain");
  1725. });
  1726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. Client cli(HOST, PORT);
  1734. cli.set_connection_timeout(std::chrono::seconds(5));
  1735. auto res =
  1736. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1737. "application/json", [](uint64_t, uint64_t) { return false; });
  1738. ASSERT_TRUE(!res);
  1739. EXPECT_EQ(Error::Canceled, res.error());
  1740. }
  1741. TEST(CancelTest, WithCancelLargePayloadPost) {
  1742. Server svr;
  1743. svr.set_payload_max_length(200 * 1024 * 1024);
  1744. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content(LARGE_DATA, "text/plain");
  1746. });
  1747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1748. auto se = detail::scope_exit([&] {
  1749. svr.stop();
  1750. thread.join();
  1751. ASSERT_FALSE(svr.is_running());
  1752. });
  1753. svr.wait_until_ready();
  1754. Client cli(HOST, PORT);
  1755. cli.set_payload_max_length(200 * 1024 * 1024);
  1756. cli.set_connection_timeout(std::chrono::seconds(5));
  1757. auto res =
  1758. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1759. "application/json", [](uint64_t, uint64_t) { return false; });
  1760. ASSERT_TRUE(!res);
  1761. EXPECT_EQ(Error::Canceled, res.error());
  1762. }
  1763. TEST(CancelTest, NoCancelPut) {
  1764. Server svr;
  1765. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1766. res.set_content("Hello World!", "text/plain");
  1767. });
  1768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1769. auto se = detail::scope_exit([&] {
  1770. svr.stop();
  1771. thread.join();
  1772. ASSERT_FALSE(svr.is_running());
  1773. });
  1774. svr.wait_until_ready();
  1775. Client cli(HOST, PORT);
  1776. cli.set_connection_timeout(std::chrono::seconds(5));
  1777. auto res =
  1778. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1779. "application/json", [](uint64_t, uint64_t) { return true; });
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ("Hello World!", res->body);
  1782. EXPECT_EQ(StatusCode::OK_200, res->status);
  1783. }
  1784. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1785. Server svr;
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content("Hello World!", "text/plain");
  1788. });
  1789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1790. auto se = detail::scope_exit([&] {
  1791. svr.stop();
  1792. thread.join();
  1793. ASSERT_FALSE(svr.is_running());
  1794. });
  1795. svr.wait_until_ready();
  1796. Client cli(HOST, PORT);
  1797. cli.set_connection_timeout(std::chrono::seconds(5));
  1798. auto res =
  1799. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1800. "application/json", [](uint64_t, uint64_t) { return false; });
  1801. ASSERT_TRUE(!res);
  1802. EXPECT_EQ(Error::Canceled, res.error());
  1803. }
  1804. TEST(CancelTest, WithCancelLargePayloadPut) {
  1805. Server svr;
  1806. svr.set_payload_max_length(200 * 1024 * 1024);
  1807. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content(LARGE_DATA, "text/plain");
  1809. });
  1810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1811. auto se = detail::scope_exit([&] {
  1812. svr.stop();
  1813. thread.join();
  1814. ASSERT_FALSE(svr.is_running());
  1815. });
  1816. svr.wait_until_ready();
  1817. Client cli(HOST, PORT);
  1818. cli.set_payload_max_length(200 * 1024 * 1024);
  1819. cli.set_connection_timeout(std::chrono::seconds(5));
  1820. auto res =
  1821. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1822. "application/json", [](uint64_t, uint64_t) { return false; });
  1823. ASSERT_TRUE(!res);
  1824. EXPECT_EQ(Error::Canceled, res.error());
  1825. }
  1826. TEST(CancelTest, NoCancelPatch) {
  1827. Server svr;
  1828. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1829. res.set_content("Hello World!", "text/plain");
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. Client cli(HOST, PORT);
  1839. cli.set_connection_timeout(std::chrono::seconds(5));
  1840. auto res =
  1841. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1842. "application/json", [](uint64_t, uint64_t) { return true; });
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ("Hello World!", res->body);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. }
  1847. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1848. Server svr;
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!", "text/plain");
  1851. });
  1852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1853. auto se = detail::scope_exit([&] {
  1854. svr.stop();
  1855. thread.join();
  1856. ASSERT_FALSE(svr.is_running());
  1857. });
  1858. svr.wait_until_ready();
  1859. Client cli(HOST, PORT);
  1860. cli.set_connection_timeout(std::chrono::seconds(5));
  1861. auto res =
  1862. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1863. "application/json", [](uint64_t, uint64_t) { return false; });
  1864. ASSERT_TRUE(!res);
  1865. EXPECT_EQ(Error::Canceled, res.error());
  1866. }
  1867. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1868. Server svr;
  1869. svr.set_payload_max_length(200 * 1024 * 1024);
  1870. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content(LARGE_DATA, "text/plain");
  1872. });
  1873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. Client cli(HOST, PORT);
  1881. cli.set_payload_max_length(200 * 1024 * 1024);
  1882. cli.set_connection_timeout(std::chrono::seconds(5));
  1883. auto res =
  1884. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1885. "application/json", [](uint64_t, uint64_t) { return false; });
  1886. ASSERT_TRUE(!res);
  1887. EXPECT_EQ(Error::Canceled, res.error());
  1888. }
  1889. TEST(CancelTest, NoCancelDelete) {
  1890. Server svr;
  1891. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1892. res.set_content("Hello World!", "text/plain");
  1893. });
  1894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1895. auto se = detail::scope_exit([&] {
  1896. svr.stop();
  1897. thread.join();
  1898. ASSERT_FALSE(svr.is_running());
  1899. });
  1900. svr.wait_until_ready();
  1901. Client cli(HOST, PORT);
  1902. cli.set_connection_timeout(std::chrono::seconds(5));
  1903. auto res =
  1904. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1905. "application/json", [](uint64_t, uint64_t) { return true; });
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("Hello World!", res->body);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. }
  1910. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1911. Server svr;
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. thread.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. Client cli(HOST, PORT);
  1923. cli.set_connection_timeout(std::chrono::seconds(5));
  1924. auto res =
  1925. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1926. "application/json", [](uint64_t, uint64_t) { return false; });
  1927. ASSERT_TRUE(!res);
  1928. EXPECT_EQ(Error::Canceled, res.error());
  1929. }
  1930. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1931. Server svr;
  1932. svr.set_payload_max_length(200 * 1024 * 1024);
  1933. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1934. res.set_content(LARGE_DATA, "text/plain");
  1935. });
  1936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1937. auto se = detail::scope_exit([&] {
  1938. svr.stop();
  1939. thread.join();
  1940. ASSERT_FALSE(svr.is_running());
  1941. });
  1942. svr.wait_until_ready();
  1943. Client cli(HOST, PORT);
  1944. cli.set_payload_max_length(200 * 1024 * 1024);
  1945. cli.set_connection_timeout(std::chrono::seconds(5));
  1946. auto res =
  1947. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1948. "application/json", [](uint64_t, uint64_t) { return false; });
  1949. ASSERT_TRUE(!res);
  1950. EXPECT_EQ(Error::Canceled, res.error());
  1951. }
  1952. static std::string remove_whitespace(const std::string &input) {
  1953. std::string output;
  1954. output.reserve(input.size());
  1955. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1956. [](unsigned char c) { return !std::isspace(c); });
  1957. return output;
  1958. }
  1959. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1960. auto host = "httpbingo.org";
  1961. auto path = std::string{"/basic-auth/hello/world"};
  1962. #ifdef CPPHTTPLIB_SSL_ENABLED
  1963. auto port = 443;
  1964. SSLClient cli(host, port);
  1965. #else
  1966. auto port = 80;
  1967. Client cli(host, port);
  1968. #endif
  1969. {
  1970. auto res = cli.Get(path);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1973. }
  1974. {
  1975. auto res = cli.Get(
  1976. path, Headers{make_basic_authentication_header("hello", "world")});
  1977. ASSERT_TRUE(res);
  1978. auto body = remove_whitespace(res->body);
  1979. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1980. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. cli.set_basic_auth("hello", "world");
  1985. auto res = cli.Get(path);
  1986. ASSERT_TRUE(res);
  1987. auto body = remove_whitespace(res->body);
  1988. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1989. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. }
  1992. {
  1993. cli.set_basic_auth("hello", "bad");
  1994. auto res = cli.Get(path);
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1997. }
  1998. {
  1999. cli.set_basic_auth("bad", "world");
  2000. auto res = cli.Get(path);
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2003. }
  2004. }
  2005. #ifdef CPPHTTPLIB_SSL_ENABLED
  2006. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2007. auto host = "httpbingo.org";
  2008. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2009. auto paths = std::vector<std::string>{
  2010. "/digest-auth/auth/hello/world/MD5",
  2011. "/digest-auth/auth/hello/world/SHA-256",
  2012. };
  2013. auto port = 443;
  2014. SSLClient cli(host, port);
  2015. {
  2016. auto res = cli.Get(unauth_path);
  2017. ASSERT_TRUE(res);
  2018. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2019. }
  2020. {
  2021. cli.set_digest_auth("hello", "world");
  2022. for (const auto &path : paths) {
  2023. auto res = cli.Get(path.c_str());
  2024. ASSERT_TRUE(res);
  2025. auto body = remove_whitespace(res->body);
  2026. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2027. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. }
  2030. cli.set_digest_auth("hello", "bad");
  2031. for (const auto &path : paths) {
  2032. auto res = cli.Get(path.c_str());
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. }
  2037. }
  2038. #endif
  2039. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2040. auto host = "google.com";
  2041. auto another_host = "example.com";
  2042. auto wrong_ip = "0.0.0.0";
  2043. #ifdef CPPHTTPLIB_SSL_ENABLED
  2044. SSLClient cli(host);
  2045. #else
  2046. Client cli(host);
  2047. #endif
  2048. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2049. auto res = cli.Get("/");
  2050. ASSERT_TRUE(res);
  2051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2052. }
  2053. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2054. auto host = "google.com";
  2055. auto wrong_ip = "0.0.0.0";
  2056. #ifdef CPPHTTPLIB_SSL_ENABLED
  2057. SSLClient cli(host);
  2058. #else
  2059. Client cli(host);
  2060. #endif
  2061. cli.set_hostname_addr_map({{host, wrong_ip}});
  2062. auto res = cli.Get("/");
  2063. ASSERT_TRUE(!res);
  2064. EXPECT_EQ(Error::Connection, res.error());
  2065. }
  2066. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto path = std::string{"/absolute-redirect/3"};
  2069. #ifdef CPPHTTPLIB_SSL_ENABLED
  2070. SSLClient cli(host);
  2071. #else
  2072. Client cli(host);
  2073. #endif
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get(path);
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. }
  2079. TEST(RedirectTest, Redirect_Online) {
  2080. auto host = "httpbingo.org";
  2081. auto path = std::string{"/redirect/3"};
  2082. #ifdef CPPHTTPLIB_SSL_ENABLED
  2083. SSLClient cli(host);
  2084. #else
  2085. Client cli(host);
  2086. #endif
  2087. cli.set_follow_location(true);
  2088. auto res = cli.Get(path);
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. TEST(RelativeRedirectTest, Redirect_Online) {
  2093. auto host = "httpbingo.org";
  2094. auto path = std::string{"/relative-redirect/3"};
  2095. #ifdef CPPHTTPLIB_SSL_ENABLED
  2096. SSLClient cli(host);
  2097. #else
  2098. Client cli(host);
  2099. #endif
  2100. cli.set_follow_location(true);
  2101. auto res = cli.Get(path);
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. }
  2105. TEST(TooManyRedirectTest, Redirect_Online) {
  2106. auto host = "httpbingo.org";
  2107. auto path = std::string{"/redirect/21"};
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. SSLClient cli(host);
  2110. #else
  2111. Client cli(host);
  2112. #endif
  2113. cli.set_follow_location(true);
  2114. auto res = cli.Get(path);
  2115. ASSERT_TRUE(!res);
  2116. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2117. }
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. TEST(YahooRedirectTest, Redirect_Online) {
  2120. Client cli("yahoo.com");
  2121. auto res = cli.Get("/");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2124. cli.set_follow_location(true);
  2125. res = cli.Get("/");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2129. }
  2130. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2131. #define REDIR_HOST "httpbingo.org"
  2132. #define REDIR_PATH "/redirect-to"
  2133. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2134. SSLClient cli(REDIR_HOST);
  2135. cli.set_follow_location(true);
  2136. auto res =
  2137. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. }
  2141. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2142. SSLClient cli(REDIR_HOST);
  2143. cli.set_follow_location(true);
  2144. Params params;
  2145. params.emplace("url", "http://example.com");
  2146. params.emplace("status_code", "302");
  2147. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(StatusCode::OK_200, res->status);
  2150. }
  2151. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2152. SSLClient cli(REDIR_HOST);
  2153. cli.set_follow_location(true);
  2154. Params params;
  2155. params.emplace("url", "http://example.com");
  2156. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2157. ASSERT_TRUE(res);
  2158. EXPECT_EQ(StatusCode::OK_200, res->status);
  2159. }
  2160. TEST(UrlWithSpace, Redirect_Online) {
  2161. SSLClient cli("edge.forgecdn.net");
  2162. cli.set_follow_location(true);
  2163. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2167. }
  2168. #endif
  2169. #if !defined(_WIN32) && !defined(_WIN64)
  2170. TEST(ReceiveSignals, Signal) {
  2171. auto setupSignalHandlers = []() {
  2172. struct sigaction act;
  2173. sigemptyset(&act.sa_mask);
  2174. act.sa_flags = SA_SIGINFO;
  2175. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2176. switch (sig) {
  2177. case SIGINT:
  2178. default: break;
  2179. }
  2180. };
  2181. ::sigaction(SIGINT, &act, nullptr);
  2182. };
  2183. Server svr;
  2184. int port = 0;
  2185. auto thread = std::thread([&]() {
  2186. setupSignalHandlers();
  2187. port = svr.bind_to_any_port(HOST);
  2188. svr.listen_after_bind();
  2189. });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. ASSERT_TRUE(svr.is_running());
  2197. pthread_kill(thread.native_handle(), SIGINT);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2199. ASSERT_TRUE(svr.is_running());
  2200. }
  2201. #endif
  2202. TEST(RedirectToDifferentPort, Redirect) {
  2203. Server svr1;
  2204. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2205. res.set_content("Hello World!", "text/plain");
  2206. });
  2207. int svr1_port = 0;
  2208. auto thread1 = std::thread([&]() {
  2209. svr1_port = svr1.bind_to_any_port(HOST);
  2210. svr1.listen_after_bind();
  2211. });
  2212. Server svr2;
  2213. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2214. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2215. });
  2216. int svr2_port = 0;
  2217. auto thread2 = std::thread([&]() {
  2218. svr2_port = svr2.bind_to_any_port(HOST);
  2219. svr2.listen_after_bind();
  2220. });
  2221. auto se = detail::scope_exit([&] {
  2222. svr2.stop();
  2223. thread2.join();
  2224. svr1.stop();
  2225. thread1.join();
  2226. ASSERT_FALSE(svr2.is_running());
  2227. ASSERT_FALSE(svr1.is_running());
  2228. });
  2229. svr1.wait_until_ready();
  2230. svr2.wait_until_ready();
  2231. Client cli("localhost", svr2_port);
  2232. cli.set_follow_location(true);
  2233. auto res = cli.Get("/2");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. EXPECT_EQ("Hello World!", res->body);
  2237. }
  2238. static void
  2239. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2240. Server svr1;
  2241. std::string captured_authorization;
  2242. svr1.Get("/target", [&](const Request &req, Response &res) {
  2243. captured_authorization = req.get_header_value("Authorization");
  2244. res.set_content("OK", "text/plain");
  2245. });
  2246. int svr1_port = 0;
  2247. auto thread1 = std::thread([&]() {
  2248. svr1_port = svr1.bind_to_any_port(HOST);
  2249. svr1.listen_after_bind();
  2250. });
  2251. Server svr2;
  2252. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2253. res.set_redirect(
  2254. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2255. });
  2256. int svr2_port = 0;
  2257. auto thread2 = std::thread([&]() {
  2258. svr2_port = svr2.bind_to_any_port(HOST);
  2259. svr2.listen_after_bind();
  2260. });
  2261. auto se = detail::scope_exit([&] {
  2262. svr2.stop();
  2263. thread2.join();
  2264. svr1.stop();
  2265. thread1.join();
  2266. ASSERT_FALSE(svr2.is_running());
  2267. ASSERT_FALSE(svr1.is_running());
  2268. });
  2269. svr1.wait_until_ready();
  2270. svr2.wait_until_ready();
  2271. Client cli("localhost", svr2_port);
  2272. cli.set_follow_location(true);
  2273. set_auth(cli);
  2274. auto res = cli.Get("/redir");
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2278. EXPECT_TRUE(captured_authorization.empty());
  2279. }
  2280. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2281. TestDoNotForwardCredentialsOnRedirect(
  2282. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2283. }
  2284. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2285. TestDoNotForwardCredentialsOnRedirect(
  2286. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2287. }
  2288. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2289. Server svr1;
  2290. std::string captured_cookie;
  2291. bool target_hit = false;
  2292. svr1.Get("/target", [&](const Request &req, Response &res) {
  2293. captured_cookie = req.get_header_value("Cookie");
  2294. target_hit = true;
  2295. res.set_content("OK", "text/plain");
  2296. });
  2297. int svr1_port = 0;
  2298. auto thread1 = std::thread([&]() {
  2299. svr1_port = svr1.bind_to_any_port(HOST);
  2300. svr1.listen_after_bind();
  2301. });
  2302. Server svr2;
  2303. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2304. res.set_redirect(
  2305. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2306. });
  2307. int svr2_port = 0;
  2308. auto thread2 = std::thread([&]() {
  2309. svr2_port = svr2.bind_to_any_port(HOST);
  2310. svr2.listen_after_bind();
  2311. });
  2312. auto se = detail::scope_exit([&] {
  2313. svr2.stop();
  2314. thread2.join();
  2315. svr1.stop();
  2316. thread1.join();
  2317. ASSERT_FALSE(svr2.is_running());
  2318. ASSERT_FALSE(svr1.is_running());
  2319. });
  2320. svr1.wait_until_ready();
  2321. svr2.wait_until_ready();
  2322. Client cli("localhost", svr2_port);
  2323. cli.set_follow_location(true);
  2324. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2325. auto res = cli.Get("/redir", headers);
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::OK_200, res->status);
  2328. EXPECT_TRUE(target_hit);
  2329. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2330. EXPECT_TRUE(captured_cookie.empty());
  2331. }
  2332. TEST(RedirectToSamePort, ForwardCookie) {
  2333. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2334. // header so that ordinary session flows keep working.
  2335. Server svr;
  2336. std::string captured_cookie;
  2337. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2338. res.set_redirect("/target", 302);
  2339. });
  2340. svr.Get("/target", [&](const Request &req, Response &res) {
  2341. captured_cookie = req.get_header_value("Cookie");
  2342. res.set_content("OK", "text/plain");
  2343. });
  2344. auto port = svr.bind_to_any_port(HOST);
  2345. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2346. auto se = detail::scope_exit([&] {
  2347. svr.stop();
  2348. thread.join();
  2349. ASSERT_FALSE(svr.is_running());
  2350. });
  2351. svr.wait_until_ready();
  2352. Client cli(HOST, port);
  2353. cli.set_follow_location(true);
  2354. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2355. auto res = cli.Get("/redir", headers);
  2356. ASSERT_TRUE(res);
  2357. EXPECT_EQ(StatusCode::OK_200, res->status);
  2358. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2359. }
  2360. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2361. Server svr;
  2362. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2363. // Port number that overflows int — should not crash
  2364. res.set_redirect("http://localhost:99999999999999999999/target");
  2365. });
  2366. auto port = svr.bind_to_any_port(HOST);
  2367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2368. auto se = detail::scope_exit([&] {
  2369. svr.stop();
  2370. thread.join();
  2371. ASSERT_FALSE(svr.is_running());
  2372. });
  2373. svr.wait_until_ready();
  2374. Client cli(HOST, port);
  2375. cli.set_follow_location(true);
  2376. auto res = cli.Get("/redir");
  2377. // Should fail gracefully, not crash (no valid response due to bad port)
  2378. EXPECT_FALSE(res);
  2379. }
  2380. TEST(RedirectFromPageWithContent, Redirect) {
  2381. Server svr;
  2382. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2383. res.set_content("___", "text/plain");
  2384. res.set_redirect("/2");
  2385. });
  2386. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. th.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. {
  2397. Client cli("localhost", PORT);
  2398. cli.set_follow_location(true);
  2399. std::string body;
  2400. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2401. body.append(data, data_length);
  2402. return true;
  2403. });
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(StatusCode::OK_200, res->status);
  2406. EXPECT_EQ("Hello World!", body);
  2407. }
  2408. {
  2409. Client cli("localhost", PORT);
  2410. std::string body;
  2411. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2412. body.append(data, data_length);
  2413. return true;
  2414. });
  2415. ASSERT_TRUE(res);
  2416. EXPECT_EQ(StatusCode::Found_302, res->status);
  2417. EXPECT_EQ("___", body);
  2418. }
  2419. }
  2420. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2421. Server svr;
  2422. auto port_str = std::to_string(PORT);
  2423. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2424. auto expected_host = "[::1]:" + port_str;
  2425. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2426. res.set_content("___", "text/plain");
  2427. // res.set_redirect("/2");
  2428. res.set_redirect(redirect_url);
  2429. });
  2430. svr.Get("/2", [&](const Request &req, Response &res) {
  2431. auto host_header = req.headers.find("Host");
  2432. ASSERT_TRUE(host_header != req.headers.end());
  2433. EXPECT_EQ(expected_host, host_header->second);
  2434. res.set_content("Hello World!", "text/plain");
  2435. });
  2436. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2437. auto se = detail::scope_exit([&] {
  2438. svr.stop();
  2439. th.join();
  2440. ASSERT_FALSE(svr.is_running());
  2441. });
  2442. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2443. // actually starts anything, so the condition !svr.is_running() will
  2444. // always remain true, and the loop never stops.
  2445. // This basically counts how many milliseconds have passed since the
  2446. // call to svr.listen(), and if after 5 seconds nothing started yet
  2447. // aborts the test.
  2448. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2449. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2450. ASSERT_LT(milliseconds, 5000U);
  2451. }
  2452. {
  2453. Client cli("::1", PORT);
  2454. cli.set_follow_location(true);
  2455. std::string body;
  2456. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2457. body.append(data, data_length);
  2458. return true;
  2459. });
  2460. ASSERT_TRUE(res);
  2461. EXPECT_EQ(StatusCode::OK_200, res->status);
  2462. EXPECT_EQ("Hello World!", body);
  2463. }
  2464. {
  2465. Client cli("::1", PORT);
  2466. std::string body;
  2467. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2468. body.append(data, data_length);
  2469. return true;
  2470. });
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::Found_302, res->status);
  2473. EXPECT_EQ("___", body);
  2474. }
  2475. }
  2476. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2477. Server svr;
  2478. svr.Get("/foo", [](const Request &req, Response &res) {
  2479. auto a = req.params.find("a");
  2480. if (a != req.params.end()) {
  2481. res.set_content((*a).second, "text/plain");
  2482. res.status = StatusCode::OK_200;
  2483. } else {
  2484. res.status = StatusCode::BadRequest_400;
  2485. }
  2486. });
  2487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. thread.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. {
  2495. Client cli(HOST, PORT);
  2496. cli.set_path_encode(false);
  2497. auto res = cli.Get("/foo?a=explicitly+encoded");
  2498. ASSERT_TRUE(res);
  2499. EXPECT_EQ(StatusCode::OK_200, res->status);
  2500. // This expects it back with a space, as the `+` won't have been
  2501. // url-encoded, and server-side the params get decoded turning `+`
  2502. // into spaces.
  2503. EXPECT_EQ("explicitly encoded", res->body);
  2504. }
  2505. }
  2506. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2507. // When path encoding is disabled the client must transmit the supplied
  2508. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2509. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2510. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2511. // than a space (0x20). Assert on the raw wire target to catch this.
  2512. Server svr;
  2513. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2514. svr.Get("/foo", [&](const Request &req, Response &res) {
  2515. EXPECT_EQ(expected_target, req.target);
  2516. res.status = StatusCode::OK_200;
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. {
  2526. Client cli(HOST, PORT);
  2527. cli.set_path_encode(false);
  2528. auto res = cli.Get(expected_target.c_str());
  2529. ASSERT_TRUE(res);
  2530. EXPECT_EQ(StatusCode::OK_200, res->status);
  2531. }
  2532. }
  2533. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2534. Server svr;
  2535. svr.Get("/", [](const Request &req, Response &) {
  2536. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2537. });
  2538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2539. auto se = detail::scope_exit([&] {
  2540. svr.stop();
  2541. thread.join();
  2542. ASSERT_FALSE(svr.is_running());
  2543. });
  2544. svr.wait_until_ready();
  2545. {
  2546. Client cli(HOST, PORT);
  2547. cli.set_path_encode(false);
  2548. auto res = cli.Get("/?something=%0A");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. }
  2553. TEST(BindServerTest, BindDualStack) {
  2554. Server svr;
  2555. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2556. res.set_content("Hello World!", "text/plain");
  2557. });
  2558. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2559. auto se = detail::scope_exit([&] {
  2560. svr.stop();
  2561. thread.join();
  2562. ASSERT_FALSE(svr.is_running());
  2563. });
  2564. svr.wait_until_ready();
  2565. {
  2566. Client cli("127.0.0.1", PORT);
  2567. auto res = cli.Get("/1");
  2568. ASSERT_TRUE(res);
  2569. EXPECT_EQ(StatusCode::OK_200, res->status);
  2570. EXPECT_EQ("Hello World!", res->body);
  2571. }
  2572. {
  2573. Client cli("::1", PORT);
  2574. auto res = cli.Get("/1");
  2575. ASSERT_TRUE(res);
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. }
  2579. }
  2580. TEST(BindServerTest, BindAndListenSeparately) {
  2581. Server svr;
  2582. int port = svr.bind_to_any_port("0.0.0.0");
  2583. ASSERT_TRUE(svr.is_valid());
  2584. ASSERT_TRUE(port > 0);
  2585. svr.stop();
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2590. CLIENT_CA_CERT_DIR);
  2591. int port = svr.bind_to_any_port("0.0.0.0");
  2592. ASSERT_TRUE(svr.is_valid());
  2593. ASSERT_TRUE(port > 0);
  2594. svr.stop();
  2595. }
  2596. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2597. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2598. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2599. int port = svr.bind_to_any_port("0.0.0.0");
  2600. ASSERT_TRUE(svr.is_valid());
  2601. ASSERT_TRUE(port > 0);
  2602. svr.stop();
  2603. }
  2604. TEST(BindServerTest, UpdateCertsPem) {
  2605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2606. int port = svr.bind_to_any_port("0.0.0.0");
  2607. ASSERT_TRUE(svr.is_valid());
  2608. ASSERT_TRUE(port > 0);
  2609. // Read PEM files
  2610. std::string cert_pem, key_pem, ca_pem;
  2611. read_file(SERVER_CERT_FILE, cert_pem);
  2612. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2613. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2614. // Update server certificates using PEM API
  2615. ASSERT_TRUE(
  2616. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2617. ASSERT_TRUE(svr.is_valid());
  2618. svr.stop();
  2619. }
  2620. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2621. // Start server with client CA (enables client auth)
  2622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2623. ASSERT_TRUE(svr.is_valid());
  2624. bool handler_called = false;
  2625. svr.Get("/test", [&](const Request &req, Response &res) {
  2626. handler_called = true;
  2627. // Verify client certificate is present
  2628. auto cert = req.peer_cert();
  2629. EXPECT_TRUE(static_cast<bool>(cert));
  2630. res.set_content("ok", "text/plain");
  2631. });
  2632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2633. auto se = detail::scope_exit([&] {
  2634. svr.stop();
  2635. t.join();
  2636. ASSERT_FALSE(svr.is_running());
  2637. });
  2638. svr.wait_until_ready();
  2639. // Read PEM files
  2640. std::string cert_pem, key_pem, ca_pem;
  2641. read_file(SERVER_CERT_FILE, cert_pem);
  2642. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2643. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2644. // Update server certificates and client CA using PEM API while server running
  2645. ASSERT_TRUE(
  2646. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2647. // Connect with client certificate
  2648. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2649. cli.enable_server_certificate_verification(false);
  2650. cli.set_connection_timeout(30);
  2651. auto res = cli.Get("/test");
  2652. ASSERT_TRUE(res);
  2653. ASSERT_EQ(StatusCode::OK_200, res->status);
  2654. ASSERT_TRUE(handler_called);
  2655. EXPECT_EQ("ok", res->body);
  2656. }
  2657. #endif
  2658. TEST(ErrorHandlerTest, ContentLength) {
  2659. Server svr;
  2660. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2661. res.status = StatusCode::OK_200;
  2662. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2663. "text/html"); // <= Content-Length still 13
  2664. });
  2665. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2666. res.set_content("Hello World!\n", "text/plain");
  2667. res.status = 524;
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. {
  2677. Client cli(HOST, PORT);
  2678. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2679. ASSERT_TRUE(res);
  2680. EXPECT_EQ(StatusCode::OK_200, res->status);
  2681. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2682. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2683. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2684. }
  2685. }
  2686. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2687. TEST(ExceptionTest, WithoutExceptionHandler) {
  2688. Server svr;
  2689. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2690. throw std::runtime_error("exception...");
  2691. });
  2692. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2693. throw std::runtime_error("exception\r\n...");
  2694. });
  2695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2696. auto se = detail::scope_exit([&] {
  2697. svr.stop();
  2698. listen_thread.join();
  2699. ASSERT_FALSE(svr.is_running());
  2700. });
  2701. svr.wait_until_ready();
  2702. Client cli("localhost", PORT);
  2703. {
  2704. auto res = cli.Get("/exception");
  2705. ASSERT_TRUE(res);
  2706. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2707. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2708. }
  2709. {
  2710. auto res = cli.Get("/unknown");
  2711. ASSERT_TRUE(res);
  2712. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2713. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2714. }
  2715. }
  2716. TEST(ExceptionTest, WithExceptionHandler) {
  2717. Server svr;
  2718. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2719. std::exception_ptr ep) {
  2720. EXPECT_FALSE(ep == nullptr);
  2721. try {
  2722. std::rethrow_exception(ep);
  2723. } catch (std::exception &e) {
  2724. EXPECT_EQ("abc", std::string(e.what()));
  2725. } catch (...) {}
  2726. res.status = StatusCode::InternalServerError_500;
  2727. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2728. "text/html"); // <= Content-Length still 13 at this point
  2729. });
  2730. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2731. res.set_content("Hello World!\n", "text/plain");
  2732. throw std::runtime_error("abc");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. for (size_t i = 0; i < 10; i++) {
  2742. Client cli(HOST, PORT);
  2743. for (size_t j = 0; j < 100; j++) {
  2744. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2745. ASSERT_TRUE(res);
  2746. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2747. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2748. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2749. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2750. }
  2751. cli.set_keep_alive(true);
  2752. for (size_t j = 0; j < 100; j++) {
  2753. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2754. ASSERT_TRUE(res);
  2755. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2756. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2757. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2758. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2759. }
  2760. }
  2761. }
  2762. TEST(ExceptionTest, AndErrorHandler) {
  2763. Server svr;
  2764. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2765. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2766. });
  2767. svr.set_exception_handler(
  2768. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2769. EXPECT_FALSE(ep == nullptr);
  2770. try {
  2771. std::rethrow_exception(ep);
  2772. } catch (std::exception &e) {
  2773. res.set_content(e.what(), "text/html");
  2774. } catch (...) {}
  2775. res.status = StatusCode::InternalServerError_500;
  2776. });
  2777. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2778. throw std::runtime_error("EXCEPTION");
  2779. });
  2780. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2781. res.set_content("ERROR", "text/html");
  2782. res.status = StatusCode::InternalServerError_500;
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. {
  2793. auto res = cli.Get("/exception");
  2794. ASSERT_TRUE(res);
  2795. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2796. EXPECT_EQ("EXCEPTION", res->body);
  2797. }
  2798. {
  2799. auto res = cli.Get("/error");
  2800. ASSERT_TRUE(res);
  2801. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2802. EXPECT_EQ("ERROR", res->body);
  2803. }
  2804. {
  2805. auto res = cli.Get("/invalid");
  2806. ASSERT_TRUE(res);
  2807. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2808. EXPECT_EQ("NOT_FOUND", res->body);
  2809. }
  2810. }
  2811. #endif
  2812. TEST(NoContentTest, ContentLength) {
  2813. Server svr;
  2814. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2815. res.status = StatusCode::NoContent_204;
  2816. });
  2817. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2818. auto se = detail::scope_exit([&] {
  2819. svr.stop();
  2820. thread.join();
  2821. ASSERT_FALSE(svr.is_running());
  2822. });
  2823. svr.wait_until_ready();
  2824. {
  2825. Client cli(HOST, PORT);
  2826. auto res = cli.Get("/hi");
  2827. ASSERT_TRUE(res);
  2828. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2829. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2830. }
  2831. }
  2832. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2833. #ifdef CPPHTTPLIB_SSL_ENABLED
  2834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2835. ASSERT_TRUE(svr.is_valid());
  2836. #else
  2837. Server svr;
  2838. #endif
  2839. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2840. if (req.path == "/routing_handler") {
  2841. res.set_header("PRE_ROUTING", "on");
  2842. res.set_content("Routing Handler", "text/plain");
  2843. return httplib::Server::HandlerResponse::Handled;
  2844. }
  2845. return httplib::Server::HandlerResponse::Unhandled;
  2846. });
  2847. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2848. res.set_content("Error", "text/html");
  2849. });
  2850. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2851. if (req.path == "/routing_handler") {
  2852. res.set_header("POST_ROUTING", "on");
  2853. }
  2854. });
  2855. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2856. res.set_content("Hello World!\n", "text/plain");
  2857. });
  2858. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. {
  2866. #ifdef CPPHTTPLIB_SSL_ENABLED
  2867. SSLClient cli(HOST, PORT);
  2868. cli.enable_server_certificate_verification(false);
  2869. #else
  2870. Client cli(HOST, PORT);
  2871. #endif
  2872. auto res = cli.Get("/routing_handler");
  2873. ASSERT_TRUE(res);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. EXPECT_EQ("Routing Handler", res->body);
  2876. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2877. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2878. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2879. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2880. }
  2881. {
  2882. #ifdef CPPHTTPLIB_SSL_ENABLED
  2883. SSLClient cli(HOST, PORT);
  2884. cli.enable_server_certificate_verification(false);
  2885. #else
  2886. Client cli(HOST, PORT);
  2887. #endif
  2888. auto res = cli.Get("/hi");
  2889. ASSERT_TRUE(res);
  2890. EXPECT_EQ(StatusCode::OK_200, res->status);
  2891. EXPECT_EQ("Hello World!\n", res->body);
  2892. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2893. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2894. }
  2895. {
  2896. #ifdef CPPHTTPLIB_SSL_ENABLED
  2897. SSLClient cli(HOST, PORT);
  2898. cli.enable_server_certificate_verification(false);
  2899. #else
  2900. Client cli(HOST, PORT);
  2901. #endif
  2902. auto res = cli.Get("/aaa");
  2903. ASSERT_TRUE(res);
  2904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2905. EXPECT_EQ("Error", res->body);
  2906. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2907. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2908. }
  2909. }
  2910. TEST(RequestHandlerTest, PreRequestHandler) {
  2911. auto route_path = "/user/:user";
  2912. Server svr;
  2913. svr.Get("/hi", [](const Request &, Response &res) {
  2914. res.set_content("hi", "text/plain");
  2915. });
  2916. svr.Get(route_path, [](const Request &req, Response &res) {
  2917. res.set_content(req.path_params.at("user"), "text/plain");
  2918. });
  2919. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2920. if (req.matched_route == route_path) {
  2921. auto user = req.path_params.at("user");
  2922. if (user != "john") {
  2923. res.status = StatusCode::Forbidden_403;
  2924. res.set_content("error", "text/html");
  2925. return Server::HandlerResponse::Handled;
  2926. }
  2927. }
  2928. return Server::HandlerResponse::Unhandled;
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. {
  2939. auto res = cli.Get("/hi");
  2940. ASSERT_TRUE(res);
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. EXPECT_EQ("hi", res->body);
  2943. }
  2944. {
  2945. auto res = cli.Get("/user/john");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::OK_200, res->status);
  2948. EXPECT_EQ("john", res->body);
  2949. }
  2950. {
  2951. auto res = cli.Get("/user/invalid-user");
  2952. ASSERT_TRUE(res);
  2953. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2954. EXPECT_EQ("error", res->body);
  2955. }
  2956. }
  2957. // The pre-request handler must run before the request body is read, so a
  2958. // rejected request never forces the server to buffer a (potentially large)
  2959. // body. Here the posted body is larger than the payload limit: if the body
  2960. // were read first the server would answer 413, but because the pre-request
  2961. // handler runs first it answers 403 and the body is never read.
  2962. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2963. Server svr;
  2964. svr.set_payload_max_length(8);
  2965. auto handler_ran = false;
  2966. svr.Post("/reject", [&](const Request &req, Response &res) {
  2967. handler_ran = true;
  2968. res.set_content(req.body, "text/plain");
  2969. });
  2970. svr.Post("/accept", [](const Request &req, Response &res) {
  2971. res.set_content(req.body, "text/plain");
  2972. });
  2973. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2974. if (req.matched_route == "/reject") {
  2975. res.status = StatusCode::Forbidden_403;
  2976. res.set_content("denied", "text/plain");
  2977. return Server::HandlerResponse::Handled;
  2978. }
  2979. return Server::HandlerResponse::Unhandled;
  2980. });
  2981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. Client cli(HOST, PORT);
  2989. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2990. // rejects with 403 before the body is read, so 413 is never reached.
  2991. {
  2992. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2993. ASSERT_TRUE(res);
  2994. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2995. EXPECT_EQ("denied", res->body);
  2996. EXPECT_FALSE(handler_ran);
  2997. }
  2998. // An approved route still reads the body and enforces the payload limit.
  2999. {
  3000. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3001. ASSERT_TRUE(res);
  3002. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3003. }
  3004. }
  3005. TEST(UserDataTest, BasicOperations) {
  3006. httplib::UserData ud;
  3007. // Initially empty
  3008. EXPECT_FALSE(ud.has("key"));
  3009. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3010. // set and get
  3011. ud.set("key", 42);
  3012. EXPECT_TRUE(ud.has("key"));
  3013. auto *p = ud.get<int>("key");
  3014. ASSERT_NE(nullptr, p);
  3015. EXPECT_EQ(42, *p);
  3016. // Type mismatch → nullptr
  3017. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3018. // Overwrite with different type
  3019. ud.set("key", std::string("hello"));
  3020. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3021. auto *s = ud.get<std::string>("key");
  3022. ASSERT_NE(nullptr, s);
  3023. EXPECT_EQ("hello", *s);
  3024. // erase
  3025. ud.erase("key");
  3026. EXPECT_FALSE(ud.has("key"));
  3027. // clear
  3028. ud.set("a", 1);
  3029. ud.set("b", 2);
  3030. ud.clear();
  3031. EXPECT_FALSE(ud.has("a"));
  3032. EXPECT_FALSE(ud.has("b"));
  3033. }
  3034. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3035. struct AuthCtx {
  3036. std::string user_id;
  3037. };
  3038. Server svr;
  3039. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3040. res.user_data.set("auth", AuthCtx{"alice"});
  3041. return Server::HandlerResponse::Unhandled;
  3042. });
  3043. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3044. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3045. ASSERT_NE(nullptr, ctx);
  3046. res.set_content("Hello " + ctx->user_id, "text/plain");
  3047. });
  3048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3049. auto se = detail::scope_exit([&] {
  3050. svr.stop();
  3051. thread.join();
  3052. ASSERT_FALSE(svr.is_running());
  3053. });
  3054. svr.wait_until_ready();
  3055. Client cli(HOST, PORT);
  3056. auto res = cli.Get("/me");
  3057. ASSERT_TRUE(res);
  3058. EXPECT_EQ(StatusCode::OK_200, res->status);
  3059. EXPECT_EQ("Hello alice", res->body);
  3060. }
  3061. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3062. struct RoleCtx {
  3063. std::string role;
  3064. };
  3065. Server svr;
  3066. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3067. res.user_data.set("role", RoleCtx{"admin"});
  3068. return Server::HandlerResponse::Unhandled;
  3069. });
  3070. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3071. auto *ctx = res.user_data.get<RoleCtx>("role");
  3072. ASSERT_NE(nullptr, ctx);
  3073. res.set_content(ctx->role, "text/plain");
  3074. });
  3075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3076. auto se = detail::scope_exit([&] {
  3077. svr.stop();
  3078. thread.join();
  3079. ASSERT_FALSE(svr.is_running());
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, PORT);
  3083. auto res = cli.Get("/role");
  3084. ASSERT_TRUE(res);
  3085. EXPECT_EQ(StatusCode::OK_200, res->status);
  3086. EXPECT_EQ("admin", res->body);
  3087. }
  3088. TEST(InvalidFormatTest, StatusCode) {
  3089. Server svr;
  3090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3091. res.set_content("Hello World!\n", "text/plain");
  3092. res.status = 9999; // Status should be a three-digit code...
  3093. });
  3094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3095. auto se = detail::scope_exit([&] {
  3096. svr.stop();
  3097. thread.join();
  3098. ASSERT_FALSE(svr.is_running());
  3099. });
  3100. svr.wait_until_ready();
  3101. {
  3102. Client cli(HOST, PORT);
  3103. auto res = cli.Get("/hi");
  3104. ASSERT_FALSE(res);
  3105. }
  3106. }
  3107. TEST(URLFragmentTest, WithFragment) {
  3108. Server svr;
  3109. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3110. EXPECT_TRUE(req.target == "/hi");
  3111. });
  3112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3113. auto se = detail::scope_exit([&] {
  3114. svr.stop();
  3115. thread.join();
  3116. ASSERT_FALSE(svr.is_running());
  3117. });
  3118. svr.wait_until_ready();
  3119. {
  3120. Client cli(HOST, PORT);
  3121. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3122. EXPECT_TRUE(res);
  3123. EXPECT_EQ(StatusCode::OK_200, res->status);
  3124. res = cli.Get("/hi%23key1=val1=key2=val2");
  3125. EXPECT_TRUE(res);
  3126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3127. }
  3128. }
  3129. TEST(HeaderWriter, SetHeaderWriter) {
  3130. Server svr;
  3131. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3132. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3133. return detail::write_headers(strm, hdrs);
  3134. });
  3135. svr.Get("/hi", [](const Request &req, Response &res) {
  3136. auto it = req.headers.find("CustomClientHeader");
  3137. EXPECT_TRUE(it != req.headers.end());
  3138. EXPECT_EQ(it->second, "CustomClientValue");
  3139. res.set_content("Hello World!\n", "text/plain");
  3140. });
  3141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3142. auto se = detail::scope_exit([&] {
  3143. svr.stop();
  3144. thread.join();
  3145. ASSERT_FALSE(svr.is_running());
  3146. });
  3147. svr.wait_until_ready();
  3148. {
  3149. Client cli(HOST, PORT);
  3150. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3151. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3152. return detail::write_headers(strm, hdrs);
  3153. });
  3154. auto res = cli.Get("/hi");
  3155. EXPECT_TRUE(res);
  3156. EXPECT_EQ(StatusCode::OK_200, res->status);
  3157. auto it = res->headers.find("CustomServerHeader");
  3158. EXPECT_TRUE(it != res->headers.end());
  3159. EXPECT_EQ(it->second, "CustomServerValue");
  3160. }
  3161. }
  3162. class ServerTest : public ::testing::Test {
  3163. protected:
  3164. ServerTest()
  3165. : cli_(HOST, PORT)
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. ,
  3168. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3169. #endif
  3170. {
  3171. #ifdef CPPHTTPLIB_SSL_ENABLED
  3172. cli_.enable_server_certificate_verification(false);
  3173. #endif
  3174. // Allow LARGE_DATA (100MB) responses
  3175. cli_.set_payload_max_length(200 * 1024 * 1024);
  3176. }
  3177. virtual void SetUp() {
  3178. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3179. svr_.set_payload_max_length(200 * 1024 * 1024);
  3180. svr_.set_mount_point("/", "./www");
  3181. svr_.set_mount_point("/mount", "./www2");
  3182. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3183. svr_.Get("/hi",
  3184. [&](const Request & /*req*/, Response &res) {
  3185. res.set_content("Hello World!", "text/plain");
  3186. })
  3187. .Get("/file_content",
  3188. [&](const Request & /*req*/, Response &res) {
  3189. res.set_file_content("./www/dir/test.html");
  3190. })
  3191. .Get("/file_content_with_content_type",
  3192. [&](const Request & /*req*/, Response &res) {
  3193. res.set_file_content("./www/file", "text/plain");
  3194. })
  3195. .Get("/invalid_file_content",
  3196. [&](const Request & /*req*/, Response &res) {
  3197. res.set_file_content("./www/dir/invalid_file_path");
  3198. })
  3199. .Get("/http_response_splitting",
  3200. [&](const Request & /*req*/, Response &res) {
  3201. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3202. EXPECT_EQ(0U, res.headers.size());
  3203. EXPECT_FALSE(res.has_header("a"));
  3204. res.set_header("a", "1\nSet-Cookie: a=1");
  3205. EXPECT_EQ(0U, res.headers.size());
  3206. EXPECT_FALSE(res.has_header("a"));
  3207. res.set_header("a", "1\rSet-Cookie: a=1");
  3208. EXPECT_EQ(0U, res.headers.size());
  3209. EXPECT_FALSE(res.has_header("a"));
  3210. res.set_header("a\r\nb", "0");
  3211. EXPECT_EQ(0U, res.headers.size());
  3212. EXPECT_FALSE(res.has_header("a"));
  3213. res.set_header("a\rb", "0");
  3214. EXPECT_EQ(0U, res.headers.size());
  3215. EXPECT_FALSE(res.has_header("a"));
  3216. res.set_header("a\nb", "0");
  3217. EXPECT_EQ(0U, res.headers.size());
  3218. EXPECT_FALSE(res.has_header("a"));
  3219. res.set_redirect("1\r\nSet-Cookie: a=1");
  3220. EXPECT_EQ(0U, res.headers.size());
  3221. EXPECT_FALSE(res.has_header("Location"));
  3222. })
  3223. .Get("/slow",
  3224. [&](const Request & /*req*/, Response &res) {
  3225. std::this_thread::sleep_for(std::chrono::seconds(4));
  3226. res.set_content("slow", "text/plain");
  3227. })
  3228. #if 0
  3229. .Post("/slowpost",
  3230. [&](const Request & /*req*/, Response &res) {
  3231. std::this_thread::sleep_for(std::chrono::seconds(2));
  3232. res.set_content("slow", "text/plain");
  3233. })
  3234. #endif
  3235. .Get("/remote_addr",
  3236. [&](const Request &req, Response &res) {
  3237. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3238. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3239. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3240. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3241. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3242. #endif
  3243. res.set_content(req.remote_addr, "text/plain");
  3244. })
  3245. .Get("/local_addr",
  3246. [&](const Request &req, Response &res) {
  3247. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3248. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3249. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3250. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3251. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3252. #endif
  3253. auto local_addr = req.local_addr;
  3254. auto local_port = std::to_string(req.local_port);
  3255. res.set_content(local_addr.append(":").append(local_port),
  3256. "text/plain");
  3257. })
  3258. .Get("/endwith%",
  3259. [&](const Request & /*req*/, Response &res) {
  3260. res.set_content("Hello World!", "text/plain");
  3261. })
  3262. .Get("/a\\+\\+b",
  3263. [&](const Request &req, Response &res) {
  3264. ASSERT_TRUE(req.has_param("a +b"));
  3265. auto val = req.get_param_value("a +b");
  3266. res.set_content(val, "text/plain");
  3267. })
  3268. .Get("/", [&](const Request & /*req*/,
  3269. Response &res) { res.set_redirect("/hi"); })
  3270. .Post("/1",
  3271. [](const Request & /*req*/, Response &res) {
  3272. res.set_redirect("/2", StatusCode::SeeOther_303);
  3273. })
  3274. .Get("/2",
  3275. [](const Request & /*req*/, Response &res) {
  3276. res.set_content("redirected.", "text/plain");
  3277. res.status = StatusCode::OK_200;
  3278. })
  3279. .Post("/person",
  3280. [&](const Request &req, Response &res) {
  3281. if (req.has_param("name") && req.has_param("note")) {
  3282. persons_[req.get_param_value("name")] =
  3283. req.get_param_value("note");
  3284. } else {
  3285. res.status = StatusCode::BadRequest_400;
  3286. }
  3287. })
  3288. .Put("/person",
  3289. [&](const Request &req, Response &res) {
  3290. if (req.has_param("name") && req.has_param("note")) {
  3291. persons_[req.get_param_value("name")] =
  3292. req.get_param_value("note");
  3293. } else {
  3294. res.status = StatusCode::BadRequest_400;
  3295. }
  3296. })
  3297. .Get("/person/(.*)",
  3298. [&](const Request &req, Response &res) {
  3299. string name = req.matches[1];
  3300. if (persons_.find(name) != persons_.end()) {
  3301. auto note = persons_[name];
  3302. res.set_content(note, "text/plain");
  3303. } else {
  3304. res.status = StatusCode::NotFound_404;
  3305. }
  3306. })
  3307. .Delete("/person",
  3308. [&](const Request &req, Response &res) {
  3309. if (req.has_param("name")) {
  3310. string name = req.get_param_value("name");
  3311. if (persons_.find(name) != persons_.end()) {
  3312. persons_.erase(name);
  3313. res.set_content("DELETED", "text/plain");
  3314. } else {
  3315. res.status = StatusCode::NotFound_404;
  3316. }
  3317. } else {
  3318. res.status = StatusCode::BadRequest_400;
  3319. }
  3320. })
  3321. .Post("/x-www-form-urlencoded-json",
  3322. [&](const Request &req, Response &res) {
  3323. auto json = req.get_param_value("json");
  3324. ASSERT_EQ(JSON_DATA, json);
  3325. res.set_content(json, "appliation/json");
  3326. res.status = StatusCode::OK_200;
  3327. })
  3328. .Get("/streamed-chunked",
  3329. [&](const Request & /*req*/, Response &res) {
  3330. res.set_chunked_content_provider(
  3331. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3332. sink.os << "123";
  3333. sink.os << "456";
  3334. sink.os << "789";
  3335. sink.done();
  3336. return true;
  3337. });
  3338. })
  3339. .Get("/streamed-chunked-with-prohibited-trailer",
  3340. [&](const Request & /*req*/, Response &res) {
  3341. auto i = new int(0);
  3342. // Declare both a prohibited trailer (Content-Length) and an
  3343. // allowed one
  3344. res.set_header("Trailer", "Content-Length, X-Allowed");
  3345. res.set_chunked_content_provider(
  3346. "text/plain",
  3347. [i](size_t /*offset*/, DataSink &sink) {
  3348. switch (*i) {
  3349. case 0: sink.os << "123"; break;
  3350. case 1: sink.os << "456"; break;
  3351. case 2: sink.os << "789"; break;
  3352. case 3: {
  3353. sink.done_with_trailer(
  3354. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3355. } break;
  3356. }
  3357. (*i)++;
  3358. return true;
  3359. },
  3360. [i](bool success) {
  3361. EXPECT_TRUE(success);
  3362. delete i;
  3363. });
  3364. })
  3365. .Get("/streamed-chunked2",
  3366. [&](const Request & /*req*/, Response &res) {
  3367. auto i = new int(0);
  3368. res.set_chunked_content_provider(
  3369. "text/plain",
  3370. [i](size_t /*offset*/, DataSink &sink) {
  3371. switch (*i) {
  3372. case 0: sink.os << "123"; break;
  3373. case 1: sink.os << "456"; break;
  3374. case 2: sink.os << "789"; break;
  3375. case 3: sink.done(); break;
  3376. }
  3377. (*i)++;
  3378. return true;
  3379. },
  3380. [i](bool success) {
  3381. EXPECT_TRUE(success);
  3382. delete i;
  3383. });
  3384. })
  3385. .Get("/streamed-chunked-with-trailer",
  3386. [&](const Request & /*req*/, Response &res) {
  3387. auto i = new int(0);
  3388. res.set_header("Trailer", "Dummy1, Dummy2");
  3389. res.set_chunked_content_provider(
  3390. "text/plain",
  3391. [i](size_t /*offset*/, DataSink &sink) {
  3392. switch (*i) {
  3393. case 0: sink.os << "123"; break;
  3394. case 1: sink.os << "456"; break;
  3395. case 2: sink.os << "789"; break;
  3396. case 3: {
  3397. sink.done_with_trailer(
  3398. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3399. } break;
  3400. }
  3401. (*i)++;
  3402. return true;
  3403. },
  3404. [i](bool success) {
  3405. EXPECT_TRUE(success);
  3406. delete i;
  3407. });
  3408. })
  3409. .Get("/streamed",
  3410. [&](const Request & /*req*/, Response &res) {
  3411. res.set_content_provider(
  3412. 6, "text/plain",
  3413. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3414. sink.os << (offset < 3 ? "a" : "b");
  3415. return true;
  3416. });
  3417. })
  3418. .Get("/streamed-without-length",
  3419. [&](const Request & /*req*/, Response &res) {
  3420. auto data = new std::string("abcdefg");
  3421. res.set_content_provider(
  3422. "text/plain",
  3423. [data](size_t offset, DataSink &sink) {
  3424. if (offset < data->size()) {
  3425. sink.os << data->substr(offset);
  3426. }
  3427. sink.done();
  3428. return true;
  3429. },
  3430. [data](bool success) {
  3431. EXPECT_TRUE(success);
  3432. delete data;
  3433. });
  3434. })
  3435. .Get("/streamed-with-range",
  3436. [&](const Request &req, Response &res) {
  3437. auto data = new std::string("abcdefg");
  3438. res.set_content_provider(
  3439. data->size(), "text/plain",
  3440. [data](size_t offset, size_t length, DataSink &sink) {
  3441. size_t DATA_CHUNK_SIZE = 4;
  3442. const auto &d = *data;
  3443. auto out_len =
  3444. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3445. auto ret =
  3446. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3447. EXPECT_TRUE(ret);
  3448. return true;
  3449. },
  3450. [data, &req](bool success) {
  3451. EXPECT_EQ(success, !req.has_param("error"));
  3452. delete data;
  3453. });
  3454. })
  3455. .Get("/streamed-cancel",
  3456. [&](const Request & /*req*/, Response &res) {
  3457. res.set_content_provider(
  3458. size_t(-1), "text/plain",
  3459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3460. sink.os << "data_chunk";
  3461. return true;
  3462. });
  3463. })
  3464. .Get("/regex-with-delimiter",
  3465. [&](const Request &req, Response & /*res*/) {
  3466. ASSERT_TRUE(req.has_param("key"));
  3467. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3468. })
  3469. .Get("/with-range",
  3470. [&](const Request & /*req*/, Response &res) {
  3471. res.set_content("abcdefg", "text/plain");
  3472. })
  3473. .Get("/test-start-time",
  3474. [&](const Request &req, Response & /*res*/) {
  3475. EXPECT_NE(req.start_time_,
  3476. std::chrono::steady_clock::time_point::min());
  3477. })
  3478. .Get("/with-range-customized-response",
  3479. [&](const Request & /*req*/, Response &res) {
  3480. res.status = StatusCode::BadRequest_400;
  3481. res.set_content(JSON_DATA, "application/json");
  3482. })
  3483. .Post("/chunked",
  3484. [&](const Request &req, Response & /*res*/) {
  3485. EXPECT_EQ(req.body, "dechunked post body");
  3486. })
  3487. .Post("/large-chunked",
  3488. [&](const Request &req, Response & /*res*/) {
  3489. std::string expected(6 * 30 * 1024u, 'a');
  3490. EXPECT_EQ(req.body, expected);
  3491. })
  3492. .Post("/multipart",
  3493. [&](const Request &req, Response & /*res*/) {
  3494. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3495. req.form.get_field_count("text2") +
  3496. req.form.get_field_count("file3") +
  3497. req.form.get_field_count("file4"));
  3498. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3499. req.form.get_file_count("file2"));
  3500. ASSERT_TRUE(!req.form.has_file("???"));
  3501. ASSERT_TRUE(!req.form.has_field("???"));
  3502. ASSERT_TRUE(req.body.empty());
  3503. {
  3504. const auto &text = req.form.get_field("text1");
  3505. EXPECT_EQ("text default", text);
  3506. }
  3507. {
  3508. const auto &text = req.form.get_field("text2");
  3509. EXPECT_EQ("aωb", text);
  3510. }
  3511. {
  3512. const auto &file = req.form.get_file("file1");
  3513. EXPECT_EQ("hello.txt", file.filename);
  3514. EXPECT_EQ("text/plain", file.content_type);
  3515. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3516. }
  3517. {
  3518. const auto &file = req.form.get_file("file2");
  3519. EXPECT_EQ("world.json", file.filename);
  3520. EXPECT_EQ("application/json", file.content_type);
  3521. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3522. }
  3523. {
  3524. const auto &text = req.form.get_field("file3");
  3525. EXPECT_EQ(0u, text.size());
  3526. }
  3527. {
  3528. const auto &text = req.form.get_field("file4");
  3529. EXPECT_EQ(0u, text.size());
  3530. }
  3531. })
  3532. .Post("/multipart/multi_file_values",
  3533. [&](const Request &req, Response & /*res*/) {
  3534. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3535. req.form.get_field_count("multi_text1"));
  3536. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3537. ASSERT_TRUE(!req.form.has_file("???"));
  3538. ASSERT_TRUE(!req.form.has_field("???"));
  3539. ASSERT_TRUE(req.body.empty());
  3540. {
  3541. const auto &text = req.form.get_field("text");
  3542. EXPECT_EQ("default text", text);
  3543. }
  3544. {
  3545. const auto &text1_values = req.form.get_fields("multi_text1");
  3546. EXPECT_EQ(2u, text1_values.size());
  3547. EXPECT_EQ("aaaaa", text1_values[0]);
  3548. EXPECT_EQ("bbbbb", text1_values[1]);
  3549. }
  3550. {
  3551. const auto &file1_values = req.form.get_files("multi_file1");
  3552. EXPECT_EQ(2u, file1_values.size());
  3553. auto file1 = file1_values[0];
  3554. EXPECT_EQ(file1.filename, "hello.txt");
  3555. EXPECT_EQ(file1.content_type, "text/plain");
  3556. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3557. auto file2 = file1_values[1];
  3558. EXPECT_EQ(file2.filename, "world.json");
  3559. EXPECT_EQ(file2.content_type, "application/json");
  3560. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3561. }
  3562. })
  3563. .Post("/empty",
  3564. [&](const Request &req, Response &res) {
  3565. EXPECT_EQ(req.body, "");
  3566. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3567. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3568. res.set_content("empty", "text/plain");
  3569. })
  3570. .Post("/empty-no-content-type",
  3571. [&](const Request &req, Response &res) {
  3572. EXPECT_EQ(req.body, "");
  3573. EXPECT_FALSE(req.has_header("Content-Type"));
  3574. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3575. res.set_content("empty-no-content-type", "text/plain");
  3576. })
  3577. .Post("/path-only",
  3578. [&](const Request &req, Response &res) {
  3579. EXPECT_EQ(req.body, "");
  3580. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3581. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3582. res.set_content("path-only", "text/plain");
  3583. })
  3584. .Post("/path-headers-only",
  3585. [&](const Request &req, Response &res) {
  3586. EXPECT_EQ(req.body, "");
  3587. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3588. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3589. EXPECT_EQ("world", req.get_header_value("hello"));
  3590. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3591. res.set_content("path-headers-only", "text/plain");
  3592. })
  3593. .Post("/post-large",
  3594. [&](const Request &req, Response &res) {
  3595. EXPECT_EQ(req.body, LARGE_DATA);
  3596. res.set_content(req.body, "text/plain");
  3597. })
  3598. .Post("/post-loopback",
  3599. [&](const Request &, Response &res,
  3600. ContentReader const &content_reader) {
  3601. std::string body;
  3602. content_reader([&](const char *data, size_t data_length) {
  3603. body.append(data, data_length);
  3604. return true;
  3605. });
  3606. res.set_content(body, "text/plain");
  3607. })
  3608. .Put("/put-loopback",
  3609. [&](const Request &, Response &res,
  3610. ContentReader const &content_reader) {
  3611. std::string body;
  3612. content_reader([&](const char *data, size_t data_length) {
  3613. body.append(data, data_length);
  3614. return true;
  3615. });
  3616. res.set_content(body, "text/plain");
  3617. })
  3618. .Patch("/patch-loopback",
  3619. [&](const Request &, Response &res,
  3620. ContentReader const &content_reader) {
  3621. std::string body;
  3622. content_reader([&](const char *data, size_t data_length) {
  3623. body.append(data, data_length);
  3624. return true;
  3625. });
  3626. res.set_content(body, "text/plain");
  3627. })
  3628. .Put("/empty-no-content-type",
  3629. [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(req.body, "");
  3631. EXPECT_FALSE(req.has_header("Content-Type"));
  3632. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3633. res.set_content("empty-no-content-type", "text/plain");
  3634. })
  3635. .Put("/put",
  3636. [&](const Request &req, Response &res) {
  3637. EXPECT_EQ(req.body, "PUT");
  3638. res.set_content(req.body, "text/plain");
  3639. })
  3640. .Put("/put-large",
  3641. [&](const Request &req, Response &res) {
  3642. EXPECT_EQ(req.body, LARGE_DATA);
  3643. res.set_content(req.body, "text/plain");
  3644. })
  3645. .Patch("/patch",
  3646. [&](const Request &req, Response &res) {
  3647. EXPECT_EQ(req.body, "PATCH");
  3648. res.set_content(req.body, "text/plain");
  3649. })
  3650. .Delete("/delete",
  3651. [&](const Request & /*req*/, Response &res) {
  3652. res.set_content("DELETE", "text/plain");
  3653. })
  3654. .Delete("/delete-body",
  3655. [&](const Request &req, Response &res) {
  3656. EXPECT_EQ(req.body, "content");
  3657. res.set_content(req.body, "text/plain");
  3658. })
  3659. .Options(R"(\*)",
  3660. [&](const Request & /*req*/, Response &res) {
  3661. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3662. })
  3663. .Get("/request-target",
  3664. [&](const Request &req, Response & /*res*/) {
  3665. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3666. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3667. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3668. })
  3669. .Get("/long-query-value",
  3670. [&](const Request &req, Response & /*res*/) {
  3671. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3672. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3673. })
  3674. .Get("/too-long-query-value",
  3675. [&](const Request &req, Response & /*res*/) {
  3676. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3677. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3678. })
  3679. .Get("/array-param",
  3680. [&](const Request &req, Response & /*res*/) {
  3681. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3682. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3683. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3684. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3685. })
  3686. .Get("/array-param-values",
  3687. [&](const Request &req, Response & /*res*/) {
  3688. auto values = req.get_param_values("array");
  3689. EXPECT_EQ(3u, values.size());
  3690. EXPECT_EQ("value1", values[0]);
  3691. EXPECT_EQ("value2", values[1]);
  3692. EXPECT_EQ("value3", values[2]);
  3693. auto empty = req.get_param_values("nonexistent");
  3694. EXPECT_TRUE(empty.empty());
  3695. })
  3696. .Post("/validate-no-multiple-headers",
  3697. [&](const Request &req, Response & /*res*/) {
  3698. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3699. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3700. })
  3701. .Post("/content_receiver",
  3702. [&](const Request &req, Response &res,
  3703. const ContentReader &content_reader) {
  3704. if (req.is_multipart_form_data()) {
  3705. std::vector<FormData> items;
  3706. content_reader(
  3707. [&](const FormData &file) {
  3708. items.push_back(file);
  3709. return true;
  3710. },
  3711. [&](const char *data, size_t data_length) {
  3712. items.back().content.append(data, data_length);
  3713. return true;
  3714. });
  3715. EXPECT_EQ(5u, items.size());
  3716. {
  3717. const auto &file = get_file_value(items, "text1");
  3718. EXPECT_TRUE(file.filename.empty());
  3719. EXPECT_EQ("text default", file.content);
  3720. }
  3721. {
  3722. const auto &file = get_file_value(items, "text2");
  3723. EXPECT_TRUE(file.filename.empty());
  3724. EXPECT_EQ("aωb", file.content);
  3725. }
  3726. {
  3727. const auto &file = get_file_value(items, "file1");
  3728. EXPECT_EQ("hello.txt", file.filename);
  3729. EXPECT_EQ("text/plain", file.content_type);
  3730. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3731. }
  3732. {
  3733. const auto &file = get_file_value(items, "file2");
  3734. EXPECT_EQ("world.json", file.filename);
  3735. EXPECT_EQ("application/json", file.content_type);
  3736. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3737. }
  3738. {
  3739. const auto &file = get_file_value(items, "file3");
  3740. EXPECT_TRUE(file.filename.empty());
  3741. EXPECT_EQ("application/octet-stream", file.content_type);
  3742. EXPECT_EQ(0u, file.content.size());
  3743. }
  3744. } else {
  3745. std::string body;
  3746. content_reader([&](const char *data, size_t data_length) {
  3747. EXPECT_EQ(7U, data_length);
  3748. body.append(data, data_length);
  3749. return true;
  3750. });
  3751. EXPECT_EQ(body, "content");
  3752. res.set_content(body, "text/plain");
  3753. }
  3754. })
  3755. .Put("/content_receiver",
  3756. [&](const Request & /*req*/, Response &res,
  3757. const ContentReader &content_reader) {
  3758. std::string body;
  3759. content_reader([&](const char *data, size_t data_length) {
  3760. body.append(data, data_length);
  3761. return true;
  3762. });
  3763. EXPECT_EQ(body, "content");
  3764. res.set_content(body, "text/plain");
  3765. })
  3766. .Patch("/content_receiver",
  3767. [&](const Request & /*req*/, Response &res,
  3768. const ContentReader &content_reader) {
  3769. std::string body;
  3770. content_reader([&](const char *data, size_t data_length) {
  3771. body.append(data, data_length);
  3772. return true;
  3773. });
  3774. EXPECT_EQ(body, "content");
  3775. res.set_content(body, "text/plain");
  3776. })
  3777. .Post("/query-string-and-body",
  3778. [&](const Request &req, Response & /*res*/) {
  3779. ASSERT_TRUE(req.has_param("key"));
  3780. EXPECT_EQ(req.get_param_value("key"), "value");
  3781. EXPECT_EQ(req.body, "content");
  3782. })
  3783. .Get("/last-request",
  3784. [&](const Request &req, Response & /*res*/) {
  3785. EXPECT_EQ("close", req.get_header_value("Connection"));
  3786. })
  3787. .Get(R"(/redirect/(\d+))",
  3788. [&](const Request &req, Response &res) {
  3789. auto num = std::stoi(req.matches[1]) + 1;
  3790. std::string url = "/redirect/" + std::to_string(num);
  3791. res.set_redirect(url);
  3792. })
  3793. .Post("/binary",
  3794. [&](const Request &req, Response &res) {
  3795. EXPECT_EQ(4U, req.body.size());
  3796. EXPECT_EQ("application/octet-stream",
  3797. req.get_header_value("Content-Type"));
  3798. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3799. res.set_content(req.body, "application/octet-stream");
  3800. })
  3801. .Put("/binary",
  3802. [&](const Request &req, Response &res) {
  3803. EXPECT_EQ(4U, req.body.size());
  3804. EXPECT_EQ("application/octet-stream",
  3805. req.get_header_value("Content-Type"));
  3806. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3807. res.set_content(req.body, "application/octet-stream");
  3808. })
  3809. .Patch("/binary",
  3810. [&](const Request &req, Response &res) {
  3811. EXPECT_EQ(4U, req.body.size());
  3812. EXPECT_EQ("application/octet-stream",
  3813. req.get_header_value("Content-Type"));
  3814. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3815. res.set_content(req.body, "application/octet-stream");
  3816. })
  3817. .Delete("/binary",
  3818. [&](const Request &req, Response &res) {
  3819. EXPECT_EQ(4U, req.body.size());
  3820. EXPECT_EQ("application/octet-stream",
  3821. req.get_header_value("Content-Type"));
  3822. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3823. res.set_content(req.body, "application/octet-stream");
  3824. })
  3825. .Get("/issue1772",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. res.status = 401;
  3828. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3829. })
  3830. .Delete("/issue609",
  3831. [](const httplib::Request &, httplib::Response &res,
  3832. const httplib::ContentReader &) {
  3833. res.set_content("ok", "text/plain");
  3834. })
  3835. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3836. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3837. .Get("/compress",
  3838. [&](const Request & /*req*/, Response &res) {
  3839. res.set_content(
  3840. "12345678901234567890123456789012345678901234567890123456789"
  3841. "01234567890123456789012345678901234567890",
  3842. "text/plain");
  3843. })
  3844. .Get("/compress-with-charset",
  3845. [&](const Request & /*req*/, Response &res) {
  3846. res.set_content(
  3847. "12345678901234567890123456789012345678901234567890123456789"
  3848. "01234567890123456789012345678901234567890",
  3849. "application/json; charset=utf-8");
  3850. })
  3851. .Get("/nocompress",
  3852. [&](const Request & /*req*/, Response &res) {
  3853. res.set_content(
  3854. "12345678901234567890123456789012345678901234567890123456789"
  3855. "01234567890123456789012345678901234567890",
  3856. "application/octet-stream");
  3857. })
  3858. .Post("/compress-multipart",
  3859. [&](const Request &req, Response & /*res*/) {
  3860. EXPECT_EQ(2u, req.form.fields.size());
  3861. ASSERT_TRUE(!req.form.has_field("???"));
  3862. {
  3863. const auto &text = req.form.get_field("key1");
  3864. EXPECT_EQ("test", text);
  3865. }
  3866. {
  3867. const auto &text = req.form.get_field("key2");
  3868. EXPECT_EQ("--abcdefg123", text);
  3869. }
  3870. })
  3871. #endif
  3872. ;
  3873. persons_["john"] = "programmer";
  3874. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3875. svr_.wait_until_ready();
  3876. }
  3877. virtual void TearDown() {
  3878. svr_.stop();
  3879. if (!request_threads_.empty()) {
  3880. std::this_thread::sleep_for(std::chrono::seconds(1));
  3881. for (auto &t : request_threads_) {
  3882. t.join();
  3883. }
  3884. }
  3885. t_.join();
  3886. }
  3887. map<string, string> persons_;
  3888. #ifdef CPPHTTPLIB_SSL_ENABLED
  3889. SSLClient cli_;
  3890. SSLServer svr_;
  3891. #else
  3892. Client cli_;
  3893. Server svr_;
  3894. #endif
  3895. thread t_;
  3896. std::vector<thread> request_threads_;
  3897. };
  3898. TEST_F(ServerTest, GetMethod200) {
  3899. auto res = cli_.Get("/hi");
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ("HTTP/1.1", res->version);
  3902. EXPECT_EQ(StatusCode::OK_200, res->status);
  3903. EXPECT_EQ("OK", res->reason);
  3904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3905. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3906. EXPECT_EQ("Hello World!", res->body);
  3907. }
  3908. TEST_F(ServerTest, GetEmptyFile) {
  3909. auto res = cli_.Get("/empty_file");
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3913. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3914. EXPECT_EQ("", res->body);
  3915. }
  3916. TEST_F(ServerTest, GetFileContent) {
  3917. auto res = cli_.Get("/file_content");
  3918. ASSERT_TRUE(res);
  3919. EXPECT_EQ(StatusCode::OK_200, res->status);
  3920. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3921. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3922. EXPECT_EQ("test.html", res->body);
  3923. }
  3924. TEST_F(ServerTest, GetFileContentWithRange) {
  3925. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3928. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3929. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3930. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3931. EXPECT_EQ("est", res->body);
  3932. }
  3933. TEST_F(ServerTest, GetFileContentWithContentType) {
  3934. auto res = cli_.Get("/file_content_with_content_type");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(StatusCode::OK_200, res->status);
  3937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3938. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3939. EXPECT_EQ("file\n", res->body);
  3940. }
  3941. TEST_F(ServerTest, GetInvalidFileContent) {
  3942. auto res = cli_.Get("/invalid_file_content");
  3943. ASSERT_TRUE(res);
  3944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3945. }
  3946. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3947. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ("HTTP/1.1", res->version);
  3950. EXPECT_EQ(StatusCode::OK_200, res->status);
  3951. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3952. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3953. EXPECT_EQ("Hello World!", res->body);
  3954. }
  3955. TEST_F(ServerTest, GetMethod302) {
  3956. auto res = cli_.Get("/");
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::Found_302, res->status);
  3959. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3960. }
  3961. TEST_F(ServerTest, GetMethod302Redirect) {
  3962. cli_.set_follow_location(true);
  3963. auto res = cli_.Get("/");
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. EXPECT_EQ("Hello World!", res->body);
  3967. EXPECT_EQ("/hi", res->location);
  3968. }
  3969. TEST_F(ServerTest, GetMethod404) {
  3970. auto res = cli_.Get("/invalid");
  3971. ASSERT_TRUE(res);
  3972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3973. }
  3974. TEST_F(ServerTest, HeadMethod200) {
  3975. auto res = cli_.Head("/hi");
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::OK_200, res->status);
  3978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3979. EXPECT_TRUE(res->body.empty());
  3980. }
  3981. TEST_F(ServerTest, HeadMethod200Static) {
  3982. auto res = cli_.Head("/mount/dir/index.html");
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3986. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3987. EXPECT_TRUE(res->body.empty());
  3988. }
  3989. TEST_F(ServerTest, HeadMethod404) {
  3990. auto res = cli_.Head("/invalid");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3993. EXPECT_TRUE(res->body.empty());
  3994. }
  3995. TEST_F(ServerTest, GetMethodPersonJohn) {
  3996. auto res = cli_.Get("/person/john");
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::OK_200, res->status);
  3999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4000. EXPECT_EQ("programmer", res->body);
  4001. }
  4002. TEST_F(ServerTest, PostMethod1) {
  4003. auto res = cli_.Get("/person/john1");
  4004. ASSERT_TRUE(res);
  4005. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4006. res = cli_.Post("/person", "name=john1&note=coder",
  4007. "application/x-www-form-urlencoded");
  4008. ASSERT_TRUE(res);
  4009. ASSERT_EQ(StatusCode::OK_200, res->status);
  4010. res = cli_.Get("/person/john1");
  4011. ASSERT_TRUE(res);
  4012. ASSERT_EQ(StatusCode::OK_200, res->status);
  4013. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4014. ASSERT_EQ("coder", res->body);
  4015. }
  4016. TEST_F(ServerTest, PostMethod2) {
  4017. auto res = cli_.Get("/person/john2");
  4018. ASSERT_TRUE(res);
  4019. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4020. Params params;
  4021. params.emplace("name", "john2");
  4022. params.emplace("note", "coder");
  4023. res = cli_.Post("/person", params);
  4024. ASSERT_TRUE(res);
  4025. ASSERT_EQ(StatusCode::OK_200, res->status);
  4026. res = cli_.Get("/person/john2");
  4027. ASSERT_TRUE(res);
  4028. ASSERT_EQ(StatusCode::OK_200, res->status);
  4029. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4030. ASSERT_EQ("coder", res->body);
  4031. }
  4032. TEST_F(ServerTest, PutMethod3) {
  4033. auto res = cli_.Get("/person/john3");
  4034. ASSERT_TRUE(res);
  4035. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4036. Params params;
  4037. params.emplace("name", "john3");
  4038. params.emplace("note", "coder");
  4039. res = cli_.Put("/person", params);
  4040. ASSERT_TRUE(res);
  4041. ASSERT_EQ(StatusCode::OK_200, res->status);
  4042. res = cli_.Get("/person/john3");
  4043. ASSERT_TRUE(res);
  4044. ASSERT_EQ(StatusCode::OK_200, res->status);
  4045. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4046. ASSERT_EQ("coder", res->body);
  4047. }
  4048. TEST_F(ServerTest, DeleteMethod1) {
  4049. auto res = cli_.Get("/person/john4");
  4050. ASSERT_TRUE(res);
  4051. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4052. Params params;
  4053. params.emplace("name", "john4");
  4054. params.emplace("note", "coder");
  4055. res = cli_.Post("/person", params);
  4056. ASSERT_TRUE(res);
  4057. ASSERT_EQ(StatusCode::OK_200, res->status);
  4058. res = cli_.Get("/person/john4");
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4062. ASSERT_EQ("coder", res->body);
  4063. Params delete_params;
  4064. delete_params.emplace("name", "john4");
  4065. res = cli_.Delete("/person", delete_params);
  4066. ASSERT_TRUE(res);
  4067. ASSERT_EQ(StatusCode::OK_200, res->status);
  4068. ASSERT_EQ("DELETED", res->body);
  4069. res = cli_.Get("/person/john4");
  4070. ASSERT_TRUE(res);
  4071. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, DeleteMethod2) {
  4074. auto res = cli_.Get("/person/john5");
  4075. ASSERT_TRUE(res);
  4076. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4077. Params params;
  4078. params.emplace("name", "john5");
  4079. params.emplace("note", "developer");
  4080. res = cli_.Post("/person", params);
  4081. ASSERT_TRUE(res);
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. res = cli_.Get("/person/john5");
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4087. ASSERT_EQ("developer", res->body);
  4088. Params delete_params;
  4089. delete_params.emplace("name", "john5");
  4090. Headers headers;
  4091. headers.emplace("Custom-Header", "test-value");
  4092. res = cli_.Delete("/person", headers, delete_params);
  4093. ASSERT_TRUE(res);
  4094. ASSERT_EQ(StatusCode::OK_200, res->status);
  4095. ASSERT_EQ("DELETED", res->body);
  4096. res = cli_.Get("/person/john5");
  4097. ASSERT_TRUE(res);
  4098. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4099. }
  4100. TEST_F(ServerTest, DeleteMethod3) {
  4101. auto res = cli_.Get("/person/john6");
  4102. ASSERT_TRUE(res);
  4103. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4104. Params params;
  4105. params.emplace("name", "john6");
  4106. params.emplace("note", "tester");
  4107. res = cli_.Post("/person", params);
  4108. ASSERT_TRUE(res);
  4109. ASSERT_EQ(StatusCode::OK_200, res->status);
  4110. res = cli_.Get("/person/john6");
  4111. ASSERT_TRUE(res);
  4112. ASSERT_EQ(StatusCode::OK_200, res->status);
  4113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4114. ASSERT_EQ("tester", res->body);
  4115. Params delete_params;
  4116. delete_params.emplace("name", "john6");
  4117. Headers headers;
  4118. headers.emplace("Custom-Header", "test-value");
  4119. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ("DELETED", res->body);
  4123. res = cli_.Get("/person/john6");
  4124. ASSERT_TRUE(res);
  4125. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4128. Params params;
  4129. params.emplace("json", JSON_DATA);
  4130. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4131. ASSERT_TRUE(res);
  4132. ASSERT_EQ(StatusCode::OK_200, res->status);
  4133. ASSERT_EQ(JSON_DATA, res->body);
  4134. }
  4135. TEST_F(ServerTest, PostEmptyContent) {
  4136. auto res = cli_.Post("/empty", "", "text/plain");
  4137. ASSERT_TRUE(res);
  4138. ASSERT_EQ(StatusCode::OK_200, res->status);
  4139. ASSERT_EQ("empty", res->body);
  4140. }
  4141. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4142. auto res = cli_.Post("/empty-no-content-type");
  4143. ASSERT_TRUE(res);
  4144. ASSERT_EQ(StatusCode::OK_200, res->status);
  4145. ASSERT_EQ("empty-no-content-type", res->body);
  4146. }
  4147. TEST_F(ServerTest, PostPathOnly) {
  4148. auto res = cli_.Post("/path-only");
  4149. ASSERT_TRUE(res);
  4150. ASSERT_EQ(StatusCode::OK_200, res->status);
  4151. ASSERT_EQ("path-only", res->body);
  4152. }
  4153. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4154. auto res = cli_.Post("/path-headers-only",
  4155. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4156. ASSERT_TRUE(res);
  4157. ASSERT_EQ(StatusCode::OK_200, res->status);
  4158. ASSERT_EQ("path-headers-only", res->body);
  4159. }
  4160. TEST_F(ServerTest, PostLarge) {
  4161. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::OK_200, res->status);
  4164. EXPECT_EQ(LARGE_DATA, res->body);
  4165. }
  4166. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4167. auto res = cli_.Put("/empty-no-content-type");
  4168. ASSERT_TRUE(res);
  4169. ASSERT_EQ(StatusCode::OK_200, res->status);
  4170. ASSERT_EQ("empty-no-content-type", res->body);
  4171. }
  4172. TEST_F(ServerTest, GetMethodDir) {
  4173. auto res = cli_.Get("/dir/");
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4177. auto body = R"(<html>
  4178. <head>
  4179. </head>
  4180. <body>
  4181. <a href="/dir/test.html">Test</a>
  4182. <a href="/hi">hi</a>
  4183. </body>
  4184. </html>
  4185. )";
  4186. EXPECT_EQ(body, res->body);
  4187. }
  4188. TEST_F(ServerTest, GetMethodDirTest) {
  4189. auto res = cli_.Get("/dir/test.html");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4193. EXPECT_EQ("test.html", res->body);
  4194. }
  4195. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4196. auto res = cli_.Get("/dir/../dir/test.html");
  4197. ASSERT_TRUE(res);
  4198. EXPECT_EQ(StatusCode::OK_200, res->status);
  4199. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4200. EXPECT_EQ("test.html", res->body);
  4201. }
  4202. TEST_F(ServerTest, GetMethodInvalidPath) {
  4203. auto res = cli_.Get("/dir/../test.html");
  4204. ASSERT_TRUE(res);
  4205. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4206. }
  4207. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4208. auto res = cli_.Get("/../www/dir/test.html");
  4209. ASSERT_TRUE(res);
  4210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4211. }
  4212. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4213. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4216. }
  4217. TEST_F(ServerTest, GetMethodDirMountTest) {
  4218. auto res = cli_.Get("/mount/dir/test.html");
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4222. EXPECT_EQ("test.html", res->body);
  4223. }
  4224. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4225. auto res = cli_.Get("/mount/dir/../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, GetMethodInvalidMountPath) {
  4232. auto res = cli_.Get("/mount/dir/../test.html");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4237. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4242. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4247. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4250. }
  4251. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4252. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4253. ASSERT_TRUE(res);
  4254. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4255. }
  4256. TEST_F(ServerTest, PostMethod303) {
  4257. auto res = cli_.Post("/1", "body", "text/plain");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4260. EXPECT_EQ("/2", res->get_header_value("Location"));
  4261. }
  4262. TEST_F(ServerTest, PostMethod303Redirect) {
  4263. cli_.set_follow_location(true);
  4264. auto res = cli_.Post("/1", "body", "text/plain");
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::OK_200, res->status);
  4267. EXPECT_EQ("redirected.", res->body);
  4268. EXPECT_EQ("/2", res->location);
  4269. }
  4270. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4271. auto res = cli_.Get("/dir/test.abcde");
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4275. EXPECT_EQ("abcde", res->body);
  4276. }
  4277. TEST_F(ServerTest, StaticFileRange) {
  4278. auto res =
  4279. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4282. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4283. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4284. EXPECT_EQ(true, res->has_header("Content-Range"));
  4285. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4286. EXPECT_EQ(std::string("cd"), res->body);
  4287. }
  4288. TEST_F(ServerTest, StaticFileRanges) {
  4289. auto res = cli_.Get("/dir/test.abcde",
  4290. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4293. EXPECT_TRUE(
  4294. res->get_header_value("Content-Type")
  4295. .find(
  4296. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4297. 0);
  4298. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4299. }
  4300. TEST_F(ServerTest, StaticFileRangeHead) {
  4301. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4304. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4305. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(true, res->has_header("Content-Range"));
  4307. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4308. }
  4309. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4310. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4314. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4315. EXPECT_EQ(true, res->has_header("Content-Range"));
  4316. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4317. res->get_header_value("Content-Range"));
  4318. EXPECT_EQ("LAST\n", res->body);
  4319. }
  4320. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4321. auto res =
  4322. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4326. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4327. EXPECT_EQ(true, res->has_header("Content-Range"));
  4328. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4329. }
  4330. TEST_F(ServerTest, StaticFileBigFile) {
  4331. auto res = cli_.Get("/dir/1MB.txt");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4335. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4336. }
  4337. TEST_F(ServerTest, InvalidBaseDirMount) {
  4338. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4339. }
  4340. TEST_F(ServerTest, Binary) {
  4341. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4342. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4343. "application/octet-stream");
  4344. ASSERT_TRUE(res);
  4345. ASSERT_EQ(StatusCode::OK_200, res->status);
  4346. ASSERT_EQ(4U, res->body.size());
  4347. res = cli_.Put("/binary", binary.data(), binary.size(),
  4348. "application/octet-stream");
  4349. ASSERT_TRUE(res);
  4350. ASSERT_EQ(StatusCode::OK_200, res->status);
  4351. ASSERT_EQ(4U, res->body.size());
  4352. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4353. "application/octet-stream");
  4354. ASSERT_TRUE(res);
  4355. ASSERT_EQ(StatusCode::OK_200, res->status);
  4356. ASSERT_EQ(4U, res->body.size());
  4357. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4358. "application/octet-stream");
  4359. ASSERT_TRUE(res);
  4360. ASSERT_EQ(StatusCode::OK_200, res->status);
  4361. ASSERT_EQ(4U, res->body.size());
  4362. }
  4363. TEST_F(ServerTest, BinaryString) {
  4364. auto binary = std::string("\x00\x01\x02\x03", 4);
  4365. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4366. ASSERT_TRUE(res);
  4367. ASSERT_EQ(StatusCode::OK_200, res->status);
  4368. ASSERT_EQ(4U, res->body.size());
  4369. res = cli_.Put("/binary", binary, "application/octet-stream");
  4370. ASSERT_TRUE(res);
  4371. ASSERT_EQ(StatusCode::OK_200, res->status);
  4372. ASSERT_EQ(4U, res->body.size());
  4373. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4374. ASSERT_TRUE(res);
  4375. ASSERT_EQ(StatusCode::OK_200, res->status);
  4376. ASSERT_EQ(4U, res->body.size());
  4377. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4378. ASSERT_TRUE(res);
  4379. ASSERT_EQ(StatusCode::OK_200, res->status);
  4380. ASSERT_EQ(4U, res->body.size());
  4381. }
  4382. TEST_F(ServerTest, EmptyRequest) {
  4383. auto res = cli_.Get("");
  4384. ASSERT_TRUE(!res);
  4385. EXPECT_EQ(Error::Connection, res.error());
  4386. }
  4387. TEST_F(ServerTest, LongRequest) {
  4388. std::string request;
  4389. for (size_t i = 0; i < 545; i++) {
  4390. request += "/TooLongRequest";
  4391. }
  4392. request += "OK";
  4393. auto res = cli_.Get(request.c_str());
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4396. }
  4397. TEST_F(ServerTest, TooLongRequest) {
  4398. std::string request;
  4399. for (size_t i = 0; i < 546; i++) {
  4400. request += "/TooLongRequest";
  4401. }
  4402. request += "_NG";
  4403. auto start = std::chrono::high_resolution_clock::now();
  4404. cli_.set_keep_alive(true);
  4405. auto res = cli_.Get(request.c_str());
  4406. auto end = std::chrono::high_resolution_clock::now();
  4407. auto elapsed =
  4408. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4409. .count();
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4412. EXPECT_LE(elapsed, 1000);
  4413. EXPECT_EQ("close", res->get_header_value("Connection"));
  4414. EXPECT_FALSE(cli_.is_socket_open());
  4415. }
  4416. TEST_F(ServerTest, AlmostTooLongRequest) {
  4417. // test for #2046 - URI length check shouldn't include other content on req
  4418. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4419. // leading /, space, HTTP/1.1)
  4420. std::string request =
  4421. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4422. auto res = cli_.Get(request.c_str());
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4425. }
  4426. TEST_F(ServerTest, LongHeader) {
  4427. Request req;
  4428. req.method = "GET";
  4429. req.path = "/hi";
  4430. std::string host_and_port;
  4431. host_and_port += HOST;
  4432. host_and_port += ":";
  4433. host_and_port += std::to_string(PORT);
  4434. req.headers.emplace("Host", host_and_port.c_str());
  4435. req.headers.emplace("Accept", "*/*");
  4436. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4437. req.headers.emplace(
  4438. "Header-Name",
  4439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4467. "@@@@@@@@@@@@@@@@");
  4468. auto res = std::make_shared<Response>();
  4469. auto error = Error::Success;
  4470. auto ret = cli_.send(req, *res, error);
  4471. ASSERT_TRUE(ret);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. }
  4474. TEST_F(ServerTest, LongQueryValue) {
  4475. auto start = std::chrono::high_resolution_clock::now();
  4476. cli_.set_keep_alive(true);
  4477. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4478. auto end = std::chrono::high_resolution_clock::now();
  4479. auto elapsed =
  4480. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4481. .count();
  4482. ASSERT_TRUE(res);
  4483. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4484. EXPECT_LE(elapsed, 1000);
  4485. EXPECT_EQ("close", res->get_header_value("Connection"));
  4486. EXPECT_FALSE(cli_.is_socket_open());
  4487. }
  4488. TEST_F(ServerTest, TooLongQueryValue) {
  4489. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4490. ASSERT_FALSE(res);
  4491. EXPECT_EQ(Error::Read, res.error());
  4492. }
  4493. TEST_F(ServerTest, TooLongHeader) {
  4494. Request req;
  4495. req.method = "GET";
  4496. req.path = "/hi";
  4497. std::string host_and_port;
  4498. host_and_port += HOST;
  4499. host_and_port += ":";
  4500. host_and_port += std::to_string(PORT);
  4501. req.headers.emplace("Host", host_and_port.c_str());
  4502. req.headers.emplace("Accept", "*/*");
  4503. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4504. req.headers.emplace(
  4505. "Header-Name",
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4534. "@@@@@@@@@@@@@@@@@");
  4535. auto res = std::make_shared<Response>();
  4536. auto error = Error::Success;
  4537. auto ret = cli_.send(req, *res, error);
  4538. ASSERT_TRUE(ret);
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. }
  4541. TEST_F(ServerTest, HeaderCountAtLimit) {
  4542. // Test with headers just under the 100 limit
  4543. httplib::Headers headers;
  4544. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4545. // This should keep us just under the 100 header limit
  4546. for (int i = 0; i < 95; i++) {
  4547. std::string name = "X-Test-Header-" + std::to_string(i);
  4548. std::string value = "value" + std::to_string(i);
  4549. headers.emplace(name, value);
  4550. }
  4551. // This should work fine as we're under the limit
  4552. auto res = cli_.Get("/hi", headers);
  4553. EXPECT_TRUE(res);
  4554. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4555. }
  4556. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4557. // Test with many headers to exceed the 100 limit
  4558. httplib::Headers headers;
  4559. // Add 150 headers to definitely exceed the 100 limit
  4560. for (int i = 0; i < 150; i++) {
  4561. std::string name = "X-Test-Header-" + std::to_string(i);
  4562. std::string value = "value" + std::to_string(i);
  4563. headers.emplace(name, value);
  4564. }
  4565. // This should fail due to exceeding header count limit
  4566. cli_.set_keep_alive(true);
  4567. auto res = cli_.Get("/hi", headers);
  4568. // The server should respond with 400 Bad Request
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4571. EXPECT_EQ("close", res->get_header_value("Connection"));
  4572. EXPECT_FALSE(cli_.is_socket_open());
  4573. }
  4574. TEST_F(ServerTest, PercentEncoding) {
  4575. auto res = cli_.Get("/e%6edwith%");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. }
  4579. TEST_F(ServerTest, PercentEncodingUnicode) {
  4580. auto res = cli_.Get("/e%u006edwith%");
  4581. ASSERT_TRUE(res);
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. }
  4584. TEST_F(ServerTest, InvalidPercentEncoding) {
  4585. auto res = cli_.Get("/%endwith%");
  4586. ASSERT_TRUE(res);
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4590. auto res = cli_.Get("/%uendwith%");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4593. }
  4594. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4595. auto res = cli_.Get("/hello?aaa=bbb%");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4598. }
  4599. TEST_F(ServerTest, PlusSignEncoding) {
  4600. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("a +b", res->body);
  4604. }
  4605. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4606. // This test simulates a potential DoS attack using many headers
  4607. // to verify our security fix prevents memory exhaustion
  4608. httplib::Headers attack_headers;
  4609. // Attempt to add many headers like an attacker would (200 headers to far
  4610. // exceed limit)
  4611. for (int i = 0; i < 200; i++) {
  4612. std::string name = "X-Attack-Header-" + std::to_string(i);
  4613. std::string value = "attack_payload_" + std::to_string(i);
  4614. attack_headers.emplace(name, value);
  4615. }
  4616. // Try to POST with excessive headers
  4617. cli_.set_keep_alive(true);
  4618. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4619. // Should either fail or return 400 Bad Request due to security limit
  4620. if (res) {
  4621. // If we get a response, it should be 400 Bad Request
  4622. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4623. EXPECT_EQ("close", res->get_header_value("Connection"));
  4624. }
  4625. EXPECT_FALSE(cli_.is_socket_open());
  4626. }
  4627. TEST_F(ServerTest, MultipartFormData) {
  4628. UploadFormDataItems items = {
  4629. {"text1", "text default", "", ""},
  4630. {"text2", "aωb", "", ""},
  4631. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4632. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4633. {"file3", "", "", "application/octet-stream"},
  4634. {"file4", "", "", " application/json tmp-string "}};
  4635. auto res = cli_.Post("/multipart", items);
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4640. UploadFormDataItems items = {
  4641. {"text", "default text", "", ""},
  4642. {"multi_text1", "aaaaa", "", ""},
  4643. {"multi_text1", "bbbbb", "", ""},
  4644. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4645. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4646. "application/json"},
  4647. };
  4648. auto res = cli_.Post("/multipart/multi_file_values", items);
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. }
  4652. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4653. auto res = cli_.Get("/hi");
  4654. ASSERT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::OK_200, res->status);
  4656. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4657. EXPECT_EQ("Hello World!", res->body);
  4658. }
  4659. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4660. Request req;
  4661. req.method = "POST";
  4662. req.path = "/chunked";
  4663. std::string host_and_port;
  4664. host_and_port += HOST;
  4665. host_and_port += ":";
  4666. host_and_port += std::to_string(PORT);
  4667. req.headers.emplace("Host", host_and_port.c_str());
  4668. req.headers.emplace("Accept", "*/*");
  4669. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4670. req.headers.emplace("Content-Type", "text/plain");
  4671. req.headers.emplace("Content-Length", "0");
  4672. req.headers.emplace(
  4673. "Transfer-Encoding",
  4674. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4675. // Client does not chunk, so make a chunked body manually.
  4676. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4677. auto res = std::make_shared<Response>();
  4678. auto error = Error::Success;
  4679. auto ret = cli_.send(req, *res, error);
  4680. ASSERT_TRUE(ret);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. }
  4683. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4684. // rather than treat them as valid lengths.
  4685. template <typename ClientT>
  4686. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4687. Request req;
  4688. req.method = "POST";
  4689. req.path = "/chunked";
  4690. std::string host_and_port;
  4691. host_and_port += HOST;
  4692. host_and_port += ":";
  4693. host_and_port += std::to_string(PORT);
  4694. req.headers.emplace("Host", host_and_port.c_str());
  4695. req.headers.emplace("Content-Length", "0");
  4696. req.headers.emplace("Transfer-Encoding", "chunked");
  4697. req.body = body;
  4698. auto res = std::make_shared<Response>();
  4699. auto error = Error::Success;
  4700. ASSERT_TRUE(cli.send(req, *res, error));
  4701. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4702. }
  4703. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4704. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4705. }
  4706. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4707. expect_chunked_body_rejected(
  4708. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4709. }
  4710. TEST_F(ServerTest, GetStreamed2) {
  4711. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4712. ASSERT_TRUE(res);
  4713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4714. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4715. EXPECT_EQ(true, res->has_header("Content-Range"));
  4716. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4717. EXPECT_EQ(std::string("ab"), res->body);
  4718. }
  4719. TEST_F(ServerTest, GetStreamed) {
  4720. auto res = cli_.Get("/streamed");
  4721. ASSERT_TRUE(res);
  4722. EXPECT_EQ(StatusCode::OK_200, res->status);
  4723. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4724. EXPECT_EQ(std::string("aaabbb"), res->body);
  4725. }
  4726. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4727. auto res = cli_.Get("/streamed-without-length",
  4728. Headers{make_range_header({{0, -1}})});
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ(false, res->has_header("Content-Length"));
  4732. EXPECT_EQ(false, res->has_header("Content-Range"));
  4733. EXPECT_EQ(std::string("abcdefg"), res->body);
  4734. }
  4735. TEST_F(ServerTest, GetStreamedWithRange1) {
  4736. auto res =
  4737. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4738. ASSERT_TRUE(res);
  4739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4740. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4741. EXPECT_EQ(true, res->has_header("Content-Range"));
  4742. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4743. EXPECT_EQ(std::string("def"), res->body);
  4744. }
  4745. TEST_F(ServerTest, GetStreamedWithRange2) {
  4746. auto res =
  4747. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4750. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4751. EXPECT_EQ(true, res->has_header("Content-Range"));
  4752. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4753. EXPECT_EQ(std::string("bcdefg"), res->body);
  4754. }
  4755. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4756. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4759. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4760. EXPECT_EQ(true, res->has_header("Content-Range"));
  4761. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4762. EXPECT_EQ(std::string("efg"), res->body);
  4763. }
  4764. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4765. auto res =
  4766. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4769. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4770. EXPECT_EQ(false, res->has_header("Content-Range"));
  4771. EXPECT_EQ(0U, res->body.size());
  4772. }
  4773. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4774. auto res =
  4775. cli_.Get("/streamed-with-range",
  4776. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4777. "92233720368547758079223372036854775807"}});
  4778. ASSERT_TRUE(res);
  4779. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4780. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4781. EXPECT_EQ(false, res->has_header("Content-Range"));
  4782. EXPECT_EQ(0U, res->body.size());
  4783. }
  4784. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4785. auto res = cli_.Get(
  4786. "/with-range",
  4787. Headers{{"Range",
  4788. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4789. {"Accept-Encoding", ""}});
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4792. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4793. EXPECT_EQ(true, res->has_header("Content-Range"));
  4794. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4795. EXPECT_EQ(std::string("abcdefg"), res->body);
  4796. }
  4797. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4798. auto res = cli_.Get("/with-range", Headers{
  4799. {"Range", "bytes=0-"},
  4800. {"Accept-Encoding", ""},
  4801. });
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4804. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4805. EXPECT_EQ(true, res->has_header("Content-Range"));
  4806. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4807. EXPECT_EQ(std::string("abcdefg"), res->body);
  4808. }
  4809. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4810. auto res = cli_.Get("/streamed-with-range",
  4811. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4812. ASSERT_TRUE(res);
  4813. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4814. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4815. EXPECT_EQ(false, res->has_header("Content-Range"));
  4816. EXPECT_EQ(267U, res->body.size());
  4817. // Check that both range contents are present
  4818. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4819. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4820. // Check that Content-Range headers are present for both ranges
  4821. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4822. std::string::npos);
  4823. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4824. std::string::npos);
  4825. }
  4826. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4827. Ranges ranges;
  4828. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4829. ranges.emplace_back(0, -1);
  4830. }
  4831. auto res = cli_.Get("/streamed-with-range?error",
  4832. Headers{{make_range_header(ranges)}});
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4835. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4836. EXPECT_EQ(false, res->has_header("Content-Range"));
  4837. EXPECT_EQ(0U, res->body.size());
  4838. }
  4839. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4840. auto res = cli_.Get("/streamed-with-range",
  4841. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4842. ASSERT_TRUE(res);
  4843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4844. EXPECT_EQ(5U, res->body.size());
  4845. // Check that overlapping ranges are coalesced into a single range
  4846. EXPECT_EQ("bcdef", res->body);
  4847. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4848. // Should be single range, not multipart
  4849. EXPECT_TRUE(res->has_header("Content-Range"));
  4850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4851. }
  4852. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4853. auto res = cli_.Get("/streamed-with-range",
  4854. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4857. EXPECT_EQ(268U, res->body.size());
  4858. // Check that both range contents are present
  4859. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4860. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4861. // Check that Content-Range headers are present for both ranges
  4862. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4863. std::string::npos);
  4864. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4865. std::string::npos);
  4866. }
  4867. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4868. auto res = cli_.Get("/streamed-with-range",
  4869. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4870. ASSERT_TRUE(res);
  4871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4872. EXPECT_EQ(269U, res->body.size());
  4873. // Check that both duplicate range contents are present
  4874. size_t first_abc = res->body.find("abc\r\n");
  4875. EXPECT_TRUE(first_abc != std::string::npos);
  4876. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4877. EXPECT_TRUE(second_abc != std::string::npos);
  4878. // Check that Content-Range headers are present for both ranges
  4879. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4880. EXPECT_TRUE(first_range != std::string::npos);
  4881. size_t second_range =
  4882. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4883. EXPECT_TRUE(second_range != std::string::npos);
  4884. }
  4885. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4886. auto res =
  4887. cli_.Get("/streamed-with-range?error",
  4888. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4889. ASSERT_TRUE(res);
  4890. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4891. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4892. EXPECT_EQ(false, res->has_header("Content-Range"));
  4893. EXPECT_EQ(0U, res->body.size());
  4894. }
  4895. TEST_F(ServerTest, GetStreamedEndless) {
  4896. uint64_t offset = 0;
  4897. auto res = cli_.Get("/streamed-cancel",
  4898. [&](const char * /*data*/, uint64_t data_length) {
  4899. if (offset < 100) {
  4900. offset += data_length;
  4901. return true;
  4902. }
  4903. return false;
  4904. });
  4905. ASSERT_TRUE(!res);
  4906. EXPECT_EQ(Error::Canceled, res.error());
  4907. }
  4908. TEST_F(ServerTest, ClientStop) {
  4909. std::atomic_size_t count{4};
  4910. std::vector<std::thread> threads;
  4911. for (auto i = count.load(); i != 0; --i) {
  4912. threads.emplace_back([&]() {
  4913. auto res = cli_.Get("/streamed-cancel",
  4914. [&](const char *, uint64_t) { return true; });
  4915. --count;
  4916. ASSERT_TRUE(!res);
  4917. EXPECT_TRUE(res.error() == Error::Canceled ||
  4918. res.error() == Error::Read || res.error() == Error::Write);
  4919. });
  4920. }
  4921. std::this_thread::sleep_for(std::chrono::seconds(2));
  4922. while (count != 0) {
  4923. cli_.stop();
  4924. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4925. }
  4926. for (auto &t : threads) {
  4927. t.join();
  4928. }
  4929. }
  4930. TEST_F(ServerTest, GetWithRange1) {
  4931. auto res = cli_.Get("/with-range", Headers{
  4932. make_range_header({{3, 5}}),
  4933. {"Accept-Encoding", ""},
  4934. });
  4935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4936. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4937. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4938. EXPECT_EQ(true, res->has_header("Content-Range"));
  4939. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4940. EXPECT_EQ(std::string("def"), res->body);
  4941. }
  4942. TEST_F(ServerTest, GetWithRange2) {
  4943. auto res = cli_.Get("/with-range", Headers{
  4944. make_range_header({{1, -1}}),
  4945. {"Accept-Encoding", ""},
  4946. });
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4949. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4950. EXPECT_EQ(true, res->has_header("Content-Range"));
  4951. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4952. EXPECT_EQ(std::string("bcdefg"), res->body);
  4953. }
  4954. TEST_F(ServerTest, GetWithRange3) {
  4955. auto res = cli_.Get("/with-range", Headers{
  4956. make_range_header({{0, 0}}),
  4957. {"Accept-Encoding", ""},
  4958. });
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4961. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4962. EXPECT_EQ(true, res->has_header("Content-Range"));
  4963. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4964. EXPECT_EQ(std::string("a"), res->body);
  4965. }
  4966. TEST_F(ServerTest, GetWithRange4) {
  4967. auto res = cli_.Get("/with-range", Headers{
  4968. make_range_header({{-1, 2}}),
  4969. {"Accept-Encoding", ""},
  4970. });
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4973. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4974. EXPECT_EQ(true, res->has_header("Content-Range"));
  4975. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4976. EXPECT_EQ(std::string("fg"), res->body);
  4977. }
  4978. TEST_F(ServerTest, GetWithRange5) {
  4979. auto res = cli_.Get("/with-range", Headers{
  4980. make_range_header({{0, 5}}),
  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 0-5/7", res->get_header_value("Content-Range"));
  4988. EXPECT_EQ(std::string("abcdef"), res->body);
  4989. }
  4990. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4991. auto res =
  4992. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4995. }
  4996. TEST_F(ServerTest, GetWithRangeMultipart) {
  4997. auto res =
  4998. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5001. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5002. EXPECT_EQ(false, res->has_header("Content-Range"));
  5003. EXPECT_EQ(267U, res->body.size());
  5004. }
  5005. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5006. auto res = cli_.Get("/with-range",
  5007. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5010. }
  5011. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5012. auto res = cli_.Get("/with-range-customized-response",
  5013. Headers{{make_range_header({{1, 2}})}});
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5016. EXPECT_EQ(true, res->has_header("Content-Length"));
  5017. EXPECT_EQ(false, res->has_header("Content-Range"));
  5018. EXPECT_EQ(JSON_DATA, res->body);
  5019. }
  5020. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5021. auto res = cli_.Get("/with-range-customized-response",
  5022. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5025. EXPECT_EQ(true, res->has_header("Content-Length"));
  5026. EXPECT_EQ(false, res->has_header("Content-Range"));
  5027. EXPECT_EQ(JSON_DATA, res->body);
  5028. }
  5029. TEST_F(ServerTest, Issue1772) {
  5030. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5033. }
  5034. TEST_F(ServerTest, Issue609) {
  5035. auto res = cli_.Delete("/issue609");
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. EXPECT_EQ(std::string("ok"), res->body);
  5039. }
  5040. TEST_F(ServerTest, GetStreamedChunked) {
  5041. auto res = cli_.Get("/streamed-chunked");
  5042. ASSERT_TRUE(res);
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ(std::string("123456789"), res->body);
  5045. }
  5046. TEST_F(ServerTest, GetStreamedChunked2) {
  5047. auto res = cli_.Get("/streamed-chunked2");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ(std::string("123456789"), res->body);
  5051. }
  5052. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5053. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5054. ASSERT_TRUE(res);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. EXPECT_EQ(std::string("123456789"), res->body);
  5057. EXPECT_TRUE(res->has_header("Trailer"));
  5058. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5059. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5060. // Trailers are now stored separately from headers (security fix)
  5061. EXPECT_EQ(2U, res->trailers.size());
  5062. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5063. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5064. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5065. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5066. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5067. // Verify trailers are NOT in headers (security verification)
  5068. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5069. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5070. }
  5071. TEST_F(ServerTest, LargeChunkedPost) {
  5072. Request req;
  5073. req.method = "POST";
  5074. req.path = "/large-chunked";
  5075. std::string host_and_port;
  5076. host_and_port += HOST;
  5077. host_and_port += ":";
  5078. host_and_port += std::to_string(PORT);
  5079. req.headers.emplace("Host", host_and_port.c_str());
  5080. req.headers.emplace("Accept", "*/*");
  5081. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5082. req.headers.emplace("Content-Type", "text/plain");
  5083. req.headers.emplace("Content-Length", "0");
  5084. req.headers.emplace("Transfer-Encoding", "chunked");
  5085. std::string long_string(30 * 1024u, 'a');
  5086. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5087. // Attempt to make a large enough post to exceed OS buffers, to test that
  5088. // the server handles short reads if the full chunk data isn't available.
  5089. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5090. auto res = std::make_shared<Response>();
  5091. auto error = Error::Success;
  5092. auto ret = cli_.send(req, *res, error);
  5093. ASSERT_TRUE(ret);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. }
  5096. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5097. auto res = cli_.Get("/remote_addr");
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5101. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5102. }
  5103. TEST_F(ServerTest, GetMethodLocalAddr) {
  5104. auto res = cli_.Get("/local_addr");
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5108. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5109. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5110. }
  5111. TEST_F(ServerTest, HTTPResponseSplitting) {
  5112. auto res = cli_.Get("/http_response_splitting");
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ(StatusCode::OK_200, res->status);
  5115. }
  5116. TEST_F(ServerTest, SlowRequest) {
  5117. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5118. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5119. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5120. }
  5121. #if 0
  5122. TEST_F(ServerTest, SlowPost) {
  5123. char buffer[64 * 1024];
  5124. memset(buffer, 0x42, sizeof(buffer));
  5125. auto res = cli_.Post(
  5126. "/slowpost", 64 * 1024 * 1024,
  5127. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5128. auto ret = sink.write(buffer, sizeof(buffer));
  5129. EXPECT_TRUE(ret);
  5130. return true;
  5131. },
  5132. "text/plain");
  5133. ASSERT_TRUE(res);
  5134. EXPECT_EQ(StatusCode::OK_200, res->status);
  5135. }
  5136. TEST_F(ServerTest, SlowPostFail) {
  5137. char buffer[64 * 1024];
  5138. memset(buffer, 0x42, sizeof(buffer));
  5139. cli_.set_write_timeout(std::chrono::seconds(0));
  5140. auto res = cli_.Post(
  5141. "/slowpost", 64 * 1024 * 1024,
  5142. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5143. sink.write(buffer, sizeof(buffer));
  5144. return true;
  5145. },
  5146. "text/plain");
  5147. ASSERT_TRUE(!res);
  5148. EXPECT_EQ(Error::Write, res.error());
  5149. }
  5150. #endif
  5151. TEST_F(ServerTest, Put) {
  5152. auto res = cli_.Put("/put", "PUT", "text/plain");
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("PUT", res->body);
  5156. }
  5157. TEST_F(ServerTest, PutWithContentProvider) {
  5158. auto res = cli_.Put(
  5159. "/put", 3,
  5160. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5161. sink.os << "PUT";
  5162. return true;
  5163. },
  5164. "text/plain");
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. EXPECT_EQ("PUT", res->body);
  5168. }
  5169. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5170. auto res = cli_.Post(
  5171. "/post", 42,
  5172. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5173. return false;
  5174. },
  5175. "text/plain");
  5176. ASSERT_TRUE(!res);
  5177. EXPECT_EQ(Error::Canceled, res.error());
  5178. }
  5179. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5180. auto res = cli_.Put(
  5181. "/put",
  5182. [](size_t /*offset*/, DataSink &sink) {
  5183. sink.os << "PUT";
  5184. sink.done();
  5185. return true;
  5186. },
  5187. "text/plain");
  5188. ASSERT_TRUE(res);
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. EXPECT_EQ("PUT", res->body);
  5191. }
  5192. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5193. auto res = cli_.Post(
  5194. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5195. "text/plain");
  5196. ASSERT_TRUE(!res);
  5197. EXPECT_EQ(Error::Canceled, res.error());
  5198. }
  5199. TEST_F(ServerTest, PostLoopBack) {
  5200. std::string body;
  5201. auto res = cli_.Post(
  5202. "/post-loopback", 9,
  5203. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5204. EXPECT_EQ(9u, length);
  5205. sink.write("123", 3);
  5206. sink.write("456", 3);
  5207. sink.write("789", 3);
  5208. return true;
  5209. },
  5210. "text/plain",
  5211. [&body](const char *data, size_t data_length) {
  5212. body.append(data, data_length);
  5213. return true;
  5214. });
  5215. ASSERT_TRUE(res);
  5216. EXPECT_EQ(StatusCode::OK_200, res->status);
  5217. EXPECT_EQ("123456789", body);
  5218. }
  5219. TEST_F(ServerTest, PutLoopBack) {
  5220. std::string body;
  5221. auto res = cli_.Put(
  5222. "/put-loopback", 9,
  5223. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5224. EXPECT_EQ(9u, length);
  5225. sink.write("123", 3);
  5226. sink.write("456", 3);
  5227. sink.write("789", 3);
  5228. return true;
  5229. },
  5230. "text/plain",
  5231. [&body](const char *data, size_t data_length) {
  5232. body.append(data, data_length);
  5233. return true;
  5234. });
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::OK_200, res->status);
  5237. EXPECT_EQ("123456789", body);
  5238. }
  5239. TEST_F(ServerTest, PatchLoopBack) {
  5240. std::string body;
  5241. auto res = cli_.Patch(
  5242. "/patch-loopback", 9,
  5243. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5244. EXPECT_EQ(9u, length);
  5245. sink.write("123", 3);
  5246. sink.write("456", 3);
  5247. sink.write("789", 3);
  5248. return true;
  5249. },
  5250. "text/plain",
  5251. [&body](const char *data, size_t data_length) {
  5252. body.append(data, data_length);
  5253. return true;
  5254. });
  5255. ASSERT_TRUE(res);
  5256. EXPECT_EQ(StatusCode::OK_200, res->status);
  5257. EXPECT_EQ("123456789", body);
  5258. }
  5259. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5260. std::string body;
  5261. auto res = cli_.Post(
  5262. "/post-loopback",
  5263. [](size_t /*offset*/, DataSink &sink) {
  5264. sink.write("123", 3);
  5265. sink.write("456", 3);
  5266. sink.write("789", 3);
  5267. sink.done();
  5268. return true;
  5269. },
  5270. "text/plain",
  5271. [&body](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("123456789", body);
  5278. }
  5279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5280. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5281. cli_.set_compress(true);
  5282. auto res = cli_.Put(
  5283. "/put", 3,
  5284. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5285. sink.os << "PUT";
  5286. return true;
  5287. },
  5288. "text/plain");
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("PUT", res->body);
  5292. }
  5293. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5294. cli_.set_compress(true);
  5295. auto res = cli_.Post(
  5296. "/post", 42,
  5297. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5298. return false;
  5299. },
  5300. "text/plain");
  5301. ASSERT_TRUE(!res);
  5302. EXPECT_EQ(Error::Canceled, res.error());
  5303. }
  5304. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5305. cli_.set_compress(true);
  5306. auto res = cli_.Put(
  5307. "/put",
  5308. [](size_t /*offset*/, DataSink &sink) {
  5309. sink.os << "PUT";
  5310. sink.done();
  5311. return true;
  5312. },
  5313. "text/plain");
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. EXPECT_EQ("PUT", res->body);
  5317. }
  5318. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5319. cli_.set_compress(true);
  5320. auto res = cli_.Post(
  5321. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5322. "text/plain");
  5323. ASSERT_TRUE(!res);
  5324. EXPECT_EQ(Error::Canceled, res.error());
  5325. }
  5326. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5327. cli_.set_compress(true);
  5328. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5329. ASSERT_TRUE(res);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. EXPECT_EQ(LARGE_DATA, res->body);
  5332. }
  5333. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5334. #ifdef CPPHTTPLIB_SSL_ENABLED
  5335. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5336. Client cli(s.c_str());
  5337. cli.enable_server_certificate_verification(false);
  5338. #else
  5339. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5340. Client cli(s.c_str());
  5341. #endif
  5342. cli.set_compress(true);
  5343. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ(LARGE_DATA, res->body);
  5347. // The compressed size should be less than a 10th of the original. May vary
  5348. // depending on the zlib library.
  5349. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5350. static_cast<uint64_t>(10 * 1024 * 1024));
  5351. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5352. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5353. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5354. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5355. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5356. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5357. #endif
  5358. }
  5359. TEST_F(ServerTest, PutContentWithDeflate) {
  5360. cli_.set_compress(false);
  5361. Headers headers;
  5362. headers.emplace("Content-Encoding", "deflate");
  5363. // PUT in deflate format:
  5364. auto res = cli_.Put("/put", headers,
  5365. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5371. Headers headers;
  5372. headers.emplace("Accept-Encoding", "gzip, deflate");
  5373. auto res = cli_.Get("/streamed-chunked", headers);
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ(std::string("123456789"), res->body);
  5377. }
  5378. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "gzip, deflate");
  5381. auto res = cli_.Get("/streamed-chunked2", headers);
  5382. ASSERT_TRUE(res);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. EXPECT_EQ(std::string("123456789"), res->body);
  5385. }
  5386. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5387. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5388. ASSERT_TRUE(res);
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST(GzipDecompressor, ChunkedDecompression) {
  5392. std::string data;
  5393. for (size_t i = 0; i < 32 * 1024; ++i) {
  5394. data.push_back(static_cast<char>('a' + i % 26));
  5395. }
  5396. std::string compressed_data;
  5397. {
  5398. httplib::detail::gzip_compressor compressor;
  5399. bool result = compressor.compress(
  5400. data.data(), data.size(),
  5401. /*last=*/true,
  5402. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5403. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5404. compressed_data_size);
  5405. return true;
  5406. });
  5407. ASSERT_TRUE(result);
  5408. }
  5409. std::string decompressed_data;
  5410. {
  5411. httplib::detail::gzip_decompressor decompressor;
  5412. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5413. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5414. size_t chunk_size = 130;
  5415. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5416. chunk_begin += chunk_size) {
  5417. size_t current_chunk_size =
  5418. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5419. bool result = decompressor.decompress(
  5420. compressed_data.data() + chunk_begin, current_chunk_size,
  5421. [&](const char *decompressed_data_chunk,
  5422. size_t decompressed_data_chunk_size) {
  5423. decompressed_data.insert(decompressed_data.size(),
  5424. decompressed_data_chunk,
  5425. decompressed_data_chunk_size);
  5426. return true;
  5427. });
  5428. ASSERT_TRUE(result);
  5429. }
  5430. }
  5431. ASSERT_EQ(data, decompressed_data);
  5432. }
  5433. TEST(GzipDecompressor, DeflateDecompression) {
  5434. std::string original_text = "Raw deflate without gzip";
  5435. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5436. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5437. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5438. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5439. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5440. std::string decompressed_data;
  5441. {
  5442. httplib::detail::gzip_decompressor decompressor;
  5443. bool result = decompressor.decompress(
  5444. compressed_data.data(), compressed_data.size(),
  5445. [&](const char *decompressed_data_chunk,
  5446. size_t decompressed_data_chunk_size) {
  5447. decompressed_data.insert(decompressed_data.size(),
  5448. decompressed_data_chunk,
  5449. decompressed_data_chunk_size);
  5450. return true;
  5451. });
  5452. ASSERT_TRUE(result);
  5453. }
  5454. ASSERT_EQ(original_text, decompressed_data);
  5455. }
  5456. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5457. std::string original_text = "Raw deflate without gzip";
  5458. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5459. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5460. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5461. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5462. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5463. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5464. std::string decompressed_data;
  5465. {
  5466. httplib::detail::gzip_decompressor decompressor;
  5467. bool result = decompressor.decompress(
  5468. compressed_data.data(), compressed_data.size(),
  5469. [&](const char *decompressed_data_chunk,
  5470. size_t decompressed_data_chunk_size) {
  5471. decompressed_data.insert(decompressed_data.size(),
  5472. decompressed_data_chunk,
  5473. decompressed_data_chunk_size);
  5474. return true;
  5475. });
  5476. ASSERT_TRUE(result);
  5477. }
  5478. ASSERT_EQ(original_text, decompressed_data);
  5479. }
  5480. #endif
  5481. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5482. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5483. Headers headers;
  5484. headers.emplace("Accept-Encoding", "br");
  5485. auto res = cli_.Get("/streamed-chunked", headers);
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ(std::string("123456789"), res->body);
  5489. }
  5490. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5491. Headers headers;
  5492. headers.emplace("Accept-Encoding", "br");
  5493. auto res = cli_.Get("/streamed-chunked2", headers);
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ(std::string("123456789"), res->body);
  5497. }
  5498. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5499. cli_.set_compress(true);
  5500. auto res = cli_.Put(
  5501. "/put", 3,
  5502. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5503. sink.os << "PUT";
  5504. return true;
  5505. },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("PUT", res->body);
  5510. }
  5511. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5512. cli_.set_compress(true);
  5513. auto res = cli_.Put(
  5514. "/put",
  5515. [](size_t /*offset*/, DataSink &sink) {
  5516. sink.os << "PUT";
  5517. sink.done();
  5518. return true;
  5519. },
  5520. "text/plain");
  5521. ASSERT_TRUE(res);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. EXPECT_EQ("PUT", res->body);
  5524. }
  5525. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5526. cli_.set_compress(true);
  5527. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. EXPECT_EQ(LARGE_DATA, res->body);
  5531. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5532. }
  5533. #endif
  5534. TEST_F(ServerTest, Patch) {
  5535. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5536. ASSERT_TRUE(res);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. EXPECT_EQ("PATCH", res->body);
  5539. }
  5540. TEST_F(ServerTest, Delete) {
  5541. auto res = cli_.Delete("/delete");
  5542. ASSERT_TRUE(res);
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. EXPECT_EQ("DELETE", res->body);
  5545. }
  5546. TEST_F(ServerTest, DeleteContentReceiver) {
  5547. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("content", res->body);
  5551. }
  5552. TEST_F(ServerTest, Options) {
  5553. auto res = cli_.Options("*");
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5557. EXPECT_TRUE(res->body.empty());
  5558. }
  5559. TEST_F(ServerTest, URL) {
  5560. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5561. ASSERT_TRUE(res);
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. }
  5564. TEST_F(ServerTest, ArrayParam) {
  5565. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5566. ASSERT_TRUE(res);
  5567. EXPECT_EQ(StatusCode::OK_200, res->status);
  5568. }
  5569. TEST_F(ServerTest, ArrayParamValues) {
  5570. auto res =
  5571. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5572. ASSERT_TRUE(res);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, NoMultipleHeaders) {
  5576. Headers headers = {{"Content-Length", "5"}};
  5577. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5578. "text/plain");
  5579. ASSERT_TRUE(res);
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. }
  5582. TEST_F(ServerTest, PostContentReceiver) {
  5583. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5584. ASSERT_TRUE(res);
  5585. ASSERT_EQ(StatusCode::OK_200, res->status);
  5586. ASSERT_EQ("content", res->body);
  5587. }
  5588. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5589. UploadFormDataItems items = {
  5590. {"text1", "text default", "", ""},
  5591. {"text2", "aωb", "", ""},
  5592. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5593. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5594. {"file3", "", "", "application/octet-stream"},
  5595. };
  5596. auto res = cli_.Post("/content_receiver", items);
  5597. ASSERT_TRUE(res);
  5598. EXPECT_EQ(StatusCode::OK_200, res->status);
  5599. }
  5600. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5601. UploadFormDataItems items = {
  5602. {"text1", "text default", "", ""},
  5603. {"text2", "aωb", "", ""},
  5604. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5605. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5606. {"file3", "", "", "application/octet-stream"},
  5607. };
  5608. auto boundary = std::string("+++++");
  5609. std::string body;
  5610. for (const auto &item : items) {
  5611. body += "--" + boundary + "\r\n";
  5612. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5613. if (!item.filename.empty()) {
  5614. body += "; filename=\"" + item.filename + "\"";
  5615. }
  5616. body += "\r\n";
  5617. if (!item.content_type.empty()) {
  5618. body += "Content-Type: " + item.content_type + "\r\n";
  5619. }
  5620. body += "\r\n";
  5621. body += item.content + "\r\n";
  5622. }
  5623. body += "--" + boundary + "--\r\n";
  5624. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5625. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST(MultipartFormDataTest, FieldEscaping) {
  5630. Server svr;
  5631. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5632. const ContentReader &content_reader) {
  5633. ASSERT_TRUE(req.is_multipart_form_data());
  5634. std::vector<FormData> received;
  5635. content_reader(
  5636. [&](const FormData &file) {
  5637. received.push_back(file);
  5638. return true;
  5639. },
  5640. [&](const char *data, size_t data_length) {
  5641. received.back().content.append(data, data_length);
  5642. return true;
  5643. });
  5644. // '"', CR and LF in names and filenames are escaped following the
  5645. // WHATWG HTML standard, so each part still parses as a single part
  5646. // with no injected headers. Content types get CR/LF escaped too,
  5647. // while '"' (legal there, e.g. quoted charset) is preserved.
  5648. ASSERT_EQ(4U, received.size());
  5649. EXPECT_EQ("na%22me", received[0].name);
  5650. EXPECT_EQ("quoted name", received[0].content);
  5651. EXPECT_EQ("file", received[1].name);
  5652. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5653. received[1].filename);
  5654. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5655. EXPECT_EQ("injected", received[1].content);
  5656. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5657. EXPECT_EQ("my%22file.txt", received[2].filename);
  5658. EXPECT_EQ("cr lf name", received[2].content);
  5659. EXPECT_EQ("typed", received[3].name);
  5660. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5661. received[3].content_type);
  5662. EXPECT_EQ("typed content", received[3].content);
  5663. });
  5664. auto port = svr.bind_to_any_port("localhost");
  5665. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5666. auto se = detail::scope_exit([&] {
  5667. svr.stop();
  5668. t.join();
  5669. ASSERT_FALSE(svr.is_running());
  5670. });
  5671. svr.wait_until_ready();
  5672. Client cli("localhost", port);
  5673. UploadFormDataItems items = {
  5674. {"na\"me", "quoted name", "", ""},
  5675. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5676. "application/octet-stream"},
  5677. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5678. {"typed", "typed content", "",
  5679. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5680. };
  5681. auto res = cli.Post("/post", items);
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5686. const UploadFormDataItems items = {
  5687. {"name1", "Content 1", "", ""},
  5688. {"name2", "Content 2", "file2.txt", "text/plain"},
  5689. };
  5690. Server svr;
  5691. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5692. const ContentReader &content_reader) {
  5693. ASSERT_TRUE(req.is_multipart_form_data());
  5694. std::vector<FormData> received;
  5695. content_reader(
  5696. [&](const FormData &file) {
  5697. received.push_back(file);
  5698. return true;
  5699. },
  5700. [&](const char *data, size_t data_length) {
  5701. received.back().content.append(data, data_length);
  5702. return true;
  5703. });
  5704. ASSERT_EQ(2U, received.size());
  5705. EXPECT_EQ("name1", received[0].name);
  5706. EXPECT_EQ("Content 1", received[0].content);
  5707. EXPECT_EQ("name2", received[1].name);
  5708. EXPECT_EQ("Content 2", received[1].content);
  5709. EXPECT_EQ("file2.txt", received[1].filename);
  5710. EXPECT_EQ("text/plain", received[1].content_type);
  5711. });
  5712. auto port = svr.bind_to_any_port("localhost");
  5713. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5714. auto se = detail::scope_exit([&] {
  5715. svr.stop();
  5716. t.join();
  5717. ASSERT_FALSE(svr.is_running());
  5718. });
  5719. svr.wait_until_ready();
  5720. Client cli("localhost", port);
  5721. // Whole-body serialization with a generated boundary
  5722. {
  5723. MultipartFormDataWriter writer;
  5724. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5725. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5726. writer.content_type());
  5727. auto body = writer.serialize(items);
  5728. EXPECT_EQ(body.size(), writer.content_length(items));
  5729. auto res = cli.Post("/post", body, writer.content_type());
  5730. ASSERT_TRUE(res);
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. }
  5733. // Per-part framing with a custom boundary via a content provider
  5734. {
  5735. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5736. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5737. MultipartFormDataWriter writer("custom-boundary_123");
  5738. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5739. std::string body;
  5740. for (const auto &item : items) {
  5741. body += writer.item_begin(item);
  5742. body += item.content;
  5743. body += MultipartFormDataWriter::item_end();
  5744. }
  5745. body += writer.finish();
  5746. EXPECT_EQ(body.size(), writer.content_length(items));
  5747. auto res = cli.Post(
  5748. "/post", body.size(),
  5749. [&](size_t offset, size_t length, DataSink &sink) {
  5750. sink.write(body.data() + offset, length);
  5751. return true;
  5752. },
  5753. writer.content_type());
  5754. ASSERT_TRUE(res);
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. }
  5757. }
  5758. TEST_F(ServerTest, PostContentReceiverGzip) {
  5759. cli_.set_compress(true);
  5760. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5761. ASSERT_TRUE(res);
  5762. ASSERT_EQ(StatusCode::OK_200, res->status);
  5763. ASSERT_EQ("content", res->body);
  5764. }
  5765. TEST_F(ServerTest, PutContentReceiver) {
  5766. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5767. ASSERT_TRUE(res);
  5768. ASSERT_EQ(StatusCode::OK_200, res->status);
  5769. ASSERT_EQ("content", res->body);
  5770. }
  5771. TEST_F(ServerTest, PatchContentReceiver) {
  5772. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5773. ASSERT_TRUE(res);
  5774. ASSERT_EQ(StatusCode::OK_200, res->status);
  5775. ASSERT_EQ("content", res->body);
  5776. }
  5777. template <typename ClientType>
  5778. void TestWithHeadersAndContentReceiver(
  5779. ClientType &cli,
  5780. std::function<Result(ClientType &, const std::string &, const Headers &,
  5781. const std::string &, const std::string &,
  5782. ContentReceiver, DownloadProgress)>
  5783. request_func) {
  5784. Headers headers;
  5785. headers.emplace("X-Custom-Header", "test-value");
  5786. std::string received_body;
  5787. auto res = request_func(
  5788. cli, "/content_receiver", headers, "content", "application/json",
  5789. [&](const char *data, size_t data_length) {
  5790. received_body.append(data, data_length);
  5791. return true;
  5792. },
  5793. nullptr);
  5794. ASSERT_TRUE(res);
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ("content", received_body);
  5797. }
  5798. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5799. #ifdef CPPHTTPLIB_SSL_ENABLED
  5800. using ClientT = SSLClient;
  5801. #else
  5802. using ClientT = Client;
  5803. #endif
  5804. TestWithHeadersAndContentReceiver<ClientT>(
  5805. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5806. const std::string &body, const std::string &content_type,
  5807. ContentReceiver receiver, DownloadProgress progress) {
  5808. return cli.Post(path, headers, body, content_type, receiver, progress);
  5809. });
  5810. }
  5811. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5812. #ifdef CPPHTTPLIB_SSL_ENABLED
  5813. using ClientT = SSLClient;
  5814. #else
  5815. using ClientT = Client;
  5816. #endif
  5817. TestWithHeadersAndContentReceiver<ClientT>(
  5818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5819. const std::string &body, const std::string &content_type,
  5820. ContentReceiver receiver, DownloadProgress progress) {
  5821. return cli.Put(path, headers, body, content_type, receiver, progress);
  5822. });
  5823. }
  5824. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5825. #ifdef CPPHTTPLIB_SSL_ENABLED
  5826. using ClientT = SSLClient;
  5827. #else
  5828. using ClientT = Client;
  5829. #endif
  5830. TestWithHeadersAndContentReceiver<ClientT>(
  5831. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5832. const std::string &body, const std::string &content_type,
  5833. ContentReceiver receiver, DownloadProgress progress) {
  5834. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5835. });
  5836. }
  5837. template <typename ClientType>
  5838. void TestWithHeadersAndContentReceiverWithProgress(
  5839. ClientType &cli,
  5840. std::function<Result(ClientType &, const std::string &, const Headers &,
  5841. const std::string &, const std::string &,
  5842. ContentReceiver, DownloadProgress)>
  5843. request_func) {
  5844. Headers headers;
  5845. headers.emplace("X-Test-Header", "progress-test");
  5846. std::string received_body;
  5847. auto progress_called = false;
  5848. auto res = request_func(
  5849. cli, "/content_receiver", headers, "content", "text/plain",
  5850. [&](const char *data, size_t data_length) {
  5851. received_body.append(data, data_length);
  5852. return true;
  5853. },
  5854. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5855. progress_called = true;
  5856. return true;
  5857. });
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("content", received_body);
  5861. EXPECT_TRUE(progress_called);
  5862. }
  5863. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5864. #ifdef CPPHTTPLIB_SSL_ENABLED
  5865. using ClientT = SSLClient;
  5866. #else
  5867. using ClientT = Client;
  5868. #endif
  5869. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5870. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5871. const std::string &body, const std::string &content_type,
  5872. ContentReceiver receiver, DownloadProgress progress) {
  5873. return cli.Post(path, headers, body, content_type, receiver, progress);
  5874. });
  5875. }
  5876. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5877. #ifdef CPPHTTPLIB_SSL_ENABLED
  5878. using ClientT = SSLClient;
  5879. #else
  5880. using ClientT = Client;
  5881. #endif
  5882. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5883. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5884. const std::string &body, const std::string &content_type,
  5885. ContentReceiver receiver, DownloadProgress progress) {
  5886. return cli.Put(path, headers, body, content_type, receiver, progress);
  5887. });
  5888. }
  5889. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5890. #ifdef CPPHTTPLIB_SSL_ENABLED
  5891. using ClientT = SSLClient;
  5892. #else
  5893. using ClientT = Client;
  5894. #endif
  5895. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5896. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5897. const std::string &body, const std::string &content_type,
  5898. ContentReceiver receiver, DownloadProgress progress) {
  5899. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5900. });
  5901. }
  5902. template <typename ClientType>
  5903. void TestWithHeadersAndContentReceiverError(
  5904. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5905. const Headers &, const std::string &,
  5906. const std::string &, ContentReceiver)>
  5907. request_func) {
  5908. Headers headers;
  5909. headers.emplace("X-Error-Test", "true");
  5910. std::string received_body;
  5911. auto receiver_failed = false;
  5912. auto res =
  5913. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5914. [&](const char *data, size_t data_length) {
  5915. received_body.append(data, data_length);
  5916. receiver_failed = true;
  5917. return false;
  5918. });
  5919. ASSERT_FALSE(res);
  5920. EXPECT_TRUE(receiver_failed);
  5921. }
  5922. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5923. #ifdef CPPHTTPLIB_SSL_ENABLED
  5924. using ClientT = SSLClient;
  5925. #else
  5926. using ClientT = Client;
  5927. #endif
  5928. TestWithHeadersAndContentReceiverError<ClientT>(
  5929. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5930. const std::string &body, const std::string &content_type,
  5931. ContentReceiver receiver) {
  5932. return cli.Post(path, headers, body, content_type, receiver);
  5933. });
  5934. }
  5935. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5936. #ifdef CPPHTTPLIB_SSL_ENABLED
  5937. using ClientT = SSLClient;
  5938. #else
  5939. using ClientT = Client;
  5940. #endif
  5941. TestWithHeadersAndContentReceiverError<ClientT>(
  5942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5943. const std::string &body, const std::string &content_type,
  5944. ContentReceiver receiver) {
  5945. return cli.Put(path, headers, body, content_type, receiver);
  5946. });
  5947. }
  5948. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5949. #ifdef CPPHTTPLIB_SSL_ENABLED
  5950. using ClientT = SSLClient;
  5951. #else
  5952. using ClientT = Client;
  5953. #endif
  5954. TestWithHeadersAndContentReceiverError<ClientT>(
  5955. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5956. const std::string &body, const std::string &content_type,
  5957. ContentReceiver receiver) {
  5958. return cli.Patch(path, headers, body, content_type, receiver);
  5959. });
  5960. }
  5961. TEST_F(ServerTest, PostQueryStringAndBody) {
  5962. auto res =
  5963. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5964. ASSERT_TRUE(res);
  5965. ASSERT_EQ(StatusCode::OK_200, res->status);
  5966. }
  5967. TEST_F(ServerTest, HTTP2Magic) {
  5968. Request req;
  5969. req.method = "PRI";
  5970. req.path = "*";
  5971. req.body = "SM";
  5972. auto res = std::make_shared<Response>();
  5973. auto error = Error::Success;
  5974. auto ret = cli_.send(req, *res, error);
  5975. ASSERT_TRUE(ret);
  5976. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5977. }
  5978. TEST_F(ServerTest, KeepAlive) {
  5979. auto res = cli_.Get("/hi");
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5983. EXPECT_EQ("Hello World!", res->body);
  5984. res = cli_.Get("/hi");
  5985. ASSERT_TRUE(res);
  5986. EXPECT_EQ(StatusCode::OK_200, res->status);
  5987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5988. EXPECT_EQ("Hello World!", res->body);
  5989. res = cli_.Get("/hi");
  5990. ASSERT_TRUE(res);
  5991. EXPECT_EQ(StatusCode::OK_200, res->status);
  5992. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5993. EXPECT_EQ("Hello World!", res->body);
  5994. res = cli_.Get("/not-exist");
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5997. res = cli_.Post("/empty", "", "text/plain");
  5998. ASSERT_TRUE(res);
  5999. EXPECT_EQ(StatusCode::OK_200, res->status);
  6000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6001. EXPECT_EQ("empty", res->body);
  6002. EXPECT_EQ("close", res->get_header_value("Connection"));
  6003. res = cli_.Post(
  6004. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6005. "text/plain");
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6009. EXPECT_EQ("empty", res->body);
  6010. cli_.set_keep_alive(false);
  6011. res = cli_.Get("/last-request");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. EXPECT_EQ("close", res->get_header_value("Connection"));
  6015. }
  6016. TEST_F(ServerTest, TooManyRedirect) {
  6017. cli_.set_follow_location(true);
  6018. auto res = cli_.Get("/redirect/0");
  6019. ASSERT_TRUE(!res);
  6020. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6021. }
  6022. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6023. Request req;
  6024. req.method = "FOOBAR";
  6025. req.path = "/hi";
  6026. cli_.set_keep_alive(true);
  6027. auto res = cli_.send(req);
  6028. ASSERT_TRUE(res);
  6029. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6030. EXPECT_EQ("close", res->get_header_value("Connection"));
  6031. EXPECT_FALSE(cli_.is_socket_open());
  6032. }
  6033. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6035. TEST_F(ServerTest, Gzip) {
  6036. Headers headers;
  6037. headers.emplace("Accept-Encoding", "gzip, deflate");
  6038. auto res = cli_.Get("/compress", headers);
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6042. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6044. "7890123456789012345678901234567890",
  6045. res->body);
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. }
  6048. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6049. Headers headers;
  6050. headers.emplace("Accept-Encoding", "gzip, deflate");
  6051. auto res = cli_.Get("/compress-with-charset", headers);
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6054. EXPECT_EQ("application/json; charset=utf-8",
  6055. res->get_header_value("Content-Type"));
  6056. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6057. "7890123456789012345678901234567890",
  6058. res->body);
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. }
  6061. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6062. Headers headers;
  6063. headers.emplace("Accept-Encoding", "");
  6064. auto res = cli_.Get("/compress", headers);
  6065. ASSERT_TRUE(res);
  6066. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6067. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6068. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6069. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6070. "7890123456789012345678901234567890",
  6071. res->body);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. }
  6074. TEST_F(ServerTest, GzipWithContentReceiver) {
  6075. Headers headers;
  6076. headers.emplace("Accept-Encoding", "gzip, deflate");
  6077. std::string body;
  6078. auto res = cli_.Get("/compress", headers,
  6079. [&](const char *data, uint64_t data_length) {
  6080. EXPECT_EQ(100U, data_length);
  6081. body.append(data, data_length);
  6082. return true;
  6083. });
  6084. ASSERT_TRUE(res);
  6085. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6089. "7890123456789012345678901234567890",
  6090. body);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. }
  6093. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6094. Headers headers;
  6095. headers.emplace("Accept-Encoding", "gzip, deflate");
  6096. cli_.set_decompress(false);
  6097. auto res = cli_.Get("/compress", headers);
  6098. ASSERT_TRUE(res);
  6099. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6101. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6102. EXPECT_EQ(33U, res->body.size());
  6103. EXPECT_EQ(StatusCode::OK_200, res->status);
  6104. }
  6105. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6106. Headers headers;
  6107. headers.emplace("Accept-Encoding", "");
  6108. std::string body;
  6109. auto res = cli_.Get("/compress", headers,
  6110. [&](const char *data, uint64_t data_length) {
  6111. EXPECT_EQ(100U, data_length);
  6112. body.append(data, data_length);
  6113. return true;
  6114. });
  6115. ASSERT_TRUE(res);
  6116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6120. "7890123456789012345678901234567890",
  6121. body);
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. }
  6124. TEST_F(ServerTest, NoGzip) {
  6125. Headers headers;
  6126. headers.emplace("Accept-Encoding", "gzip, deflate");
  6127. auto res = cli_.Get("/nocompress", headers);
  6128. ASSERT_TRUE(res);
  6129. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6130. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6133. "7890123456789012345678901234567890",
  6134. res->body);
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. }
  6137. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "gzip, deflate");
  6140. std::string body;
  6141. auto res = cli_.Get("/nocompress", headers,
  6142. [&](const char *data, uint64_t data_length) {
  6143. EXPECT_EQ(100U, data_length);
  6144. body.append(data, data_length);
  6145. return true;
  6146. });
  6147. ASSERT_TRUE(res);
  6148. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6149. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6152. "7890123456789012345678901234567890",
  6153. body);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. }
  6156. TEST_F(ServerTest, MultipartFormDataGzip) {
  6157. UploadFormDataItems items = {
  6158. {"key1", "test", "", ""},
  6159. {"key2", "--abcdefg123", "", ""},
  6160. };
  6161. cli_.set_compress(true);
  6162. auto res = cli_.Post("/compress-multipart", items);
  6163. ASSERT_TRUE(res);
  6164. EXPECT_EQ(StatusCode::OK_200, res->status);
  6165. }
  6166. #endif
  6167. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6168. TEST_F(ServerTest, Brotli) {
  6169. Headers headers;
  6170. headers.emplace("Accept-Encoding", "br");
  6171. auto res = cli_.Get("/compress", headers);
  6172. ASSERT_TRUE(res);
  6173. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6175. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6177. "7890123456789012345678901234567890",
  6178. res->body);
  6179. EXPECT_EQ(StatusCode::OK_200, res->status);
  6180. }
  6181. #endif
  6182. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6183. TEST_F(ServerTest, Zstd) {
  6184. Headers headers;
  6185. headers.emplace("Accept-Encoding", "zstd");
  6186. auto res = cli_.Get("/compress", headers);
  6187. ASSERT_TRUE(res);
  6188. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6190. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6192. "7890123456789012345678901234567890",
  6193. res->body);
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. }
  6196. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6197. Headers headers;
  6198. headers.emplace("Accept-Encoding", "");
  6199. auto res = cli_.Get("/compress", headers);
  6200. ASSERT_TRUE(res);
  6201. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6203. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6204. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6205. "7890123456789012345678901234567890",
  6206. res->body);
  6207. EXPECT_EQ(StatusCode::OK_200, res->status);
  6208. }
  6209. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6210. Headers headers;
  6211. headers.emplace("Accept-Encoding", "zstd");
  6212. std::string body;
  6213. auto res = cli_.Get("/compress", headers,
  6214. [&](const char *data, uint64_t data_length) {
  6215. EXPECT_EQ(100U, data_length);
  6216. body.append(data, data_length);
  6217. return true;
  6218. });
  6219. ASSERT_TRUE(res);
  6220. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6222. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6224. "7890123456789012345678901234567890",
  6225. body);
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "zstd");
  6231. cli_.set_decompress(false);
  6232. auto res = cli_.Get("/compress", headers);
  6233. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6234. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6235. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6236. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6237. ASSERT_TRUE(res);
  6238. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6240. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. ASSERT_EQ(26U, res->body.size());
  6243. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6244. 0);
  6245. }
  6246. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6247. Headers headers;
  6248. headers.emplace("Accept-Encoding", "");
  6249. std::string body;
  6250. auto res = cli_.Get("/compress", headers,
  6251. [&](const char *data, uint64_t data_length) {
  6252. EXPECT_EQ(100U, data_length);
  6253. body.append(data, data_length);
  6254. return true;
  6255. });
  6256. ASSERT_TRUE(res);
  6257. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6258. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6259. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6260. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6261. "7890123456789012345678901234567890",
  6262. body);
  6263. EXPECT_EQ(StatusCode::OK_200, res->status);
  6264. }
  6265. TEST_F(ServerTest, NoZstd) {
  6266. Headers headers;
  6267. headers.emplace("Accept-Encoding", "zstd");
  6268. auto res = cli_.Get("/nocompress", headers);
  6269. ASSERT_TRUE(res);
  6270. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6271. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6272. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6273. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6274. "7890123456789012345678901234567890",
  6275. res->body);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6279. Headers headers;
  6280. headers.emplace("Accept-Encoding", "zstd");
  6281. std::string body;
  6282. auto res = cli_.Get("/nocompress", headers,
  6283. [&](const char *data, uint64_t data_length) {
  6284. EXPECT_EQ(100U, data_length);
  6285. body.append(data, data_length);
  6286. return true;
  6287. });
  6288. ASSERT_TRUE(res);
  6289. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6290. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6291. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6293. "7890123456789012345678901234567890",
  6294. body);
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. }
  6297. // TODO: How to enable zstd ??
  6298. TEST_F(ServerTest, MultipartFormDataZstd) {
  6299. UploadFormDataItems items = {
  6300. {"key1", "test", "", ""},
  6301. {"key2", "--abcdefg123", "", ""},
  6302. };
  6303. Headers headers;
  6304. headers.emplace("Accept-Encoding", "zstd");
  6305. cli_.set_compress(true);
  6306. auto res = cli_.Post("/compress-multipart", headers, items);
  6307. ASSERT_TRUE(res);
  6308. EXPECT_EQ(StatusCode::OK_200, res->status);
  6309. }
  6310. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6311. Headers headers;
  6312. headers.emplace("Accept-Encoding", "zstd");
  6313. cli_.set_compress(true);
  6314. auto res = cli_.Put(
  6315. "/put", headers, 3,
  6316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6317. sink.os << "PUT";
  6318. return true;
  6319. },
  6320. "text/plain");
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. EXPECT_EQ("PUT", res->body);
  6324. }
  6325. // Pre-compression logging tests
  6326. TEST_F(ServerTest, PreCompressionLogging) {
  6327. // Test data for compression (matches the actual /compress endpoint content)
  6328. const std::string test_content =
  6329. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6330. "3456789012345678901234567890";
  6331. // Variables to capture logging data
  6332. std::string pre_compression_body;
  6333. std::string pre_compression_content_type;
  6334. std::string pre_compression_content_encoding;
  6335. std::string post_compression_body;
  6336. std::string post_compression_content_type;
  6337. std::string post_compression_content_encoding;
  6338. // Set up pre-compression logger
  6339. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6340. const Response &res) {
  6341. pre_compression_body = res.body;
  6342. pre_compression_content_type = res.get_header_value("Content-Type");
  6343. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6344. });
  6345. // Set up post-compression logger
  6346. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6347. post_compression_body = res.body;
  6348. post_compression_content_type = res.get_header_value("Content-Type");
  6349. post_compression_content_encoding =
  6350. res.get_header_value("Content-Encoding");
  6351. });
  6352. // Test with gzip compression
  6353. Headers headers;
  6354. headers.emplace("Accept-Encoding", "gzip");
  6355. auto res = cli_.Get("/compress", headers);
  6356. // Verify response was compressed
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6360. // Verify pre-compression logger captured uncompressed content
  6361. EXPECT_EQ(test_content, pre_compression_body);
  6362. EXPECT_EQ("text/plain", pre_compression_content_type);
  6363. EXPECT_TRUE(pre_compression_content_encoding
  6364. .empty()); // No encoding header before compression
  6365. // Verify post-compression logger captured compressed content
  6366. EXPECT_NE(test_content,
  6367. post_compression_body); // Should be different after compression
  6368. EXPECT_EQ("text/plain", post_compression_content_type);
  6369. EXPECT_EQ("gzip", post_compression_content_encoding);
  6370. // Verify compressed content is smaller
  6371. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6372. }
  6373. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6374. const std::string test_content =
  6375. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6376. "3456789012345678901234567890";
  6377. std::string pre_compression_body;
  6378. std::string post_compression_body;
  6379. svr_.set_pre_compression_logger(
  6380. [&](const Request & /*req*/, const Response &res) {
  6381. pre_compression_body = res.body;
  6382. });
  6383. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6384. post_compression_body = res.body;
  6385. });
  6386. Headers headers;
  6387. headers.emplace("Accept-Encoding", "br");
  6388. auto res = cli_.Get("/compress", headers);
  6389. ASSERT_TRUE(res);
  6390. EXPECT_EQ(StatusCode::OK_200, res->status);
  6391. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6392. // Verify pre-compression content is uncompressed
  6393. EXPECT_EQ(test_content, pre_compression_body);
  6394. // Verify post-compression content is compressed
  6395. EXPECT_NE(test_content, post_compression_body);
  6396. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6397. }
  6398. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6399. const std::string test_content =
  6400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6401. "3456789012345678901234567890";
  6402. std::string pre_compression_body;
  6403. std::string post_compression_body;
  6404. svr_.set_pre_compression_logger(
  6405. [&](const Request & /*req*/, const Response &res) {
  6406. pre_compression_body = res.body;
  6407. });
  6408. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6409. post_compression_body = res.body;
  6410. });
  6411. // Request without compression (use /nocompress endpoint)
  6412. Headers headers;
  6413. auto res = cli_.Get("/nocompress", headers);
  6414. ASSERT_TRUE(res);
  6415. EXPECT_EQ(StatusCode::OK_200, res->status);
  6416. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6417. // Pre-compression logger should not be called when no compression is applied
  6418. EXPECT_TRUE(
  6419. pre_compression_body.empty()); // Pre-compression logger not called
  6420. EXPECT_EQ(
  6421. test_content,
  6422. post_compression_body); // Post-compression logger captures final content
  6423. }
  6424. TEST_F(ServerTest, LoggerSeesContentLength) {
  6425. size_t logged_content_length = 0;
  6426. std::string logged_content_length_header;
  6427. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6428. logged_content_length = res.content_length_;
  6429. logged_content_length_header = res.get_header_value("Content-Length");
  6430. });
  6431. auto res = cli_.Get("/nocompress");
  6432. ASSERT_TRUE(res);
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. EXPECT_EQ(res->body.size(), logged_content_length);
  6435. EXPECT_EQ(std::to_string(logged_content_length),
  6436. logged_content_length_header);
  6437. }
  6438. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6439. const std::string test_content =
  6440. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6441. "3456789012345678901234567890";
  6442. std::string pre_compression_body;
  6443. bool pre_logger_called = false;
  6444. // Set only pre-compression logger
  6445. svr_.set_pre_compression_logger(
  6446. [&](const Request & /*req*/, const Response &res) {
  6447. pre_compression_body = res.body;
  6448. pre_logger_called = true;
  6449. });
  6450. Headers headers;
  6451. headers.emplace("Accept-Encoding", "gzip");
  6452. auto res = cli_.Get("/compress", headers);
  6453. ASSERT_TRUE(res);
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6456. // Verify pre-compression logger was called
  6457. EXPECT_TRUE(pre_logger_called);
  6458. EXPECT_EQ(test_content, pre_compression_body);
  6459. }
  6460. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6461. {
  6462. // Test with Expect: 100-continue header - success case
  6463. // Server returns 100 Continue, client sends body, server returns 200 OK
  6464. Request req;
  6465. req.method = "POST";
  6466. req.path = "/post-large";
  6467. req.set_header("Expect", "100-continue");
  6468. req.body = LARGE_DATA;
  6469. Response res;
  6470. auto error = Error::Success;
  6471. cli_.set_keep_alive(true);
  6472. auto ret = cli_.send(req, res, error);
  6473. EXPECT_TRUE(ret);
  6474. EXPECT_EQ(StatusCode::OK_200, res.status);
  6475. EXPECT_EQ(LARGE_DATA, res.body);
  6476. }
  6477. {
  6478. // Test with Expect: 100-continue header - error case
  6479. // Client should not send the body when server returns an error
  6480. Request req;
  6481. req.method = "POST";
  6482. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6483. req.set_header("Expect", "100-continue");
  6484. req.body = LARGE_DATA;
  6485. Response res;
  6486. auto error = Error::Success;
  6487. auto start = std::chrono::high_resolution_clock::now();
  6488. cli_.set_keep_alive(true);
  6489. auto ret = cli_.send(req, res, error);
  6490. auto end = std::chrono::high_resolution_clock::now();
  6491. auto elapsed =
  6492. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6493. .count();
  6494. // With Expect: 100-continue, request completes successfully but with error
  6495. EXPECT_TRUE(ret);
  6496. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6497. EXPECT_EQ("close", res.get_header_value("Connection"));
  6498. EXPECT_FALSE(cli_.is_socket_open());
  6499. EXPECT_LE(elapsed, 2000);
  6500. }
  6501. {
  6502. // Send an extra GET request to ensure error recovery without hanging
  6503. Request req;
  6504. req.method = "GET";
  6505. req.path = "/hi";
  6506. auto start = std::chrono::high_resolution_clock::now();
  6507. auto res = cli_.send(req);
  6508. auto end = std::chrono::high_resolution_clock::now();
  6509. auto elapsed =
  6510. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6511. .count();
  6512. ASSERT_TRUE(res);
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("Hello World!", res->body);
  6515. EXPECT_LE(elapsed, 500);
  6516. }
  6517. }
  6518. TEST(ZstdDecompressor, ChunkedDecompression) {
  6519. std::string data;
  6520. for (size_t i = 0; i < 32 * 1024; ++i) {
  6521. data.push_back(static_cast<char>('a' + i % 26));
  6522. }
  6523. std::string compressed_data;
  6524. {
  6525. httplib::detail::zstd_compressor compressor;
  6526. bool result = compressor.compress(
  6527. data.data(), data.size(),
  6528. /*last=*/true,
  6529. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6530. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6531. compressed_data_size);
  6532. return true;
  6533. });
  6534. ASSERT_TRUE(result);
  6535. }
  6536. std::string decompressed_data;
  6537. {
  6538. httplib::detail::zstd_decompressor decompressor;
  6539. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6540. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6541. size_t chunk_size = 130;
  6542. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6543. chunk_begin += chunk_size) {
  6544. size_t current_chunk_size =
  6545. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6546. bool result = decompressor.decompress(
  6547. compressed_data.data() + chunk_begin, current_chunk_size,
  6548. [&](const char *decompressed_data_chunk,
  6549. size_t decompressed_data_chunk_size) {
  6550. decompressed_data.insert(decompressed_data.size(),
  6551. decompressed_data_chunk,
  6552. decompressed_data_chunk_size);
  6553. return true;
  6554. });
  6555. ASSERT_TRUE(result);
  6556. }
  6557. }
  6558. ASSERT_EQ(data, decompressed_data);
  6559. }
  6560. TEST(ZstdDecompressor, Decompress) {
  6561. std::string original_text = "Compressed with ZSTD";
  6562. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6563. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6564. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6565. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6566. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6567. std::string decompressed_data;
  6568. {
  6569. httplib::detail::zstd_decompressor decompressor;
  6570. bool result = decompressor.decompress(
  6571. compressed_data.data(), compressed_data.size(),
  6572. [&](const char *decompressed_data_chunk,
  6573. size_t decompressed_data_chunk_size) {
  6574. decompressed_data.insert(decompressed_data.size(),
  6575. decompressed_data_chunk,
  6576. decompressed_data_chunk_size);
  6577. return true;
  6578. });
  6579. ASSERT_TRUE(result);
  6580. }
  6581. ASSERT_EQ(original_text, decompressed_data);
  6582. }
  6583. #endif
  6584. // Sends a raw request to a server listening at HOST:PORT.
  6585. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6586. std::string *resp = nullptr) {
  6587. auto error = Error::Success;
  6588. auto client_sock = detail::create_client_socket(
  6589. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6590. /*connection_timeout_sec=*/5, 0,
  6591. /*read_timeout_sec=*/5, 0,
  6592. /*write_timeout_sec=*/5, 0, std::string(), error);
  6593. if (client_sock == INVALID_SOCKET) { return false; }
  6594. auto ret = detail::process_client_socket(
  6595. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6596. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6597. if (req.size() !=
  6598. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6599. return false;
  6600. }
  6601. char buf[512];
  6602. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6603. while (line_reader.getline()) {
  6604. if (resp) { *resp += line_reader.ptr(); }
  6605. }
  6606. return true;
  6607. });
  6608. detail::close_socket(client_sock);
  6609. return ret;
  6610. }
  6611. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6612. Server svr;
  6613. std::string header_value;
  6614. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6615. header_value = req.get_header_value("foo");
  6616. res.set_content("ok", "text/plain");
  6617. });
  6618. thread t = thread([&] { svr.listen(HOST, PORT); });
  6619. auto se = detail::scope_exit([&] {
  6620. svr.stop();
  6621. t.join();
  6622. ASSERT_FALSE(svr.is_running());
  6623. });
  6624. svr.wait_until_ready();
  6625. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6626. // like characters are not treated the same - use vertical tab and escape.
  6627. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6628. "foo: \t \v bar \x1B\t \r\n"
  6629. "Connection: close\r\n"
  6630. "\r\n";
  6631. std::string res;
  6632. ASSERT_TRUE(send_request(5, req, &res));
  6633. EXPECT_EQ(header_value, "");
  6634. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6635. }
  6636. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6637. Server svr;
  6638. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6639. auto i = new int(0);
  6640. res.set_header("Trailer", "X-Safe, X-Reflected");
  6641. res.set_chunked_content_provider(
  6642. "text/plain",
  6643. [i](size_t /*offset*/, DataSink &sink) {
  6644. if (*i == 0) {
  6645. sink.os << "body";
  6646. } else {
  6647. Headers trailer;
  6648. // A valid trailer that must survive.
  6649. trailer.emplace("X-Safe", "safe");
  6650. // Attacker-controlled value carrying CR/LF (response splitting).
  6651. trailer.emplace("X-Reflected",
  6652. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6653. // Attacker-controlled name carrying CR/LF.
  6654. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6655. sink.done_with_trailer(trailer);
  6656. }
  6657. (*i)++;
  6658. return true;
  6659. },
  6660. [i](bool /*success*/) { delete i; });
  6661. });
  6662. thread t = thread([&] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. t.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6670. "Host: " + HOST +
  6671. "\r\n"
  6672. "Connection: close\r\n"
  6673. "\r\n";
  6674. std::string res;
  6675. ASSERT_TRUE(send_request(5, req, &res));
  6676. // The injected fields must not appear anywhere in the raw response.
  6677. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6678. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6679. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6680. // Invalid trailers are dropped entirely, matching set_header().
  6681. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6682. // The valid trailer still passes through.
  6683. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6684. }
  6685. // Sends a raw request and verifies that there isn't a crash or exception.
  6686. static void test_raw_request(const std::string &req,
  6687. std::string *out = nullptr) {
  6688. Server svr;
  6689. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6690. res.set_content("ok", "text/plain");
  6691. });
  6692. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6693. res.set_content("ok", "text/plain");
  6694. });
  6695. svr.Get("/header_field_value_check",
  6696. [&](const Request & /*req*/, Response &res) {
  6697. res.set_content("ok", "text/plain");
  6698. });
  6699. // Server read timeout must be longer than the client read timeout for the
  6700. // bug to reproduce, probably to force the server to process a request
  6701. // without a trailing blank line.
  6702. const time_t client_read_timeout_sec = 1;
  6703. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6704. bool listen_thread_ok = false;
  6705. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6706. auto se = detail::scope_exit([&] {
  6707. svr.stop();
  6708. t.join();
  6709. ASSERT_FALSE(svr.is_running());
  6710. EXPECT_TRUE(listen_thread_ok);
  6711. });
  6712. svr.wait_until_ready();
  6713. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6714. }
  6715. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6716. // A certain header line causes an exception if the header property is parsed
  6717. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6718. test_raw_request(
  6719. "GET /hi HTTP/1.1\r\n"
  6720. " : "
  6721. " "
  6722. " ");
  6723. }
  6724. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6725. // A certain header line causes an exception if the header property *name* is
  6726. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6727. // greedy matcher and requires backtracking when there are a lot of ":"
  6728. // characters.
  6729. // This occurs with libc++ but not libstdc++.
  6730. test_raw_request(
  6731. "GET /hi HTTP/1.1\r\n"
  6732. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6733. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6734. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6735. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6736. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6737. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6738. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6739. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6740. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6741. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6742. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6743. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6744. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6745. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6746. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6747. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6748. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6749. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6750. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6751. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6752. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6753. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6754. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6755. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6756. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6757. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6758. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6759. "&&&%%%");
  6760. }
  6761. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6762. // Make sure this doesn't crash the server.
  6763. // In a previous version of the header line regex, the "\r" rendered the line
  6764. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6765. // a new position where the leading white space ended and the field value
  6766. // began.
  6767. // The crash occurs with libc++ but not libstdc++.
  6768. test_raw_request("GET /hi HTTP/1.1\r\n"
  6769. "a:" +
  6770. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6771. "\r\n"
  6772. "\r\n");
  6773. }
  6774. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6775. std::string out;
  6776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6777. "Content-Type: text/plain\r\n"
  6778. "Transfer-Encoding: chunked\r\n"
  6779. "\r\n"
  6780. "nothex\r\n",
  6781. &out);
  6782. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6783. }
  6784. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6785. std::string out;
  6786. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6787. "Content-Type: text/plain\r\n"
  6788. "Transfer-Encoding: chunked\r\n"
  6789. "\r\n"
  6790. "3\r\n"
  6791. "xyz\r\n"
  6792. "NaN\r\n",
  6793. &out);
  6794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6795. }
  6796. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6797. std::string out;
  6798. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6799. "Content-Type: text/plain\r\n"
  6800. "Transfer-Encoding: chunked\r\n"
  6801. "\r\n"
  6802. // Length is too large for 64 bits.
  6803. "1ffffffffffffffff\r\n"
  6804. "xyz\r\n",
  6805. &out);
  6806. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6807. }
  6808. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6809. test_raw_request("GET /hi HTTP/1.1\r\n"
  6810. "Content-Type: text/plain\r\n\r");
  6811. }
  6812. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6813. std::string out;
  6814. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6815. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6816. }
  6817. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6818. Server svr;
  6819. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6820. EXPECT_TRUE(!req.remote_addr.empty());
  6821. });
  6822. thread t = thread([&] { svr.listen(HOST, PORT); });
  6823. auto se = detail::scope_exit([&] {
  6824. svr.stop();
  6825. t.join();
  6826. ASSERT_FALSE(svr.is_running());
  6827. });
  6828. svr.wait_until_ready();
  6829. // Send an invalid request line to trigger Bad Request
  6830. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6831. std::string out;
  6832. ASSERT_TRUE(send_request(5, bad_req, &out));
  6833. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6834. }
  6835. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6836. std::string out;
  6837. std::string request(
  6838. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6839. test_raw_request(request, &out);
  6840. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6841. }
  6842. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6843. std::string out;
  6844. std::string request(
  6845. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6846. test_raw_request(request, &out);
  6847. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6848. }
  6849. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6850. std::string out;
  6851. std::string request(
  6852. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6853. test_raw_request(request, &out);
  6854. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6855. }
  6856. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6857. std::string out;
  6858. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6859. "Test: \r\n\r\n",
  6860. &out);
  6861. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6862. }
  6863. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6864. Server svr;
  6865. std::string x_custom;
  6866. std::string cookie;
  6867. std::string xff;
  6868. std::string x_unicode;
  6869. std::string x_iis;
  6870. svr.Get("/check", [&](const Request &req, Response &res) {
  6871. x_custom = req.get_header_value("X-Custom");
  6872. cookie = req.get_header_value("Cookie");
  6873. xff = req.get_header_value("X-Forwarded-For");
  6874. x_unicode = req.get_header_value("X-Unicode");
  6875. x_iis = req.get_header_value("X-IIS");
  6876. res.set_content("ok", "text/plain");
  6877. });
  6878. thread t = thread([&] { svr.listen(HOST, PORT); });
  6879. auto se = detail::scope_exit([&] {
  6880. svr.stop();
  6881. t.join();
  6882. ASSERT_FALSE(svr.is_running());
  6883. });
  6884. svr.wait_until_ready();
  6885. const std::string req = "GET /check HTTP/1.1\r\n"
  6886. "Host: localhost\r\n"
  6887. "X-Custom: a%0D%0AInjected: b\r\n"
  6888. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6889. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6890. "X-Unicode: %E3%81%82\r\n"
  6891. "X-IIS: %u00E9\r\n"
  6892. "Connection: close\r\n"
  6893. "\r\n";
  6894. std::string res;
  6895. ASSERT_TRUE(send_request(5, req, &res));
  6896. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6897. // Every value must be returned verbatim (wire form), with no decoding.
  6898. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6899. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6900. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6901. EXPECT_EQ("%E3%81%82", x_unicode);
  6902. EXPECT_EQ("%u00E9", x_iis);
  6903. }
  6904. // Applications that previously relied on automatic percent-decoding can
  6905. // reproduce the old behavior by explicitly calling decode_path_component()
  6906. // or, for RFC 3986 conformance, decode_uri_component().
  6907. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6908. Server svr;
  6909. std::string decoded;
  6910. svr.Get("/check", [&](const Request &req, Response &res) {
  6911. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  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: hello%20world\r\n"
  6924. "Connection: close\r\n"
  6925. "\r\n";
  6926. std::string res;
  6927. ASSERT_TRUE(send_request(5, req, &res));
  6928. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6929. EXPECT_EQ("hello world", decoded);
  6930. }
  6931. // Regression test for #2033. Browsers send Referer values that include
  6932. // percent-encoded characters such as %0A inside the URL. Decoding the
  6933. // header value would either trip the post-decode CR/LF/NUL guard (the
  6934. // original bug, returning 400) or, after that guard was relaxed, silently
  6935. // store a literal LF — both unacceptable. The wire form must round-trip.
  6936. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6937. Server svr;
  6938. std::string referer;
  6939. svr.Get("/check", [&](const Request &req, Response &res) {
  6940. referer = req.get_header_value("Referer");
  6941. res.set_content("ok", "text/plain");
  6942. });
  6943. thread t = thread([&] { svr.listen(HOST, PORT); });
  6944. auto se = detail::scope_exit([&] {
  6945. svr.stop();
  6946. t.join();
  6947. ASSERT_FALSE(svr.is_running());
  6948. });
  6949. svr.wait_until_ready();
  6950. const std::string req = "GET /check HTTP/1.1\r\n"
  6951. "Host: localhost\r\n"
  6952. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6953. "Connection: close\r\n"
  6954. "\r\n";
  6955. std::string res;
  6956. ASSERT_TRUE(send_request(5, req, &res));
  6957. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6958. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6959. }
  6960. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6961. Server svr;
  6962. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6963. res.set_header("Cache-Control", "no-cache");
  6964. res.set_chunked_content_provider(
  6965. "text/event-stream", [](size_t offset, DataSink &sink) {
  6966. std::string s = "data:";
  6967. s += std::to_string(offset);
  6968. s += "\n\n";
  6969. auto ret = sink.write(s.data(), s.size());
  6970. EXPECT_TRUE(ret);
  6971. std::this_thread::sleep_for(std::chrono::seconds(1));
  6972. return true;
  6973. });
  6974. });
  6975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6976. svr.wait_until_ready();
  6977. Client client(HOST, PORT);
  6978. const Headers headers = {{"Accept", "text/event-stream"}};
  6979. auto get_thread = std::thread([&client, &headers]() {
  6980. auto res = client.Get(
  6981. "/events", headers,
  6982. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6983. });
  6984. auto se = detail::scope_exit([&] {
  6985. svr.stop();
  6986. get_thread.join();
  6987. listen_thread.join();
  6988. ASSERT_FALSE(svr.is_running());
  6989. });
  6990. // Give GET time to get a few messages.
  6991. std::this_thread::sleep_for(std::chrono::seconds(2));
  6992. }
  6993. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6994. httplib::Server svr;
  6995. svr.Post("/hi",
  6996. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6997. res.status = StatusCode::OK_200;
  6998. });
  6999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7000. svr.wait_until_ready();
  7001. Client cli(HOST, PORT);
  7002. auto res = cli.Post("/hi", "data", "text/plain");
  7003. ASSERT_TRUE(res);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. svr.stop();
  7006. thread.join();
  7007. ASSERT_FALSE(svr.is_running());
  7008. res = cli.Post("/hi", "data", "text/plain");
  7009. ASSERT_FALSE(res);
  7010. }
  7011. TEST(ServerStopTest, ListenFailure) {
  7012. Server svr;
  7013. auto t = thread([&]() {
  7014. auto ret = svr.listen("????", PORT);
  7015. EXPECT_FALSE(ret);
  7016. });
  7017. svr.wait_until_ready();
  7018. svr.stop();
  7019. t.join();
  7020. }
  7021. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7022. TEST(ServerStopTest, Decommision) {
  7023. Server svr;
  7024. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7025. for (int i = 0; i < 4; i++) {
  7026. auto is_even = !(i % 2);
  7027. std::thread t{[&] {
  7028. try {
  7029. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7030. if (is_even) {
  7031. throw std::runtime_error("Some thing that happens to go wrong.");
  7032. }
  7033. svr.listen(HOST, PORT);
  7034. } catch (...) { svr.decommission(); }
  7035. }};
  7036. svr.wait_until_ready();
  7037. // Server is up
  7038. {
  7039. Client cli(HOST, PORT);
  7040. auto res = cli.Get("/hi");
  7041. if (is_even) {
  7042. EXPECT_FALSE(res);
  7043. } else {
  7044. EXPECT_TRUE(res);
  7045. EXPECT_EQ("hi...", res->body);
  7046. }
  7047. }
  7048. svr.stop();
  7049. t.join();
  7050. // Server is down...
  7051. {
  7052. Client cli(HOST, PORT);
  7053. auto res = cli.Get("/hi");
  7054. EXPECT_FALSE(res);
  7055. }
  7056. }
  7057. }
  7058. #endif
  7059. // Helper function for string body upload progress tests
  7060. template <typename SetupHandler, typename ClientCall>
  7061. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7062. ClientCall &&client_call,
  7063. const string &body) {
  7064. Server svr;
  7065. setup_handler(svr);
  7066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. svr.stop();
  7069. t.join();
  7070. });
  7071. svr.wait_until_ready();
  7072. Client cli(HOST, PORT);
  7073. vector<uint64_t> progress_values;
  7074. bool progress_called = false;
  7075. auto res =
  7076. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7077. progress_values.push_back(current);
  7078. progress_called = true;
  7079. return true;
  7080. });
  7081. ASSERT_TRUE(res);
  7082. EXPECT_EQ(200, res->status);
  7083. EXPECT_TRUE(progress_called);
  7084. }
  7085. TEST(UploadProgressTest, PostStringBodyBasic) {
  7086. TestStringBodyUploadProgress(
  7087. [](Server &svr) {
  7088. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7089. res.set_content("received", "text/plain");
  7090. });
  7091. },
  7092. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7093. return cli.Post("/test", body, "text/plain", progress_callback);
  7094. },
  7095. "test data for upload progress");
  7096. }
  7097. TEST(UploadProgressTest, PutStringBodyBasic) {
  7098. TestStringBodyUploadProgress(
  7099. [](Server &svr) {
  7100. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7101. res.set_content("put received", "text/plain");
  7102. });
  7103. },
  7104. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7105. return cli.Put("/test", body, "text/plain", progress_callback);
  7106. },
  7107. "put test data for upload progress");
  7108. }
  7109. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7110. TestStringBodyUploadProgress(
  7111. [](Server &svr) {
  7112. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7113. res.set_content("patch received", "text/plain");
  7114. });
  7115. },
  7116. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7117. return cli.Patch("/test", body, "text/plain", progress_callback);
  7118. },
  7119. "patch test data for upload progress");
  7120. }
  7121. // Helper function for content provider upload progress tests
  7122. template <typename SetupHandler, typename ClientCall>
  7123. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7124. ClientCall &&client_call) {
  7125. Server svr;
  7126. setup_handler(svr);
  7127. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7128. auto se = detail::scope_exit([&] {
  7129. svr.stop();
  7130. t.join();
  7131. });
  7132. svr.wait_until_ready();
  7133. Client cli(HOST, PORT);
  7134. vector<uint64_t> progress_values;
  7135. auto res =
  7136. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7137. progress_values.push_back(current);
  7138. return true;
  7139. });
  7140. ASSERT_TRUE(res);
  7141. EXPECT_EQ(200, res->status);
  7142. EXPECT_FALSE(progress_values.empty());
  7143. }
  7144. TEST(UploadProgressTest, PostContentProviderProgress) {
  7145. TestContentProviderUploadProgress(
  7146. [](Server &svr) {
  7147. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7148. res.set_content("provider received", "text/plain");
  7149. });
  7150. },
  7151. [](Client &cli, UploadProgress progress_callback) {
  7152. return cli.Post(
  7153. "/test", 10,
  7154. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7155. sink.os << "test data";
  7156. return true;
  7157. },
  7158. "text/plain", progress_callback);
  7159. });
  7160. }
  7161. // Helper function for multipart upload progress tests
  7162. template <typename SetupHandler, typename ClientCall>
  7163. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7164. ClientCall &&client_call,
  7165. const string &endpoint) {
  7166. Server svr;
  7167. setup_handler(svr);
  7168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7169. auto se = detail::scope_exit([&] {
  7170. svr.stop();
  7171. t.join();
  7172. });
  7173. svr.wait_until_ready();
  7174. Client cli(HOST, PORT);
  7175. vector<uint64_t> progress_values;
  7176. UploadFormDataItems items = {
  7177. {"field1", "value1", "", ""},
  7178. {"field2", "longer value for progress tracking test", "", ""},
  7179. {"file1", "file content data for upload progress", "test.txt",
  7180. "text/plain"}};
  7181. auto res = client_call(cli, endpoint, items,
  7182. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7183. progress_values.push_back(current);
  7184. return true;
  7185. });
  7186. ASSERT_TRUE(res);
  7187. EXPECT_EQ(200, res->status);
  7188. EXPECT_FALSE(progress_values.empty());
  7189. }
  7190. TEST(UploadProgressTest, PostMultipartProgress) {
  7191. TestMultipartUploadProgress(
  7192. [](Server &svr) {
  7193. svr.Post("/multipart", [](const Request &req, Response &res) {
  7194. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7195. res.set_content("multipart received", "text/plain");
  7196. });
  7197. },
  7198. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7199. UploadProgress progress_callback) {
  7200. return cli.Post(endpoint, items, progress_callback);
  7201. },
  7202. "/multipart");
  7203. }
  7204. // Helper function for basic download progress tests
  7205. template <typename SetupHandler, typename ClientCall>
  7206. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7207. ClientCall &&client_call, const string &endpoint,
  7208. size_t expected_content_size) {
  7209. Server svr;
  7210. setup_handler(svr);
  7211. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7212. auto se = detail::scope_exit([&] {
  7213. svr.stop();
  7214. t.join();
  7215. });
  7216. svr.wait_until_ready();
  7217. Client cli(HOST, PORT);
  7218. vector<uint64_t> progress_values;
  7219. auto res = client_call(cli, endpoint,
  7220. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7221. progress_values.push_back(current);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(res);
  7225. EXPECT_EQ(200, res->status);
  7226. EXPECT_FALSE(progress_values.empty());
  7227. EXPECT_EQ(expected_content_size, res->body.size());
  7228. }
  7229. TEST(DownloadProgressTest, GetBasic) {
  7230. TestBasicDownloadProgress(
  7231. [](Server &svr) {
  7232. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7233. string content(1000, 'D');
  7234. res.set_content(content, "text/plain");
  7235. });
  7236. },
  7237. [](Client &cli, const string &endpoint,
  7238. DownloadProgress progress_callback) {
  7239. return cli.Get(endpoint, progress_callback);
  7240. },
  7241. "/download", 1000u);
  7242. }
  7243. // Helper function for content receiver download progress tests
  7244. template <typename SetupHandler, typename ClientCall>
  7245. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7246. ClientCall &&client_call,
  7247. const string &endpoint,
  7248. size_t expected_content_size) {
  7249. Server svr;
  7250. setup_handler(svr);
  7251. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7252. auto se = detail::scope_exit([&] {
  7253. svr.stop();
  7254. t.join();
  7255. });
  7256. svr.wait_until_ready();
  7257. Client cli(HOST, PORT);
  7258. vector<uint64_t> progress_values;
  7259. string received_body;
  7260. auto res = client_call(
  7261. cli, endpoint,
  7262. [&](const char *data, size_t data_length) -> bool {
  7263. received_body.append(data, data_length);
  7264. return true;
  7265. },
  7266. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7267. progress_values.push_back(current);
  7268. return true;
  7269. });
  7270. ASSERT_TRUE(res);
  7271. EXPECT_EQ(200, res->status);
  7272. EXPECT_FALSE(progress_values.empty());
  7273. EXPECT_EQ(expected_content_size, received_body.size());
  7274. EXPECT_TRUE(res->body.empty());
  7275. }
  7276. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7277. TestContentReceiverDownloadProgress(
  7278. [](Server &svr) {
  7279. svr.Get("/download-receiver",
  7280. [](const Request & /*req*/, Response &res) {
  7281. string content(2000, 'R');
  7282. res.set_content(content, "text/plain");
  7283. });
  7284. },
  7285. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7286. DownloadProgress progress_callback) {
  7287. return cli.Get(endpoint, content_receiver, progress_callback);
  7288. },
  7289. "/download-receiver", 2000u);
  7290. }
  7291. TEST(StreamingTest, NoContentLengthStreaming) {
  7292. Server svr;
  7293. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7294. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7295. if (offset < 6) {
  7296. sink.os << (offset < 3 ? "a" : "b");
  7297. } else {
  7298. sink.done();
  7299. }
  7300. return true;
  7301. });
  7302. });
  7303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7304. auto listen_se = detail::scope_exit([&] {
  7305. svr.stop();
  7306. listen_thread.join();
  7307. ASSERT_FALSE(svr.is_running());
  7308. });
  7309. svr.wait_until_ready();
  7310. Client client(HOST, PORT);
  7311. auto get_thread = std::thread([&client]() {
  7312. std::string s;
  7313. auto res =
  7314. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7315. s += std::string(data, len);
  7316. return true;
  7317. });
  7318. ASSERT_TRUE(res);
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("aaabbb", s);
  7321. });
  7322. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7323. // Give GET time to get a few messages.
  7324. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7325. }
  7326. TEST(MountTest, Unmount) {
  7327. Server svr;
  7328. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7329. auto se = detail::scope_exit([&] {
  7330. svr.stop();
  7331. listen_thread.join();
  7332. ASSERT_FALSE(svr.is_running());
  7333. });
  7334. svr.wait_until_ready();
  7335. Client cli("localhost", PORT);
  7336. svr.set_mount_point("/mount2", "./www2");
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7340. res = cli.Get("/mount2/dir/test.html");
  7341. ASSERT_TRUE(res);
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. svr.set_mount_point("/", "./www");
  7344. res = cli.Get("/dir/");
  7345. ASSERT_TRUE(res);
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. svr.remove_mount_point("/");
  7348. res = cli.Get("/dir/");
  7349. ASSERT_TRUE(res);
  7350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7351. svr.remove_mount_point("/mount2");
  7352. res = cli.Get("/mount2/dir/test.html");
  7353. ASSERT_TRUE(res);
  7354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7355. }
  7356. TEST(MountTest, Redicect) {
  7357. Server svr;
  7358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7359. auto se = detail::scope_exit([&] {
  7360. svr.stop();
  7361. listen_thread.join();
  7362. ASSERT_FALSE(svr.is_running());
  7363. });
  7364. svr.set_mount_point("/", "./www");
  7365. svr.wait_until_ready();
  7366. Client cli("localhost", PORT);
  7367. auto res = cli.Get("/dir/");
  7368. ASSERT_TRUE(res);
  7369. EXPECT_EQ(StatusCode::OK_200, res->status);
  7370. res = cli.Get("/dir");
  7371. ASSERT_TRUE(res);
  7372. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7373. res = cli.Get("/file");
  7374. ASSERT_TRUE(res);
  7375. EXPECT_EQ(StatusCode::OK_200, res->status);
  7376. res = cli.Get("/file/");
  7377. ASSERT_TRUE(res);
  7378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7379. cli.set_follow_location(true);
  7380. res = cli.Get("/dir");
  7381. ASSERT_TRUE(res);
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST(MountTest, MultibytesPathName) {
  7385. Server svr;
  7386. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7387. auto se = detail::scope_exit([&] {
  7388. svr.stop();
  7389. listen_thread.join();
  7390. ASSERT_FALSE(svr.is_running());
  7391. });
  7392. svr.set_mount_point("/", "./www");
  7393. svr.wait_until_ready();
  7394. Client cli("localhost", PORT);
  7395. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7396. ASSERT_TRUE(res);
  7397. EXPECT_EQ(StatusCode::OK_200, res->status);
  7398. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7399. }
  7400. #ifdef _WIN32
  7401. // Issue #2435: mmap::open() must succeed even when another handle holds
  7402. // the file open for writing (e.g. an active log file).
  7403. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7404. const char *path = "mmap_concurrent_writer_test.txt";
  7405. const char *content = "hello";
  7406. {
  7407. std::ofstream f(path, std::ios::binary);
  7408. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7409. }
  7410. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7411. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7412. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7413. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7414. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7415. detail::mmap m(path);
  7416. ASSERT_TRUE(m.is_open());
  7417. EXPECT_EQ(strlen(content), m.size());
  7418. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7419. }
  7420. #endif
  7421. TEST(KeepAliveTest, ReadTimeout) {
  7422. Server svr;
  7423. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7424. std::this_thread::sleep_for(std::chrono::seconds(2));
  7425. res.set_content("a", "text/plain");
  7426. });
  7427. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7428. res.set_content("b", "text/plain");
  7429. });
  7430. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7431. auto se = detail::scope_exit([&] {
  7432. svr.stop();
  7433. listen_thread.join();
  7434. ASSERT_FALSE(svr.is_running());
  7435. });
  7436. svr.wait_until_ready();
  7437. Client cli("localhost", PORT);
  7438. cli.set_keep_alive(true);
  7439. cli.set_read_timeout(std::chrono::seconds(1));
  7440. auto resa = cli.Get("/a");
  7441. ASSERT_FALSE(resa);
  7442. EXPECT_EQ(Error::Read, resa.error());
  7443. auto resb = cli.Get("/b");
  7444. ASSERT_TRUE(resb);
  7445. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7446. EXPECT_EQ("b", resb->body);
  7447. }
  7448. TEST(KeepAliveTest, MaxCount) {
  7449. size_t keep_alive_max_count = 3;
  7450. Server svr;
  7451. svr.set_keep_alive_max_count(keep_alive_max_count);
  7452. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7453. res.set_content("Hello World!", "text/plain");
  7454. });
  7455. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7456. auto se = detail::scope_exit([&] {
  7457. svr.stop();
  7458. listen_thread.join();
  7459. ASSERT_FALSE(svr.is_running());
  7460. });
  7461. svr.wait_until_ready();
  7462. Client cli(HOST, PORT);
  7463. cli.set_keep_alive(true);
  7464. for (size_t i = 0; i < 5; i++) {
  7465. auto result = cli.Get("/hi");
  7466. ASSERT_TRUE(result);
  7467. EXPECT_EQ(StatusCode::OK_200, result->status);
  7468. if (i == keep_alive_max_count - 1) {
  7469. EXPECT_EQ("close", result->get_header_value("Connection"));
  7470. } else {
  7471. EXPECT_FALSE(result->has_header("Connection"));
  7472. }
  7473. }
  7474. }
  7475. TEST(KeepAliveTest, Issue1041) {
  7476. Server svr;
  7477. svr.set_keep_alive_timeout(3);
  7478. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7479. res.set_content("Hello World!", "text/plain");
  7480. });
  7481. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7482. auto se = detail::scope_exit([&] {
  7483. svr.stop();
  7484. listen_thread.join();
  7485. ASSERT_FALSE(svr.is_running());
  7486. });
  7487. svr.wait_until_ready();
  7488. Client cli(HOST, PORT);
  7489. cli.set_keep_alive(true);
  7490. auto result = cli.Get("/hi");
  7491. ASSERT_TRUE(result);
  7492. EXPECT_EQ(StatusCode::OK_200, result->status);
  7493. std::this_thread::sleep_for(std::chrono::seconds(5));
  7494. result = cli.Get("/hi");
  7495. ASSERT_TRUE(result);
  7496. EXPECT_EQ(StatusCode::OK_200, result->status);
  7497. }
  7498. TEST(KeepAliveTest, Issue1959) {
  7499. Server svr;
  7500. svr.set_keep_alive_timeout(5);
  7501. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7502. res.set_content("a", "text/plain");
  7503. });
  7504. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7505. auto se = detail::scope_exit([&] {
  7506. if (!svr.is_running()) return;
  7507. svr.stop();
  7508. listen_thread.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.wait_until_ready();
  7512. Client cli("localhost", PORT);
  7513. cli.set_keep_alive(true);
  7514. using namespace std::chrono;
  7515. auto start = steady_clock::now();
  7516. cli.Get("/a");
  7517. svr.stop();
  7518. listen_thread.join();
  7519. auto end = steady_clock::now();
  7520. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7521. EXPECT_LT(elapsed, 5000);
  7522. }
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. TEST(KeepAliveTest, SSLClientReconnection) {
  7525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7526. ASSERT_TRUE(svr.is_valid());
  7527. svr.set_keep_alive_timeout(1);
  7528. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7529. res.set_content("Hello World!", "text/plain");
  7530. });
  7531. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7532. auto se = detail::scope_exit([&] {
  7533. svr.stop();
  7534. listen_thread.join();
  7535. ASSERT_FALSE(svr.is_running());
  7536. });
  7537. svr.wait_until_ready();
  7538. SSLClient cli(HOST, PORT);
  7539. cli.enable_server_certificate_verification(false);
  7540. cli.set_keep_alive(true);
  7541. auto result = cli.Get("/hi");
  7542. ASSERT_TRUE(result);
  7543. EXPECT_EQ(StatusCode::OK_200, result->status);
  7544. result = cli.Get("/hi");
  7545. ASSERT_TRUE(result);
  7546. EXPECT_EQ(StatusCode::OK_200, result->status);
  7547. std::this_thread::sleep_for(std::chrono::seconds(2));
  7548. // Recoonect
  7549. result = cli.Get("/hi");
  7550. ASSERT_TRUE(result);
  7551. EXPECT_EQ(StatusCode::OK_200, result->status);
  7552. result = cli.Get("/hi");
  7553. ASSERT_TRUE(result);
  7554. EXPECT_EQ(StatusCode::OK_200, result->status);
  7555. }
  7556. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7558. ASSERT_TRUE(svr.is_valid());
  7559. svr.set_keep_alive_timeout(1);
  7560. std::string content = "reconnect";
  7561. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7562. res.set_content("Hello World!", "text/plain");
  7563. });
  7564. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7565. auto se = detail::scope_exit([&] {
  7566. svr.stop();
  7567. listen_thread.join();
  7568. ASSERT_FALSE(svr.is_running());
  7569. });
  7570. svr.wait_until_ready();
  7571. SSLClient cli(HOST, PORT);
  7572. cli.enable_server_certificate_verification(false);
  7573. cli.set_keep_alive(true);
  7574. auto result = cli.Post(
  7575. "/hi", content.size(),
  7576. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7577. sink.write(content.c_str(), content.size());
  7578. return true;
  7579. },
  7580. "text/plain");
  7581. ASSERT_TRUE(result);
  7582. EXPECT_EQ(200, result->status);
  7583. std::this_thread::sleep_for(std::chrono::seconds(2));
  7584. // Recoonect
  7585. result = cli.Post(
  7586. "/hi", content.size(),
  7587. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7588. sink.write(content.c_str(), content.size());
  7589. return true;
  7590. },
  7591. "text/plain");
  7592. ASSERT_TRUE(result);
  7593. EXPECT_EQ(200, result->status);
  7594. result = cli.Post(
  7595. "/hi", content.size(),
  7596. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7597. sink.write(content.c_str(), content.size());
  7598. return true;
  7599. },
  7600. "text/plain");
  7601. ASSERT_TRUE(result);
  7602. EXPECT_EQ(200, result->status);
  7603. }
  7604. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7605. using namespace httplib::tls;
  7606. {
  7607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7608. ASSERT_TRUE(svr.is_valid());
  7609. svr.Get("/sni", [&](const Request &req, Response &res) {
  7610. std::string expected = req.sni();
  7611. EXPECT_EQ(expected, req.get_param_value("expected"));
  7612. res.set_content("ok", "text/plain");
  7613. });
  7614. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7615. auto se = detail::scope_exit([&] {
  7616. svr.stop();
  7617. listen_thread.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. {
  7622. SSLClient cli("localhost", PORT);
  7623. cli.enable_server_certificate_verification(false);
  7624. auto res = cli.Get("/sni?expected=localhost");
  7625. ASSERT_TRUE(res);
  7626. }
  7627. {
  7628. SSLClient cli("::1", PORT);
  7629. cli.enable_server_certificate_verification(false);
  7630. auto res = cli.Get("/sni?expected=");
  7631. // NOTE: This may fail if the server is listening on IPv4 only
  7632. // (e.g., when localhost resolves to 127.0.0.1 only)
  7633. if (res) {
  7634. EXPECT_EQ(StatusCode::OK_200, res->status);
  7635. } else {
  7636. EXPECT_EQ(Error::Connection, res.error());
  7637. }
  7638. }
  7639. }
  7640. }
  7641. #endif
  7642. TEST(ClientProblemDetectionTest, ContentProvider) {
  7643. Server svr;
  7644. size_t content_length = 1024 * 1024;
  7645. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7646. res.set_content_provider(
  7647. content_length, "text/plain",
  7648. [&](size_t offset, size_t length, DataSink &sink) {
  7649. auto out_len = std::min(length, static_cast<size_t>(1024));
  7650. std::string out(out_len, '@');
  7651. sink.write(out.data(), out_len);
  7652. return offset < 4096;
  7653. },
  7654. [](bool success) { ASSERT_FALSE(success); });
  7655. });
  7656. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7657. res.set_content_provider(
  7658. 0, "text/plain",
  7659. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7660. EXPECT_TRUE(false);
  7661. return true;
  7662. },
  7663. [](bool success) { ASSERT_FALSE(success); });
  7664. });
  7665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7666. auto se = detail::scope_exit([&] {
  7667. svr.stop();
  7668. listen_thread.join();
  7669. ASSERT_FALSE(svr.is_running());
  7670. });
  7671. svr.wait_until_ready();
  7672. Client cli("localhost", PORT);
  7673. {
  7674. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7675. size_t /*data_length*/) { return false; });
  7676. ASSERT_FALSE(res);
  7677. }
  7678. {
  7679. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7680. size_t /*data_length*/) { return false; });
  7681. ASSERT_TRUE(res);
  7682. }
  7683. }
  7684. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7685. Server svr;
  7686. svr.set_error_handler([](Request const &, Response &res) -> void {
  7687. res.set_chunked_content_provider(
  7688. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7689. sink.os << "hello";
  7690. sink.os << "world";
  7691. sink.done();
  7692. return true;
  7693. });
  7694. });
  7695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7696. auto se = detail::scope_exit([&] {
  7697. svr.stop();
  7698. listen_thread.join();
  7699. ASSERT_FALSE(svr.is_running());
  7700. });
  7701. svr.wait_until_ready();
  7702. Client cli("localhost", PORT);
  7703. auto res = cli.Get("/");
  7704. ASSERT_TRUE(res);
  7705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7706. EXPECT_EQ("helloworld", res->body);
  7707. }
  7708. TEST(LongPollingTest, ClientCloseDetection) {
  7709. Server svr;
  7710. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7711. res.set_chunked_content_provider(
  7712. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7713. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7714. sink.os << "hello";
  7715. auto count = 10;
  7716. while (count > 0 && sink.is_writable()) {
  7717. this_thread::sleep_for(chrono::milliseconds(10));
  7718. count--;
  7719. }
  7720. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7721. return true;
  7722. });
  7723. });
  7724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7725. auto se = detail::scope_exit([&] {
  7726. svr.stop();
  7727. listen_thread.join();
  7728. ASSERT_FALSE(svr.is_running());
  7729. });
  7730. svr.wait_until_ready();
  7731. Client cli("localhost", PORT);
  7732. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7733. EXPECT_EQ("hello", string(data, data_length));
  7734. return false; // close the socket immediately.
  7735. });
  7736. ASSERT_FALSE(res);
  7737. }
  7738. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7739. Server svr;
  7740. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7741. res.set_chunked_content_provider(
  7742. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7743. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7744. sink.os << "hello";
  7745. EXPECT_TRUE(sink.os.good());
  7746. // Wait for the client to close the connection
  7747. auto count = 10;
  7748. while (count > 0 && sink.is_writable()) {
  7749. this_thread::sleep_for(chrono::milliseconds(10));
  7750. count--;
  7751. }
  7752. // After client disconnect, write repeatedly until the socket
  7753. // write actually fails (small writes may be absorbed by the
  7754. // kernel buffer)
  7755. std::string chunk(1024, 'x');
  7756. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7757. sink.os << chunk;
  7758. }
  7759. EXPECT_TRUE(sink.os.fail());
  7760. return true;
  7761. });
  7762. });
  7763. auto port = svr.bind_to_any_port("localhost");
  7764. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7765. auto se = detail::scope_exit([&] {
  7766. svr.stop();
  7767. listen_thread.join();
  7768. ASSERT_FALSE(svr.is_running());
  7769. });
  7770. svr.wait_until_ready();
  7771. Client cli("localhost", port);
  7772. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7773. EXPECT_EQ("hello", string(data, data_length));
  7774. return false; // close the socket immediately.
  7775. });
  7776. ASSERT_FALSE(res);
  7777. }
  7778. TEST(GetWithParametersTest, GetWithParameters) {
  7779. Server svr;
  7780. svr.Get("/", [&](const Request &req, Response &) {
  7781. EXPECT_EQ("world", req.get_param_value("hello"));
  7782. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7783. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7784. });
  7785. svr.Get("/params", [&](const Request &req, Response &) {
  7786. EXPECT_EQ("world", req.get_param_value("hello"));
  7787. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7788. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7789. });
  7790. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7791. EXPECT_EQ("resource-id", req.matches[1]);
  7792. EXPECT_EQ("foo", req.get_param_value("param1"));
  7793. EXPECT_EQ("bar", req.get_param_value("param2"));
  7794. });
  7795. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7796. EXPECT_EQ("user-id", req.path_params.at("id"));
  7797. EXPECT_EQ("foo", req.get_param_value("param1"));
  7798. EXPECT_EQ("bar", req.get_param_value("param2"));
  7799. });
  7800. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  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. {
  7808. Client cli(HOST, PORT);
  7809. Params params;
  7810. params.emplace("hello", "world");
  7811. params.emplace("hello2", "world2");
  7812. params.emplace("hello3", "world3");
  7813. auto res = cli.Get("/", params, Headers{});
  7814. ASSERT_TRUE(res);
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. }
  7817. {
  7818. Client cli(HOST, PORT);
  7819. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7820. ASSERT_TRUE(res);
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. }
  7823. {
  7824. Client cli(HOST, PORT);
  7825. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7826. ASSERT_TRUE(res);
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. }
  7829. {
  7830. Client cli(HOST, PORT);
  7831. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7832. ASSERT_TRUE(res);
  7833. EXPECT_EQ(StatusCode::OK_200, res->status);
  7834. }
  7835. }
  7836. TEST(GetWithParametersTest, GetWithParameters2) {
  7837. Server svr;
  7838. svr.Get("/", [&](const Request &req, Response &res) {
  7839. auto text = req.get_param_value("hello");
  7840. res.set_content(text, "text/plain");
  7841. });
  7842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7843. auto se = detail::scope_exit([&] {
  7844. svr.stop();
  7845. listen_thread.join();
  7846. ASSERT_FALSE(svr.is_running());
  7847. });
  7848. svr.wait_until_ready();
  7849. Client cli("localhost", PORT);
  7850. Params params;
  7851. params.emplace("hello", "world");
  7852. std::string body;
  7853. auto res = cli.Get("/", params, Headers{},
  7854. [&](const char *data, size_t data_length) {
  7855. body.append(data, data_length);
  7856. return true;
  7857. });
  7858. ASSERT_TRUE(res);
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. EXPECT_EQ("world", body);
  7861. }
  7862. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7863. Server svr;
  7864. svr.Get("/search", [&](const Request &req, Response &res) {
  7865. auto q = req.get_param_value("q");
  7866. res.set_content(q, "text/plain");
  7867. });
  7868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7869. auto se = detail::scope_exit([&] {
  7870. svr.stop();
  7871. listen_thread.join();
  7872. ASSERT_FALSE(svr.is_running());
  7873. });
  7874. svr.wait_until_ready();
  7875. Client cli("localhost", PORT);
  7876. // Verify that Get(path, params) works without requiring Headers argument
  7877. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7878. ASSERT_TRUE(res);
  7879. EXPECT_EQ(StatusCode::OK_200, res->status);
  7880. EXPECT_EQ("cpp-httplib", res->body);
  7881. }
  7882. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7883. auto host = "httpbingo.org";
  7884. auto path = std::string{"/range/32"};
  7885. #ifdef CPPHTTPLIB_SSL_ENABLED
  7886. SSLClient cli(host);
  7887. #else
  7888. Client cli(host);
  7889. #endif
  7890. cli.set_default_headers({make_range_header({{1, 10}})});
  7891. cli.set_connection_timeout(5);
  7892. {
  7893. auto res = cli.Get(path);
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ("bcdefghijk", res->body);
  7896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7897. }
  7898. {
  7899. auto res = cli.Get(path);
  7900. ASSERT_TRUE(res);
  7901. EXPECT_EQ("bcdefghijk", res->body);
  7902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7903. }
  7904. }
  7905. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7906. Server svr;
  7907. svr.set_default_headers({{"Hello", "World"}});
  7908. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7909. res.set_content("ok", "text/plain");
  7910. });
  7911. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7912. auto se = detail::scope_exit([&] {
  7913. svr.stop();
  7914. listen_thread.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. Client cli("localhost", PORT);
  7919. auto res = cli.Get("/");
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("ok", res->body);
  7923. EXPECT_EQ("World", res->get_header_value("Hello"));
  7924. }
  7925. #ifdef CPPHTTPLIB_SSL_ENABLED
  7926. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7928. ASSERT_TRUE(svr.is_valid());
  7929. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7930. std::this_thread::sleep_for(std::chrono::seconds(2));
  7931. res.set_content("a", "text/plain");
  7932. });
  7933. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7934. res.set_content("b", "text/plain");
  7935. });
  7936. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7937. auto se = detail::scope_exit([&] {
  7938. svr.stop();
  7939. listen_thread.join();
  7940. ASSERT_FALSE(svr.is_running());
  7941. });
  7942. svr.wait_until_ready();
  7943. SSLClient cli("localhost", PORT);
  7944. cli.enable_server_certificate_verification(false);
  7945. cli.set_keep_alive(true);
  7946. cli.set_read_timeout(std::chrono::seconds(1));
  7947. auto resa = cli.Get("/a");
  7948. ASSERT_TRUE(!resa);
  7949. EXPECT_EQ(Error::Read, resa.error());
  7950. auto resb = cli.Get("/b");
  7951. ASSERT_TRUE(resb);
  7952. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7953. EXPECT_EQ("b", resb->body);
  7954. }
  7955. #endif
  7956. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7957. protected:
  7958. ServerTestWithAI_PASSIVE()
  7959. : cli_(HOST, PORT)
  7960. #ifdef CPPHTTPLIB_SSL_ENABLED
  7961. ,
  7962. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7963. #endif
  7964. {
  7965. #ifdef CPPHTTPLIB_SSL_ENABLED
  7966. cli_.enable_server_certificate_verification(false);
  7967. #endif
  7968. }
  7969. virtual void SetUp() {
  7970. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7971. res.set_content("Hello World!", "text/plain");
  7972. });
  7973. t_ = thread(
  7974. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7975. svr_.wait_until_ready();
  7976. }
  7977. virtual void TearDown() {
  7978. svr_.stop();
  7979. t_.join();
  7980. }
  7981. #ifdef CPPHTTPLIB_SSL_ENABLED
  7982. SSLClient cli_;
  7983. SSLServer svr_;
  7984. #else
  7985. Client cli_;
  7986. Server svr_;
  7987. #endif
  7988. thread t_;
  7989. };
  7990. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7991. auto res = cli_.Get("/hi");
  7992. ASSERT_TRUE(res);
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7995. EXPECT_EQ("Hello World!", res->body);
  7996. }
  7997. class ServerUpDownTest : public ::testing::Test {
  7998. protected:
  7999. ServerUpDownTest() : cli_(HOST, PORT) {}
  8000. virtual void SetUp() {
  8001. t_ = thread([&]() {
  8002. svr_.bind_to_any_port(HOST);
  8003. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8004. ASSERT_TRUE(svr_.listen_after_bind());
  8005. });
  8006. svr_.wait_until_ready();
  8007. }
  8008. virtual void TearDown() {
  8009. svr_.stop();
  8010. t_.join();
  8011. }
  8012. Client cli_;
  8013. Server svr_;
  8014. thread t_;
  8015. };
  8016. TEST_F(ServerUpDownTest, QuickStartStop) {
  8017. // Should not crash, especially when run with
  8018. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8019. }
  8020. class PayloadMaxLengthTest : public ::testing::Test {
  8021. protected:
  8022. PayloadMaxLengthTest()
  8023. : cli_(HOST, PORT)
  8024. #ifdef CPPHTTPLIB_SSL_ENABLED
  8025. ,
  8026. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8027. #endif
  8028. {
  8029. #ifdef CPPHTTPLIB_SSL_ENABLED
  8030. cli_.enable_server_certificate_verification(false);
  8031. #endif
  8032. }
  8033. virtual void SetUp() {
  8034. svr_.set_payload_max_length(8);
  8035. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8036. res.set_content("test", "text/plain");
  8037. });
  8038. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8039. svr_.wait_until_ready();
  8040. }
  8041. virtual void TearDown() {
  8042. svr_.stop();
  8043. t_.join();
  8044. }
  8045. #ifdef CPPHTTPLIB_SSL_ENABLED
  8046. SSLClient cli_;
  8047. SSLServer svr_;
  8048. #else
  8049. Client cli_;
  8050. Server svr_;
  8051. #endif
  8052. thread t_;
  8053. };
  8054. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8055. auto res = cli_.Post("/test", "123456789", "text/plain");
  8056. ASSERT_TRUE(res);
  8057. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8058. res = cli_.Post("/test", "12345678", "text/plain");
  8059. ASSERT_TRUE(res);
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. }
  8062. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8063. // Test chunked encoding with payload exceeding the 8-byte limit
  8064. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8065. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8066. ASSERT_TRUE(res);
  8067. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8068. }
  8069. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8070. // Test chunked encoding with payload within the 8-byte limit
  8071. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8072. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8073. ASSERT_TRUE(res);
  8074. EXPECT_EQ(StatusCode::OK_200, res->status);
  8075. }
  8076. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8077. // Test using send_request to send chunked data exceeding payload limit
  8078. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8079. "Host: " +
  8080. std::string(HOST) + ":" + std::to_string(PORT) +
  8081. "\r\n"
  8082. "Transfer-Encoding: chunked\r\n"
  8083. "Connection: close\r\n"
  8084. "\r\n"
  8085. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8086. "0123456789\r\n"
  8087. "0\r\n" // End chunk
  8088. "\r\n";
  8089. std::string response;
  8090. bool result = send_request(1, chunked_request, &response);
  8091. if (!result) {
  8092. // If send_request fails, it might be because the server closed the
  8093. // connection due to payload limit enforcement, which is acceptable
  8094. SUCCEED()
  8095. << "Server rejected oversized chunked request (connection closed)";
  8096. } else {
  8097. // If we got a response, check if it's an error response or connection was
  8098. // closed early Short response length indicates connection was closed due to
  8099. // payload limit
  8100. if (response.length() <= 10) {
  8101. SUCCEED() << "Server closed connection for oversized chunked request";
  8102. } else {
  8103. // Check for error status codes
  8104. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8105. response.find("Payload Too Large") != std::string::npos ||
  8106. response.find("400") != std::string::npos);
  8107. }
  8108. }
  8109. }
  8110. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8111. // Test request without Content-Length header exceeding payload limit
  8112. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8113. "Host: " +
  8114. std::string(HOST) + ":" +
  8115. std::to_string(PORT) +
  8116. "\r\n"
  8117. "Connection: close\r\n"
  8118. "\r\n";
  8119. // Add payload exceeding the 8-byte limit
  8120. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8121. request_without_content_length += large_payload;
  8122. std::string response;
  8123. bool result = send_request(1, request_without_content_length, &response);
  8124. if (!result) {
  8125. // If send_request fails, server likely closed connection due to payload
  8126. // limit
  8127. SUCCEED() << "Server rejected oversized request without Content-Length "
  8128. "(connection closed)";
  8129. } else {
  8130. // Check if server responded with error or closed connection early
  8131. if (response.length() <= 10) {
  8132. SUCCEED() << "Server closed connection for oversized request without "
  8133. "Content-Length";
  8134. } else {
  8135. // Check for error status codes
  8136. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8137. response.find("Payload Too Large") != std::string::npos ||
  8138. response.find("400") != std::string::npos);
  8139. }
  8140. }
  8141. }
  8142. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8143. // Test request without Content-Length header within payload limit
  8144. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8145. "Host: " +
  8146. std::string(HOST) + ":" +
  8147. std::to_string(PORT) +
  8148. "\r\n"
  8149. "Connection: close\r\n"
  8150. "\r\n";
  8151. // Add payload within the 8-byte limit
  8152. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8153. request_without_content_length += small_payload;
  8154. std::string response;
  8155. bool result = send_request(1, request_without_content_length, &response);
  8156. // For requests without Content-Length, the server may have different behavior
  8157. // The key is that it should not reject due to payload limit for small
  8158. // payloads
  8159. if (result) {
  8160. // Check for any HTTP response (success or error, but not connection closed)
  8161. if (response.length() > 10) {
  8162. SUCCEED()
  8163. << "Server processed request without Content-Length within limit";
  8164. } else {
  8165. // Short response might indicate connection closed, which is acceptable
  8166. SUCCEED() << "Server closed connection for request without "
  8167. "Content-Length (acceptable behavior)";
  8168. }
  8169. } else {
  8170. // Connection failure might be due to protocol requirements
  8171. SUCCEED() << "Connection issue with request without Content-Length "
  8172. "(environment-specific)";
  8173. }
  8174. }
  8175. class LargePayloadMaxLengthTest : public ::testing::Test {
  8176. protected:
  8177. LargePayloadMaxLengthTest()
  8178. : cli_(HOST, PORT)
  8179. #ifdef CPPHTTPLIB_SSL_ENABLED
  8180. ,
  8181. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8182. #endif
  8183. {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. cli_.enable_server_certificate_verification(false);
  8186. #endif
  8187. }
  8188. virtual void SetUp() {
  8189. // Set 10MB payload limit
  8190. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8191. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8192. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8193. res.set_content("Large payload test", "text/plain");
  8194. });
  8195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8196. svr_.wait_until_ready();
  8197. }
  8198. virtual void TearDown() {
  8199. svr_.stop();
  8200. t_.join();
  8201. }
  8202. #ifdef CPPHTTPLIB_SSL_ENABLED
  8203. SSLClient cli_;
  8204. SSLServer svr_;
  8205. #else
  8206. Client cli_;
  8207. Server svr_;
  8208. #endif
  8209. thread t_;
  8210. };
  8211. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8212. // Test chunked encoding with payload within 10MB limit
  8213. std::string medium_payload(5 * 1024 * 1024,
  8214. 'A'); // 5MB payload, within 10MB limit
  8215. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8216. ASSERT_TRUE(res);
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. }
  8219. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8220. // Test chunked encoding with payload exceeding 10MB limit
  8221. std::string large_payload(12 * 1024 * 1024,
  8222. 'B'); // 12MB payload, exceeds 10MB limit
  8223. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8224. // Server may either return 413 or close the connection
  8225. if (res) {
  8226. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8227. } else {
  8228. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8229. }
  8230. }
  8231. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8232. // Test request without Content-Length header within 10MB limit
  8233. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8234. "Host: " +
  8235. std::string(HOST) + ":" +
  8236. std::to_string(PORT) +
  8237. "\r\n"
  8238. "Connection: close\r\n"
  8239. "\r\n";
  8240. // Add 1MB payload (within 10MB limit)
  8241. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8242. request_without_content_length += medium_payload;
  8243. std::string response;
  8244. bool result = send_request(5, request_without_content_length, &response);
  8245. if (result) {
  8246. // Should get a proper HTTP response for payloads within limit
  8247. if (response.length() > 10) {
  8248. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8249. "10MB limit";
  8250. } else {
  8251. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8252. "Content-Length)";
  8253. }
  8254. } else {
  8255. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8256. }
  8257. }
  8258. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8259. // Test request without Content-Length header exceeding 10MB limit
  8260. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8261. "Host: " +
  8262. std::string(HOST) + ":" +
  8263. std::to_string(PORT) +
  8264. "\r\n"
  8265. "Connection: close\r\n"
  8266. "\r\n";
  8267. // Add 12MB payload (exceeds 10MB limit)
  8268. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8269. request_without_content_length += large_payload;
  8270. std::string response;
  8271. bool result = send_request(10, request_without_content_length, &response);
  8272. if (!result) {
  8273. // Server should close connection due to payload limit
  8274. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8275. "(connection closed)";
  8276. } else {
  8277. // Check for error response
  8278. if (response.length() <= 10) {
  8279. SUCCEED()
  8280. << "Server closed connection for 12MB request exceeding 10MB limit";
  8281. } else {
  8282. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8283. response.find("Payload Too Large") != std::string::npos ||
  8284. response.find("400") != std::string::npos);
  8285. }
  8286. }
  8287. }
  8288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8289. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8290. // path.
  8291. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8292. Server svr;
  8293. const size_t LIMIT = 64 * 1024; // 64KB
  8294. svr.set_payload_max_length(LIMIT);
  8295. size_t total = 0;
  8296. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8297. const ContentReader &content_reader) {
  8298. content_reader([&](const char * /*data*/, size_t len) {
  8299. total += len;
  8300. return true;
  8301. });
  8302. res.status = 200;
  8303. res.set_content("stream_ok", "text/plain");
  8304. });
  8305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8306. auto se = detail::scope_exit([&] {
  8307. svr.stop();
  8308. thread.join();
  8309. ASSERT_FALSE(svr.is_running());
  8310. });
  8311. svr.wait_until_ready();
  8312. // Prepare 256KB raw data and gzip-compress it
  8313. std::string raw(256 * 1024, 'A');
  8314. std::string gz;
  8315. {
  8316. z_stream zs{};
  8317. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8318. Z_DEFAULT_STRATEGY);
  8319. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8320. zs.avail_in = static_cast<uInt>(raw.size());
  8321. char outbuf[4096];
  8322. int ret;
  8323. do {
  8324. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8325. zs.avail_out = sizeof(outbuf);
  8326. ret = deflate(&zs, Z_FINISH);
  8327. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8328. } while (ret != Z_STREAM_END);
  8329. deflateEnd(&zs);
  8330. }
  8331. Client cli(HOST, PORT);
  8332. cli.set_connection_timeout(std::chrono::seconds(5));
  8333. Headers headers = {{"Content-Encoding", "gzip"}};
  8334. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8335. "application/octet-stream");
  8336. ASSERT_TRUE(res);
  8337. // Server must reject oversized decompressed payloads with 413.
  8338. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8339. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8340. EXPECT_LE(total, LIMIT);
  8341. }
  8342. #endif
  8343. // Regression test for DoS vulnerability: a malicious server sending a response
  8344. // without Content-Length header must not cause unbounded memory consumption on
  8345. // the client side. The client should stop reading after a reasonable limit,
  8346. // similar to the server-side set_payload_max_length protection.
  8347. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8348. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8349. #ifndef _WIN32
  8350. signal(SIGPIPE, SIG_IGN);
  8351. #endif
  8352. auto server_thread = std::thread([] {
  8353. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8354. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8355. default_socket_options(srv);
  8356. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8357. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8358. sockaddr_in addr{};
  8359. addr.sin_family = AF_INET;
  8360. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8361. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8362. int opt = 1;
  8363. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8364. #ifdef _WIN32
  8365. reinterpret_cast<const char *>(&opt),
  8366. #else
  8367. &opt,
  8368. #endif
  8369. sizeof(opt));
  8370. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8371. ::listen(srv, 1);
  8372. sockaddr_in cli_addr{};
  8373. socklen_t cli_len = sizeof(cli_addr);
  8374. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8375. if (cli != INVALID_SOCKET) {
  8376. char buf[4096];
  8377. ::recv(cli, buf, sizeof(buf), 0);
  8378. // Malicious response: no Content-Length, no chunked encoding
  8379. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8380. "Connection: close\r\n"
  8381. "\r\n";
  8382. ::send(cli,
  8383. #ifdef _WIN32
  8384. static_cast<const char *>(response_header.c_str()),
  8385. static_cast<int>(response_header.size()),
  8386. #else
  8387. response_header.c_str(), response_header.size(),
  8388. #endif
  8389. 0);
  8390. // Send 10MB of data
  8391. std::string chunk(64 * 1024, 'A');
  8392. size_t total_sent = 0;
  8393. while (total_sent < MALICIOUS_DATA_SIZE) {
  8394. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8395. auto sent = ::send(cli,
  8396. #ifdef _WIN32
  8397. static_cast<const char *>(chunk.c_str()),
  8398. static_cast<int>(to_send),
  8399. #else
  8400. chunk.c_str(), to_send,
  8401. #endif
  8402. 0);
  8403. if (sent <= 0) break;
  8404. total_sent += static_cast<size_t>(sent);
  8405. }
  8406. detail::close_socket(cli);
  8407. }
  8408. detail::close_socket(srv);
  8409. });
  8410. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8411. size_t total_read = 0;
  8412. {
  8413. Client cli("127.0.0.1", PORT + 2);
  8414. cli.set_read_timeout(5, 0);
  8415. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8416. auto stream = cli.open_stream("GET", "/malicious");
  8417. ASSERT_TRUE(stream.is_valid());
  8418. char buffer[64 * 1024];
  8419. ssize_t n;
  8420. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8421. total_read += static_cast<size_t>(n);
  8422. }
  8423. } // StreamHandle and Client destroyed here, closing the socket
  8424. server_thread.join();
  8425. // With set_payload_max_length, the client must stop reading before consuming
  8426. // all 10MB. The read loop should be cut off at or near the configured limit.
  8427. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8428. << "Client read " << total_read << " bytes, exceeding the configured "
  8429. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8430. }
  8431. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8432. // the entire response body without truncation.
  8433. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8434. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8435. #ifndef _WIN32
  8436. signal(SIGPIPE, SIG_IGN);
  8437. #endif
  8438. auto server_thread = std::thread([] {
  8439. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8440. default_socket_options(srv);
  8441. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8442. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8443. sockaddr_in addr{};
  8444. addr.sin_family = AF_INET;
  8445. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8447. int opt = 1;
  8448. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8449. #ifdef _WIN32
  8450. reinterpret_cast<const char *>(&opt),
  8451. #else
  8452. &opt,
  8453. #endif
  8454. sizeof(opt));
  8455. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8456. ::listen(srv, 1);
  8457. sockaddr_in cli_addr{};
  8458. socklen_t cli_len = sizeof(cli_addr);
  8459. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8460. if (cli != INVALID_SOCKET) {
  8461. char buf[4096];
  8462. ::recv(cli, buf, sizeof(buf), 0);
  8463. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8464. "Connection: close\r\n"
  8465. "\r\n";
  8466. ::send(cli,
  8467. #ifdef _WIN32
  8468. static_cast<const char *>(response_header.c_str()),
  8469. static_cast<int>(response_header.size()),
  8470. #else
  8471. response_header.c_str(), response_header.size(),
  8472. #endif
  8473. 0);
  8474. std::string chunk(64 * 1024, 'A');
  8475. size_t total_sent = 0;
  8476. while (total_sent < DATA_SIZE) {
  8477. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8478. auto sent = ::send(cli,
  8479. #ifdef _WIN32
  8480. static_cast<const char *>(chunk.c_str()),
  8481. static_cast<int>(to_send),
  8482. #else
  8483. chunk.c_str(), to_send,
  8484. #endif
  8485. 0);
  8486. if (sent <= 0) break;
  8487. total_sent += static_cast<size_t>(sent);
  8488. }
  8489. #ifdef _WIN32
  8490. ::shutdown(cli, SD_SEND);
  8491. #else
  8492. ::shutdown(cli, SHUT_WR);
  8493. #endif
  8494. // Drain until the client closes its end, ensuring all data is delivered
  8495. char drain[1024];
  8496. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8497. detail::close_socket(cli);
  8498. }
  8499. detail::close_socket(srv);
  8500. });
  8501. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8502. size_t total_read = 0;
  8503. {
  8504. Client cli("127.0.0.1", PORT + 2);
  8505. cli.set_read_timeout(5, 0);
  8506. cli.set_payload_max_length(0); // 0 means no limit
  8507. auto stream = cli.open_stream("GET", "/data");
  8508. ASSERT_TRUE(stream.is_valid());
  8509. char buffer[64 * 1024];
  8510. ssize_t n;
  8511. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8512. total_read += static_cast<size_t>(n);
  8513. }
  8514. }
  8515. server_thread.join();
  8516. EXPECT_EQ(total_read, DATA_SIZE)
  8517. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8518. << " bytes without truncation, but only read " << total_read << " bytes.";
  8519. }
  8520. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8521. // enormous Content-Length must not cause the client to pre-allocate a huge
  8522. // response body buffer. The reservation is capped at payload_max_length_, and
  8523. // the read itself fails when the body exceeds the limit.
  8524. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8525. #ifndef _WIN32
  8526. signal(SIGPIPE, SIG_IGN);
  8527. #endif
  8528. auto server_thread = std::thread([] {
  8529. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8530. default_socket_options(srv);
  8531. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8532. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8533. sockaddr_in addr{};
  8534. addr.sin_family = AF_INET;
  8535. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8536. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8537. int opt = 1;
  8538. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8539. #ifdef _WIN32
  8540. reinterpret_cast<const char *>(&opt),
  8541. #else
  8542. &opt,
  8543. #endif
  8544. sizeof(opt));
  8545. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8546. ::listen(srv, 1);
  8547. sockaddr_in cli_addr{};
  8548. socklen_t cli_len = sizeof(cli_addr);
  8549. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8550. if (cli != INVALID_SOCKET) {
  8551. char buf[4096];
  8552. ::recv(cli, buf, sizeof(buf), 0);
  8553. // Malicious response: claim a 20GB body but send only a tiny payload.
  8554. std::string response = "HTTP/1.1 200 OK\r\n"
  8555. "Content-Length: 20000000000\r\n"
  8556. "\r\n"
  8557. "abc";
  8558. ::send(cli,
  8559. #ifdef _WIN32
  8560. static_cast<const char *>(response.c_str()),
  8561. static_cast<int>(response.size()),
  8562. #else
  8563. response.c_str(), response.size(),
  8564. #endif
  8565. 0);
  8566. detail::close_socket(cli);
  8567. }
  8568. detail::close_socket(srv);
  8569. });
  8570. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8571. {
  8572. Client cli("127.0.0.1", PORT + 2);
  8573. cli.set_read_timeout(5, 0);
  8574. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8575. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8576. // (server claims more bytes than payload_max_length permits), but it must
  8577. // not exhaust memory before getting there.
  8578. auto res = cli.Get("/malicious");
  8579. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8580. }
  8581. server_thread.join();
  8582. }
  8583. // Verify that content_receiver bypasses the default payload_max_length,
  8584. // allowing streaming downloads larger than 100MB without requiring an explicit
  8585. // set_payload_max_length call.
  8586. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8587. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8588. #ifndef _WIN32
  8589. signal(SIGPIPE, SIG_IGN);
  8590. #endif
  8591. auto server_thread = std::thread([] {
  8592. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8593. default_socket_options(srv);
  8594. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8595. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8596. sockaddr_in addr{};
  8597. addr.sin_family = AF_INET;
  8598. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8599. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8600. int opt = 1;
  8601. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8602. #ifdef _WIN32
  8603. reinterpret_cast<const char *>(&opt),
  8604. #else
  8605. &opt,
  8606. #endif
  8607. sizeof(opt));
  8608. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8609. ::listen(srv, 1);
  8610. sockaddr_in cli_addr{};
  8611. socklen_t cli_len = sizeof(cli_addr);
  8612. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8613. if (cli != INVALID_SOCKET) {
  8614. char buf[4096];
  8615. ::recv(cli, buf, sizeof(buf), 0);
  8616. // Response with Content-Length larger than default 100MB limit
  8617. auto content_length = std::to_string(DATA_SIZE);
  8618. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8619. "Content-Length: " +
  8620. content_length +
  8621. "\r\n"
  8622. "Connection: close\r\n"
  8623. "\r\n";
  8624. ::send(cli,
  8625. #ifdef _WIN32
  8626. static_cast<const char *>(response_header.c_str()),
  8627. static_cast<int>(response_header.size()),
  8628. #else
  8629. response_header.c_str(), response_header.size(),
  8630. #endif
  8631. 0);
  8632. std::string chunk(64 * 1024, 'A');
  8633. size_t total_sent = 0;
  8634. while (total_sent < DATA_SIZE) {
  8635. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8636. auto sent = ::send(cli,
  8637. #ifdef _WIN32
  8638. static_cast<const char *>(chunk.c_str()),
  8639. static_cast<int>(to_send),
  8640. #else
  8641. chunk.c_str(), to_send,
  8642. #endif
  8643. 0);
  8644. if (sent <= 0) break;
  8645. total_sent += static_cast<size_t>(sent);
  8646. }
  8647. detail::close_socket(cli);
  8648. }
  8649. detail::close_socket(srv);
  8650. });
  8651. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8652. size_t total_received = 0;
  8653. {
  8654. Client cli("127.0.0.1", PORT + 2);
  8655. cli.set_read_timeout(10, 0);
  8656. // Do NOT call set_payload_max_length — use the default 100MB limit
  8657. auto res =
  8658. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8659. total_received += data_length;
  8660. return true;
  8661. });
  8662. ASSERT_TRUE(res);
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. }
  8665. server_thread.join();
  8666. EXPECT_EQ(total_received, DATA_SIZE)
  8667. << "With content_receiver, the client should read all " << DATA_SIZE
  8668. << " bytes despite the default 100MB payload_max_length, but only read "
  8669. << total_received << " bytes.";
  8670. }
  8671. // Verify that an explicit set_payload_max_length smaller than the response is
  8672. // enforced even when a content_receiver is used.
  8673. TEST(ClientVulnerabilityTest,
  8674. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8675. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8676. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8677. #ifndef _WIN32
  8678. signal(SIGPIPE, SIG_IGN);
  8679. #endif
  8680. auto server_thread = std::thread([] {
  8681. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8682. default_socket_options(srv);
  8683. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8684. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8685. sockaddr_in addr{};
  8686. addr.sin_family = AF_INET;
  8687. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8688. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8689. int opt = 1;
  8690. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8691. #ifdef _WIN32
  8692. reinterpret_cast<const char *>(&opt),
  8693. #else
  8694. &opt,
  8695. #endif
  8696. sizeof(opt));
  8697. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8698. ::listen(srv, 1);
  8699. sockaddr_in cli_addr{};
  8700. socklen_t cli_len = sizeof(cli_addr);
  8701. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8702. if (cli != INVALID_SOCKET) {
  8703. char buf[4096];
  8704. ::recv(cli, buf, sizeof(buf), 0);
  8705. auto content_length = std::to_string(DATA_SIZE);
  8706. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8707. "Content-Length: " +
  8708. content_length +
  8709. "\r\n"
  8710. "Connection: close\r\n"
  8711. "\r\n";
  8712. ::send(cli,
  8713. #ifdef _WIN32
  8714. static_cast<const char *>(response_header.c_str()),
  8715. static_cast<int>(response_header.size()),
  8716. #else
  8717. response_header.c_str(), response_header.size(),
  8718. #endif
  8719. 0);
  8720. std::string chunk(64 * 1024, 'A');
  8721. size_t total_sent = 0;
  8722. while (total_sent < DATA_SIZE) {
  8723. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8724. auto sent = ::send(cli,
  8725. #ifdef _WIN32
  8726. static_cast<const char *>(chunk.c_str()),
  8727. static_cast<int>(to_send),
  8728. #else
  8729. chunk.c_str(), to_send,
  8730. #endif
  8731. 0);
  8732. if (sent <= 0) break;
  8733. total_sent += static_cast<size_t>(sent);
  8734. }
  8735. detail::close_socket(cli);
  8736. }
  8737. detail::close_socket(srv);
  8738. });
  8739. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8740. size_t total_received = 0;
  8741. {
  8742. Client cli("127.0.0.1", PORT + 2);
  8743. cli.set_read_timeout(10, 0);
  8744. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8745. auto res =
  8746. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8747. total_received += data_length;
  8748. return true;
  8749. });
  8750. // Should fail because 200MB exceeds the explicit 150MB limit
  8751. EXPECT_FALSE(res);
  8752. }
  8753. server_thread.join();
  8754. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8755. << "Client with content_receiver should respect the explicit "
  8756. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8757. << total_received << " bytes.";
  8758. }
  8759. // Verify that an explicit set_payload_max_length larger than the response
  8760. // allows the content_receiver to read all data successfully.
  8761. TEST(ClientVulnerabilityTest,
  8762. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8763. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8764. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8765. #ifndef _WIN32
  8766. signal(SIGPIPE, SIG_IGN);
  8767. #endif
  8768. auto server_thread = std::thread([] {
  8769. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8770. default_socket_options(srv);
  8771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8772. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8773. sockaddr_in addr{};
  8774. addr.sin_family = AF_INET;
  8775. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8776. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8777. int opt = 1;
  8778. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8779. #ifdef _WIN32
  8780. reinterpret_cast<const char *>(&opt),
  8781. #else
  8782. &opt,
  8783. #endif
  8784. sizeof(opt));
  8785. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8786. ::listen(srv, 1);
  8787. sockaddr_in cli_addr{};
  8788. socklen_t cli_len = sizeof(cli_addr);
  8789. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8790. if (cli != INVALID_SOCKET) {
  8791. char buf[4096];
  8792. ::recv(cli, buf, sizeof(buf), 0);
  8793. auto content_length = std::to_string(DATA_SIZE);
  8794. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8795. "Content-Length: " +
  8796. content_length +
  8797. "\r\n"
  8798. "Connection: close\r\n"
  8799. "\r\n";
  8800. ::send(cli,
  8801. #ifdef _WIN32
  8802. static_cast<const char *>(response_header.c_str()),
  8803. static_cast<int>(response_header.size()),
  8804. #else
  8805. response_header.c_str(), response_header.size(),
  8806. #endif
  8807. 0);
  8808. std::string chunk(64 * 1024, 'A');
  8809. size_t total_sent = 0;
  8810. while (total_sent < DATA_SIZE) {
  8811. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8812. auto sent = ::send(cli,
  8813. #ifdef _WIN32
  8814. static_cast<const char *>(chunk.c_str()),
  8815. static_cast<int>(to_send),
  8816. #else
  8817. chunk.c_str(), to_send,
  8818. #endif
  8819. 0);
  8820. if (sent <= 0) break;
  8821. total_sent += static_cast<size_t>(sent);
  8822. }
  8823. #ifdef _WIN32
  8824. ::shutdown(cli, SD_SEND);
  8825. #else
  8826. ::shutdown(cli, SHUT_WR);
  8827. #endif
  8828. char drain[1024];
  8829. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8830. detail::close_socket(cli);
  8831. }
  8832. detail::close_socket(srv);
  8833. });
  8834. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8835. size_t total_received = 0;
  8836. {
  8837. Client cli("127.0.0.1", PORT + 2);
  8838. cli.set_read_timeout(10, 0);
  8839. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8840. auto res =
  8841. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8842. total_received += data_length;
  8843. return true;
  8844. });
  8845. ASSERT_TRUE(res);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. server_thread.join();
  8849. EXPECT_EQ(total_received, DATA_SIZE)
  8850. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8851. << " bytes (larger than " << DATA_SIZE
  8852. << " bytes response), content_receiver should read all data, but only "
  8853. "read "
  8854. << total_received << " bytes.";
  8855. }
  8856. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8857. // Regression test for "zip bomb" attack on the client side: a malicious server
  8858. // sends a small gzip-compressed response that decompresses to a huge payload.
  8859. // The client must enforce payload_max_length on the decompressed size.
  8860. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8861. constexpr size_t DECOMPRESSED_SIZE =
  8862. 10 * 1024 * 1024; // 10MB after decompression
  8863. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8864. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8865. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8866. std::string compressed;
  8867. {
  8868. httplib::detail::gzip_compressor compressor;
  8869. bool ok =
  8870. compressor.compress(uncompressed.data(), uncompressed.size(),
  8871. /*last=*/true, [&](const char *buf, size_t len) {
  8872. compressed.append(buf, len);
  8873. return true;
  8874. });
  8875. ASSERT_TRUE(ok);
  8876. }
  8877. // Sanity: compressed data should be much smaller than the decompressed size
  8878. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8879. #ifndef _WIN32
  8880. signal(SIGPIPE, SIG_IGN);
  8881. #endif
  8882. // Set up the listening socket in the main thread so the server is guaranteed
  8883. // to be ready before the client connects (eliminates race condition).
  8884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8885. default_socket_options(srv);
  8886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8888. sockaddr_in addr{};
  8889. addr.sin_family = AF_INET;
  8890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8892. int opt = 1;
  8893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8894. #ifdef _WIN32
  8895. reinterpret_cast<const char *>(&opt),
  8896. #else
  8897. &opt,
  8898. #endif
  8899. sizeof(opt));
  8900. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8901. ASSERT_EQ(0, ::listen(srv, 1));
  8902. auto server_thread = std::thread([&compressed, srv] {
  8903. sockaddr_in cli_addr{};
  8904. socklen_t cli_len = sizeof(cli_addr);
  8905. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8906. if (cli != INVALID_SOCKET) {
  8907. // Read the full HTTP request (until \r\n\r\n)
  8908. char buf[4096];
  8909. size_t total = 0;
  8910. while (total < sizeof(buf)) {
  8911. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8912. if (n <= 0) break;
  8913. total += static_cast<size_t>(n);
  8914. // Check for end of headers
  8915. if (total >= 4) {
  8916. std::string req(buf, total);
  8917. if (req.find("\r\n\r\n") != std::string::npos) break;
  8918. }
  8919. }
  8920. // Malicious response: gzip-compressed body, no Content-Length
  8921. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8922. "Content-Encoding: gzip\r\n"
  8923. "Connection: close\r\n"
  8924. "\r\n";
  8925. ::send(cli,
  8926. #ifdef _WIN32
  8927. static_cast<const char *>(response_header.c_str()),
  8928. static_cast<int>(response_header.size()),
  8929. #else
  8930. response_header.c_str(), response_header.size(),
  8931. #endif
  8932. 0);
  8933. // Send the compressed payload (small on the wire, huge when decompressed)
  8934. size_t total_sent = 0;
  8935. while (total_sent < compressed.size()) {
  8936. auto to_send = std::min(compressed.size() - total_sent,
  8937. static_cast<size_t>(64 * 1024));
  8938. auto sent =
  8939. ::send(cli,
  8940. #ifdef _WIN32
  8941. static_cast<const char *>(compressed.c_str() + total_sent),
  8942. static_cast<int>(to_send),
  8943. #else
  8944. compressed.c_str() + total_sent, to_send,
  8945. #endif
  8946. 0);
  8947. if (sent <= 0) break;
  8948. total_sent += static_cast<size_t>(sent);
  8949. }
  8950. detail::close_socket(cli);
  8951. }
  8952. });
  8953. auto se = detail::scope_exit([&] {
  8954. detail::close_socket(srv);
  8955. server_thread.join();
  8956. });
  8957. size_t total_decompressed = 0;
  8958. {
  8959. Client cli("127.0.0.1", PORT + 3);
  8960. cli.set_read_timeout(5, 0);
  8961. cli.set_decompress(true);
  8962. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8963. auto stream = cli.open_stream("GET", "/zipbomb");
  8964. ASSERT_TRUE(stream.is_valid());
  8965. char buffer[64 * 1024];
  8966. ssize_t n;
  8967. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8968. total_decompressed += static_cast<size_t>(n);
  8969. }
  8970. }
  8971. // The decompressed size must be capped by payload_max_length. Without
  8972. // protection, the client would decompress the full 10MB from a tiny
  8973. // compressed payload, enabling a zip bomb DoS attack.
  8974. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8975. << "Client decompressed " << total_decompressed
  8976. << " bytes from a gzip response. The decompressed size should be "
  8977. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8978. }
  8979. #endif
  8980. TEST(HostAndPortPropertiesTest, NoSSL) {
  8981. httplib::Client cli("www.google.com", 1234);
  8982. ASSERT_EQ("www.google.com", cli.host());
  8983. ASSERT_EQ(1234, cli.port());
  8984. }
  8985. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8986. httplib::Client cli("www.google.com:1234");
  8987. ASSERT_EQ("www.google.com", cli.host());
  8988. ASSERT_EQ(1234, cli.port());
  8989. }
  8990. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8991. // Port number that overflows int — should not crash, client becomes invalid
  8992. httplib::Client cli("http://www.google.com:99999999999999999999");
  8993. ASSERT_FALSE(cli.is_valid());
  8994. }
  8995. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8996. // Port 99999 exceeds valid range (1-65535) — should not crash
  8997. httplib::Client cli("http://www.google.com:99999");
  8998. ASSERT_FALSE(cli.is_valid());
  8999. }
  9000. #ifdef CPPHTTPLIB_SSL_ENABLED
  9001. TEST(HostAndPortPropertiesTest, SSL) {
  9002. httplib::SSLClient cli("www.google.com");
  9003. ASSERT_EQ("www.google.com", cli.host());
  9004. ASSERT_EQ(443, cli.port());
  9005. }
  9006. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9007. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9008. std::string cert;
  9009. read_file(CA_CERT_FILE, cert);
  9010. httplib::SSLClient httplib_client("www.google.com");
  9011. // Load CA store first time
  9012. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9013. // Load CA store second time (update)
  9014. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9015. // Verify client is still valid and can make connections
  9016. httplib_client.enable_server_certificate_verification(true);
  9017. auto res = httplib_client.Get("/");
  9018. ASSERT_TRUE(res);
  9019. // Google may return 200 or 301 depending on various factors
  9020. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9021. res->status == StatusCode::MovedPermanently_301);
  9022. }
  9023. TEST(SSLClientTest, ServerNameIndication_Online) {
  9024. auto host = "httpbingo.org";
  9025. auto path = std::string{"/get"};
  9026. SSLClient cli(host, 443);
  9027. auto res = cli.Get(path);
  9028. ASSERT_TRUE(res);
  9029. ASSERT_EQ(StatusCode::OK_200, res->status);
  9030. }
  9031. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9032. // Use a site that will cause SSL verification failure due to self-signed cert
  9033. SSLClient cli("self-signed.badssl.com", 443);
  9034. cli.enable_server_certificate_verification(true);
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(!res);
  9037. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9038. // Verify backend error is captured for SSLServerVerification
  9039. // This occurs when certificate verification fails
  9040. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9041. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9042. EXPECT_NE(0UL, res.ssl_backend_error());
  9043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9044. // For OpenSSL, ssl_error is 0 for verification errors
  9045. EXPECT_EQ(0, res.ssl_error());
  9046. #if !defined(_WIN32) || \
  9047. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9048. // On non-Windows or when Windows Schannel is disabled, the error comes
  9049. // from OpenSSL's verification
  9050. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9051. res.ssl_backend_error());
  9052. #endif
  9053. #endif
  9054. }
  9055. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9056. // Use a site where hostname doesn't match the certificate
  9057. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9058. SSLClient cli("wrong.host.badssl.com", 443);
  9059. cli.enable_server_certificate_verification(true);
  9060. cli.enable_server_hostname_verification(true);
  9061. auto res = cli.Get("/");
  9062. ASSERT_TRUE(!res);
  9063. // The error type depends on when hostname verification occurs:
  9064. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9065. // - Mbed TLS: SSLServerVerification (during handshake)
  9066. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9067. res.error() == Error::SSLServerVerification);
  9068. // Verify backend error is captured for hostname verification failure
  9069. EXPECT_NE(0UL, res.ssl_backend_error());
  9070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9071. // For OpenSSL, ssl_error is 0 for verification errors
  9072. EXPECT_EQ(0, res.ssl_error());
  9073. #if !defined(_WIN32) || \
  9074. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9075. // On non-Windows or when Windows Schannel is disabled, the error comes
  9076. // from OpenSSL's hostname verification
  9077. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9078. res.ssl_backend_error());
  9079. #endif
  9080. #endif
  9081. }
  9082. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9083. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9084. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9085. SSLClient cli("www.google.com", 443);
  9086. cli.enable_server_certificate_verification(true);
  9087. auto res = cli.Get("/");
  9088. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9089. }
  9090. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9091. SSLClient cli("www.google.com", 443);
  9092. cli.enable_server_certificate_verification(true);
  9093. cli.enable_windows_certificate_verification(false);
  9094. auto res = cli.Get("/");
  9095. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9096. }
  9097. #endif
  9098. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9099. Client cli("https://google.com");
  9100. auto res = cli.Get("/");
  9101. ASSERT_TRUE(res);
  9102. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9103. }
  9104. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9105. SSLClient cli("google.com");
  9106. cli.set_ca_cert_path(CA_CERT_FILE);
  9107. auto res = cli.Get("/");
  9108. ASSERT_TRUE(res);
  9109. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9110. }
  9111. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9112. SSLClient cli("google.com");
  9113. cli.enable_server_certificate_verification(true);
  9114. cli.set_ca_cert_path("hello");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(!res);
  9117. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9118. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9119. // should be set
  9120. EXPECT_EQ(0, res.ssl_error());
  9121. // Verify backend error is captured for SSLLoadingCerts
  9122. // This error occurs when loading CA certificates fails
  9123. EXPECT_NE(0UL, res.ssl_backend_error());
  9124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9125. // OpenSSL specific error codes:
  9126. // > openssl errstr 0x80000002
  9127. // error:80000002:system library::No such file or directory
  9128. // > openssl errstr 0xA000126
  9129. // error:0A000126:SSL routines::unexpected eof while reading
  9130. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9131. res.ssl_backend_error() == 0xA000126);
  9132. #endif
  9133. }
  9134. TEST(SSLClientTest, ServerCertificateVerification4) {
  9135. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9136. ASSERT_TRUE(svr.is_valid());
  9137. svr.Get("/test", [&](const Request &, Response &res) {
  9138. res.set_content("test", "text/plain");
  9139. svr.stop();
  9140. ASSERT_TRUE(true);
  9141. });
  9142. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9143. auto se = detail::scope_exit([&] {
  9144. t.join();
  9145. ASSERT_FALSE(svr.is_running());
  9146. });
  9147. svr.wait_until_ready();
  9148. SSLClient cli("127.0.0.1", PORT);
  9149. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9150. cli.enable_server_certificate_verification(true);
  9151. cli.set_connection_timeout(30);
  9152. auto res = cli.Get("/test");
  9153. ASSERT_TRUE(res);
  9154. ASSERT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9157. std::string cert;
  9158. read_file(CA_CERT_FILE, cert);
  9159. SSLClient cli("google.com");
  9160. cli.load_ca_cert_store(cert.data(), cert.size());
  9161. const auto res = cli.Get("/");
  9162. ASSERT_TRUE(res);
  9163. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9164. }
  9165. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9166. // clang-format off
  9167. static constexpr char cert[] =
  9168. "GlobalSign Root CA\n"
  9169. "==================\n"
  9170. "-----BEGIN CERTIFICATE-----\n"
  9171. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9172. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9173. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9174. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9175. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9176. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9177. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9178. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9179. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9180. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9181. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9182. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9183. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9184. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9185. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9186. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9187. "-----END CERTIFICATE-----\n";
  9188. // clang-format on
  9189. SSLClient cli("google.com");
  9190. cli.load_ca_cert_store(cert, sizeof(cert));
  9191. const auto res = cli.Get("/");
  9192. ASSERT_TRUE(res);
  9193. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9194. }
  9195. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9196. SSLClient cli("www.youtube.com");
  9197. cli.set_ca_cert_path(CA_CERT_FILE);
  9198. cli.enable_server_certificate_verification(true);
  9199. cli.set_follow_location(true);
  9200. auto res = cli.Get("/");
  9201. ASSERT_TRUE(res);
  9202. ASSERT_EQ(StatusCode::OK_200, res->status);
  9203. }
  9204. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9205. SSLClient cli("wWw.YouTube.Com");
  9206. cli.set_ca_cert_path(CA_CERT_FILE);
  9207. cli.enable_server_certificate_verification(true);
  9208. cli.enable_server_hostname_verification(true);
  9209. cli.set_follow_location(true);
  9210. auto res = cli.Get("/");
  9211. ASSERT_TRUE(res);
  9212. ASSERT_EQ(StatusCode::OK_200, res->status);
  9213. }
  9214. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9215. SSLClient cli("gOoGlE.COm");
  9216. cli.enable_server_certificate_verification(true);
  9217. cli.enable_server_hostname_verification(true);
  9218. cli.set_follow_location(true);
  9219. auto res = cli.Get("/");
  9220. ASSERT_TRUE(res);
  9221. ASSERT_EQ(StatusCode::OK_200, res->status);
  9222. }
  9223. TEST(SSLClientTest, Issue2004_Online) {
  9224. Client client("https://google.com");
  9225. client.set_follow_location(true);
  9226. auto res = client.Get("/");
  9227. ASSERT_TRUE(res);
  9228. ASSERT_EQ(StatusCode::OK_200, res->status);
  9229. auto body = res->body;
  9230. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9231. }
  9232. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9233. // Create SSLClient with invalid cert/key to make is_valid() return false
  9234. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9235. "nonexistent_key.pem");
  9236. // is_valid() should be false due to cert loading failure
  9237. ASSERT_FALSE(cli.is_valid());
  9238. auto res = cli.Get("/");
  9239. ASSERT_FALSE(res);
  9240. EXPECT_EQ(Error::SSLConnection, res.error());
  9241. }
  9242. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9243. // Test for Issue #2251: SSL error not properly reported when client cert
  9244. // and key paths are swapped or mismatched
  9245. // This simulates the scenario where user accidentally swaps the cert and key
  9246. // files
  9247. // Using client cert file as private key and vice versa (completely wrong)
  9248. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9249. // Should fail validation due to cert/key mismatch
  9250. ASSERT_FALSE(cli.is_valid());
  9251. // Attempt to make a request should fail with proper error
  9252. auto res = cli.Get("/");
  9253. ASSERT_FALSE(res);
  9254. EXPECT_EQ(Error::SSLConnection, res.error());
  9255. // SSL error should be recorded in the Result object (this is the key fix for
  9256. // Issue #2251)
  9257. auto backend_error = res.ssl_backend_error();
  9258. EXPECT_NE(0u, backend_error);
  9259. }
  9260. // Tests cert/key mismatch detection at the TLS context level
  9261. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9262. // Test that using mismatched cert/key causes connection failure.
  9263. // We verify this at the SSLClient level rather than through internal
  9264. // TLS API functions.
  9265. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9266. cli.enable_server_certificate_verification(false);
  9267. cli.set_connection_timeout(2);
  9268. // The mismatch should cause a connection or handshake error
  9269. auto res = cli.Get("/test");
  9270. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9271. // Either way, the request should fail
  9272. EXPECT_FALSE(res);
  9273. }
  9274. #endif
  9275. #if 0
  9276. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9277. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9278. ASSERT_TRUE(cli != nullptr);
  9279. cli->set_address_family(AF_INET6);
  9280. cli->set_interface("en0");
  9281. auto res = cli->Get("/get");
  9282. ASSERT_TRUE(res);
  9283. ASSERT_EQ(StatusCode::OK_200, res->status);
  9284. }
  9285. #endif
  9286. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9287. #ifdef CPPHTTPLIB_SSL_ENABLED
  9288. void ClientCertPresent(
  9289. const std::string &client_cert_file,
  9290. const std::string &client_private_key_file,
  9291. const std::string &client_encrypted_private_key_pass = std::string()) {
  9292. using namespace httplib::tls;
  9293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9294. CLIENT_CA_CERT_DIR);
  9295. ASSERT_TRUE(svr.is_valid());
  9296. svr.Get("/test", [&](const Request &req, Response &res) {
  9297. res.set_content("test", "text/plain");
  9298. auto cert = req.peer_cert();
  9299. ASSERT_TRUE(static_cast<bool>(cert));
  9300. std::string common_name = cert.subject_cn();
  9301. EXPECT_EQ("Common Name", common_name);
  9302. });
  9303. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9304. auto se = detail::scope_exit([&] {
  9305. svr.stop();
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9311. client_encrypted_private_key_pass);
  9312. cli.enable_server_certificate_verification(false);
  9313. cli.set_connection_timeout(30);
  9314. auto res = cli.Get("/test");
  9315. ASSERT_TRUE(res);
  9316. ASSERT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST(SSLClientServerTest, ClientCertPresent) {
  9319. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9320. }
  9321. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9322. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9323. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9324. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9325. }
  9326. // PEM memory-based constructor tests (works with all TLS backends)
  9327. void PemMemoryClientCertPresent(
  9328. const std::string &client_cert_file,
  9329. const std::string &client_private_key_file,
  9330. const std::string &client_encrypted_private_key_pass = std::string()) {
  9331. // Read PEM files into memory
  9332. std::string server_cert_pem, server_key_pem;
  9333. std::string client_ca_pem;
  9334. std::string client_cert_pem, client_key_pem;
  9335. read_file(SERVER_CERT_FILE, server_cert_pem);
  9336. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9337. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9338. read_file(client_cert_file, client_cert_pem);
  9339. read_file(client_private_key_file, client_key_pem);
  9340. // Create server with PEM memory
  9341. SSLServer::PemMemory server_pem = {
  9342. server_cert_pem.c_str(),
  9343. server_cert_pem.size(),
  9344. server_key_pem.c_str(),
  9345. server_key_pem.size(),
  9346. client_ca_pem.c_str(),
  9347. client_ca_pem.size(),
  9348. nullptr // no password for server key
  9349. };
  9350. SSLServer svr(server_pem);
  9351. ASSERT_TRUE(svr.is_valid());
  9352. svr.Get("/test", [&](const Request &, Response &res) {
  9353. res.set_content("test", "text/plain");
  9354. });
  9355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. // Create client with PEM memory
  9363. const char *password = client_encrypted_private_key_pass.empty()
  9364. ? nullptr
  9365. : client_encrypted_private_key_pass.c_str();
  9366. SSLClient::PemMemory client_pem = {
  9367. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9368. client_key_pem.size(), password};
  9369. SSLClient cli(HOST, PORT, client_pem);
  9370. cli.enable_server_certificate_verification(false);
  9371. cli.set_connection_timeout(30);
  9372. auto res = cli.Get("/test");
  9373. ASSERT_TRUE(res);
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9377. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9378. }
  9379. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9380. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9381. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9382. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9383. }
  9384. TEST(SSLClientServerTest, ClientCertMissing) {
  9385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9386. CLIENT_CA_CERT_DIR);
  9387. ASSERT_TRUE(svr.is_valid());
  9388. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9389. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9390. auto se = detail::scope_exit([&] {
  9391. svr.stop();
  9392. t.join();
  9393. ASSERT_FALSE(svr.is_running());
  9394. });
  9395. svr.wait_until_ready();
  9396. SSLClient cli(HOST, PORT);
  9397. cli.set_connection_timeout(30);
  9398. auto res = cli.Get("/test");
  9399. ASSERT_TRUE(!res);
  9400. // When client cert is missing and server requires it, connection fails
  9401. // Error type depends on backend implementation
  9402. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9403. res.error() == Error::SSLConnection);
  9404. // Verify backend error is captured
  9405. // Note: This test may have different error codes depending on the exact
  9406. // verification failure
  9407. EXPECT_NE(0UL, res.ssl_backend_error());
  9408. }
  9409. TEST(SSLClientServerTest, TrustDirOptional) {
  9410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9411. ASSERT_TRUE(svr.is_valid());
  9412. svr.Get("/test", [&](const Request &, Response &res) {
  9413. res.set_content("test", "text/plain");
  9414. });
  9415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9416. auto se = detail::scope_exit([&] {
  9417. svr.stop();
  9418. t.join();
  9419. ASSERT_FALSE(svr.is_running());
  9420. });
  9421. svr.wait_until_ready();
  9422. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9423. cli.enable_server_certificate_verification(false);
  9424. cli.set_connection_timeout(30);
  9425. auto res = cli.Get("/test");
  9426. ASSERT_TRUE(res);
  9427. ASSERT_EQ(StatusCode::OK_200, res->status);
  9428. }
  9429. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9430. class NoListenSSLServer : public SSLServer {
  9431. public:
  9432. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9433. const char *client_ca_cert_file_path,
  9434. const char *client_ca_cert_dir_path = nullptr)
  9435. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9436. client_ca_cert_dir_path),
  9437. stop_(false) {}
  9438. std::atomic_bool stop_;
  9439. private:
  9440. bool process_and_close_socket(socket_t /*sock*/) override {
  9441. // Don't create SSL context
  9442. while (!stop_.load()) {
  9443. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9444. }
  9445. return true;
  9446. }
  9447. };
  9448. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9449. CLIENT_CA_CERT_FILE);
  9450. ASSERT_TRUE(svr.is_valid());
  9451. svr.Get("/test", [&](const Request &, Response &res) {
  9452. res.set_content("test", "text/plain");
  9453. });
  9454. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9455. auto se = detail::scope_exit([&] {
  9456. svr.stop_ = true;
  9457. svr.stop();
  9458. t.join();
  9459. ASSERT_FALSE(svr.is_running());
  9460. });
  9461. svr.wait_until_ready();
  9462. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9463. cli.enable_server_certificate_verification(false);
  9464. cli.set_connection_timeout(1);
  9465. auto res = cli.Get("/test");
  9466. ASSERT_TRUE(!res);
  9467. EXPECT_EQ(Error::SSLConnection, res.error());
  9468. // Timeout results in WantRead error code (maps to backend-specific value)
  9469. EXPECT_NE(0, res.ssl_error());
  9470. }
  9471. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9472. // Test SSLServer with client certificate verification using the standard
  9473. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9475. CLIENT_CA_CERT_DIR);
  9476. ASSERT_TRUE(svr.is_valid());
  9477. svr.Get("/test", [&](const Request &req, Response &res) {
  9478. res.set_content("test", "text/plain");
  9479. auto cert = req.peer_cert();
  9480. ASSERT_TRUE(static_cast<bool>(cert));
  9481. auto common_name = cert.subject_cn();
  9482. EXPECT_EQ("Common Name", common_name);
  9483. });
  9484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9485. auto se = detail::scope_exit([&] {
  9486. svr.stop();
  9487. t.join();
  9488. ASSERT_FALSE(svr.is_running());
  9489. });
  9490. svr.wait_until_ready();
  9491. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9492. cli.enable_server_certificate_verification(false);
  9493. cli.set_connection_timeout(30);
  9494. auto res = cli.Get("/test");
  9495. ASSERT_TRUE(res);
  9496. ASSERT_EQ(StatusCode::OK_200, res->status);
  9497. }
  9498. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9499. // Verifies that wildcard matching and exact matching work consistently
  9500. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9501. using namespace httplib::tls;
  9502. // We need a running server to test against
  9503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9504. ASSERT_TRUE(svr.is_valid());
  9505. svr.Get("/test", [](const Request &, Response &res) {
  9506. res.set_content("ok", "text/plain");
  9507. });
  9508. thread t([&]() { svr.listen(HOST, PORT); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. });
  9513. svr.wait_until_ready();
  9514. bool verify_callback_called = false;
  9515. bool verify_result_wrong = false;
  9516. SSLClient cli(HOST, PORT);
  9517. cli.enable_server_certificate_verification(true);
  9518. cli.set_ca_cert_path(CA_CERT_FILE);
  9519. cli.set_connection_timeout(5);
  9520. // Note: Test certificate has CN="Common Name", not "localhost"
  9521. bool verify_result_cn = false;
  9522. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9523. verify_callback_called = true;
  9524. if (!ctx.cert) return false;
  9525. // Test 1: "Common Name" should match (our test server cert CN)
  9526. verify_result_cn = ctx.check_hostname("Common Name");
  9527. // Test 2: wrong hostname should not match
  9528. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9529. return true; // Accept for the purpose of this test
  9530. });
  9531. auto res = cli.Get("/test");
  9532. // The request may succeed or fail depending on cert configuration
  9533. // but the callback should have been called
  9534. ASSERT_TRUE(verify_callback_called)
  9535. << "Verify callback should have been called";
  9536. // CN="Common Name" should match our test certificate
  9537. //
  9538. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9539. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9540. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9541. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9542. // <openssl/base.h>, which is included transitively when
  9543. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9544. #if defined(OPENSSL_IS_BORINGSSL)
  9545. EXPECT_FALSE(verify_result_cn)
  9546. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9547. #else
  9548. EXPECT_TRUE(verify_result_cn)
  9549. << "verify_hostname should match 'Common Name' (certificate CN)";
  9550. #endif
  9551. // Wrong hostname should not match
  9552. EXPECT_FALSE(verify_result_wrong)
  9553. << "verify_hostname should not match 'wronghost.example.com'";
  9554. }
  9555. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9556. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9557. // X509_check_ip behavior and must hold for every backend.
  9558. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9559. using namespace httplib::tls;
  9560. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9561. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9562. ASSERT_TRUE(svr.is_valid());
  9563. svr.Get("/test", [](const Request &, Response &res) {
  9564. res.set_content("ok", "text/plain");
  9565. });
  9566. thread t([&]() { svr.listen(HOST, PORT); });
  9567. auto se = detail::scope_exit([&] {
  9568. svr.stop();
  9569. t.join();
  9570. });
  9571. svr.wait_until_ready();
  9572. bool verify_callback_called = false;
  9573. bool ip_matched_via_cn = true;
  9574. SSLClient cli(HOST, PORT);
  9575. cli.enable_server_certificate_verification(true);
  9576. cli.set_ca_cert_path(CA_CERT_FILE);
  9577. cli.set_connection_timeout(5);
  9578. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9579. verify_callback_called = true;
  9580. if (!ctx.cert) return false;
  9581. // The IP appears only in the CN, so it must NOT be accepted.
  9582. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9583. return true; // Accept for the purpose of this test
  9584. });
  9585. cli.Get("/test");
  9586. ASSERT_TRUE(verify_callback_called)
  9587. << "Verify callback should have been called";
  9588. EXPECT_FALSE(ip_matched_via_cn)
  9589. << "An IP host must not be authenticated via the certificate CN";
  9590. }
  9591. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9592. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9593. using namespace httplib::tls;
  9594. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9595. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9596. ASSERT_TRUE(svr.is_valid());
  9597. svr.Get("/test", [](const Request &, Response &res) {
  9598. res.set_content("ok", "text/plain");
  9599. });
  9600. thread t([&]() { svr.listen(HOST, PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. svr.stop();
  9603. t.join();
  9604. });
  9605. svr.wait_until_ready();
  9606. bool verify_callback_called = false;
  9607. bool san_matched = false;
  9608. bool wrong_ipv6_matched = true;
  9609. bool cn_ipv6_matched = 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. // Matches the IPv6 iPAddress SAN.
  9618. san_matched = ctx.check_hostname("2001:db8::1");
  9619. // A different IPv6 address must not match.
  9620. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9621. // "::1" lives only in the CN, so it must not be accepted.
  9622. cn_ipv6_matched = ctx.check_hostname("::1");
  9623. return true; // Accept for the purpose of this test
  9624. });
  9625. cli.Get("/test");
  9626. ASSERT_TRUE(verify_callback_called)
  9627. << "Verify callback should have been called";
  9628. EXPECT_TRUE(san_matched)
  9629. << "verify_hostname should match an IPv6 iPAddress SAN";
  9630. EXPECT_FALSE(wrong_ipv6_matched)
  9631. << "verify_hostname should not match a non-matching IPv6 address";
  9632. EXPECT_FALSE(cn_ipv6_matched)
  9633. << "An IPv6 host must not be authenticated via the certificate CN";
  9634. }
  9635. #endif
  9636. // mbedTLS-specific callback constructor test
  9637. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9638. #ifdef CPPHTTPLIB_SSL_ENABLED
  9639. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9641. ASSERT_TRUE(svr.is_valid());
  9642. // Set up a handler to verify client certificate is present
  9643. bool client_cert_verified = false;
  9644. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9645. // Verify that client certificate was provided
  9646. client_cert_verified = true;
  9647. res.set_content("success", "text/plain");
  9648. });
  9649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. ASSERT_FALSE(svr.is_running());
  9654. });
  9655. svr.wait_until_ready();
  9656. // Client with certificate
  9657. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9658. cli.enable_server_certificate_verification(false);
  9659. cli.set_connection_timeout(30);
  9660. auto res = cli.Get("/test");
  9661. ASSERT_TRUE(res);
  9662. ASSERT_EQ(StatusCode::OK_200, res->status);
  9663. ASSERT_TRUE(client_cert_verified);
  9664. EXPECT_EQ("success", res->body);
  9665. }
  9666. #endif
  9667. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9668. // backends
  9669. #ifdef CPPHTTPLIB_SSL_ENABLED
  9670. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9671. using namespace httplib::tls;
  9672. // Test that when client CA cert file is provided,
  9673. // the server properly requests and validates client certificates
  9674. // Create a server with client authentication
  9675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9676. ASSERT_TRUE(svr.is_valid());
  9677. bool handler_called = false;
  9678. svr.Get("/test", [&](const Request &req, Response &res) {
  9679. handler_called = true;
  9680. // Verify that a client certificate was provided
  9681. auto cert = req.peer_cert();
  9682. ASSERT_TRUE(static_cast<bool>(cert));
  9683. // Get the issuer name
  9684. std::string issuer_str = cert.issuer_name();
  9685. ASSERT_FALSE(issuer_str.empty());
  9686. // The client certificate should be issued by our test CA
  9687. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9688. res.set_content("authenticated", "text/plain");
  9689. });
  9690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9691. auto se = detail::scope_exit([&] {
  9692. svr.stop();
  9693. t.join();
  9694. ASSERT_FALSE(svr.is_running());
  9695. });
  9696. svr.wait_until_ready();
  9697. // Connect with a client certificate issued by the CA
  9698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9699. cli.enable_server_certificate_verification(false);
  9700. cli.set_connection_timeout(30);
  9701. auto res = cli.Get("/test");
  9702. ASSERT_TRUE(res);
  9703. ASSERT_EQ(StatusCode::OK_200, res->status);
  9704. ASSERT_TRUE(handler_called);
  9705. EXPECT_EQ("authenticated", res->body);
  9706. }
  9707. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9708. using namespace httplib::tls;
  9709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9710. ASSERT_TRUE(svr.is_valid());
  9711. svr.Get("/test", [](const Request &, Response &res) {
  9712. res.set_content("ok", "text/plain");
  9713. });
  9714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9715. auto se = detail::scope_exit([&] {
  9716. svr.stop();
  9717. t.join();
  9718. });
  9719. svr.wait_until_ready();
  9720. SSLClient cli(HOST, PORT);
  9721. cli.enable_server_certificate_verification(false);
  9722. cli.set_connection_timeout(30);
  9723. bool cert_checked = false;
  9724. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9725. if (ctx.cert) {
  9726. auto sans = ctx.sans();
  9727. // Test certificate may or may not have SANs - just verify the API
  9728. // works If SANs exist, verify the types are valid
  9729. for (const auto &san : sans) {
  9730. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9731. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9732. san.type == SanType::OTHER);
  9733. EXPECT_FALSE(san.value.empty());
  9734. }
  9735. cert_checked = true;
  9736. }
  9737. return true;
  9738. });
  9739. auto res = cli.Get("/test");
  9740. ASSERT_TRUE(res);
  9741. EXPECT_TRUE(cert_checked);
  9742. }
  9743. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  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 validity_checked = false;
  9760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9761. if (ctx.cert) {
  9762. time_t not_before = 0, not_after = 0;
  9763. bool result = ctx.validity(not_before, not_after);
  9764. EXPECT_TRUE(result);
  9765. // Verify that not_before < now < not_after for a valid cert
  9766. time_t now = time(nullptr);
  9767. EXPECT_LT(not_before, now);
  9768. EXPECT_GT(not_after, now);
  9769. validity_checked = true;
  9770. }
  9771. return true;
  9772. });
  9773. auto res = cli.Get("/test");
  9774. ASSERT_TRUE(res);
  9775. EXPECT_TRUE(validity_checked);
  9776. }
  9777. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9778. using namespace httplib::tls;
  9779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9780. ASSERT_TRUE(svr.is_valid());
  9781. svr.Get("/test", [](const Request &, Response &res) {
  9782. res.set_content("ok", "text/plain");
  9783. });
  9784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9785. auto se = detail::scope_exit([&] {
  9786. svr.stop();
  9787. t.join();
  9788. });
  9789. svr.wait_until_ready();
  9790. SSLClient cli(HOST, PORT);
  9791. cli.enable_server_certificate_verification(false);
  9792. cli.set_connection_timeout(30);
  9793. bool serial_checked = false;
  9794. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9795. if (ctx.cert) {
  9796. std::string serial = ctx.serial();
  9797. EXPECT_FALSE(serial.empty());
  9798. // Serial should be a hex string
  9799. for (char c : serial) {
  9800. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9801. (c >= 'a' && c <= 'f'));
  9802. }
  9803. serial_checked = true;
  9804. }
  9805. return true;
  9806. });
  9807. auto res = cli.Get("/test");
  9808. ASSERT_TRUE(res);
  9809. EXPECT_TRUE(serial_checked);
  9810. }
  9811. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9812. // Test 1: Valid CA file - no error should be recorded
  9813. {
  9814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9815. CLIENT_CA_CERT_FILE);
  9816. ASSERT_TRUE(svr.is_valid());
  9817. // With valid setup, last_ssl_error should be 0
  9818. EXPECT_EQ(0, svr.ssl_last_error());
  9819. }
  9820. // Test 2: Invalid CA file content
  9821. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9822. {
  9823. // Create a temporary file with completely invalid content
  9824. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9825. {
  9826. std::ofstream ofs(temp_invalid_ca);
  9827. ofs << "This is not a certificate file at all\n";
  9828. ofs << "Just plain text content\n";
  9829. }
  9830. // Create server with invalid CA file
  9831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9832. // Clean up temporary file
  9833. std::remove(temp_invalid_ca);
  9834. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9835. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9836. // Note: SSL_CTX_load_verify_locations typically fails first,
  9837. // but our error handling code path is still exercised
  9838. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9839. }
  9840. }
  9841. TEST(VerifyCallbackTest, VerifyContextFields) {
  9842. using namespace httplib::tls;
  9843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9844. ASSERT_TRUE(svr.is_valid());
  9845. svr.Get("/test", [](const Request &, Response &res) {
  9846. res.set_content("ok", "text/plain");
  9847. });
  9848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. t.join();
  9852. });
  9853. svr.wait_until_ready();
  9854. SSLClient cli(HOST, PORT);
  9855. cli.enable_server_certificate_verification(false);
  9856. cli.set_connection_timeout(30);
  9857. int callback_count = 0;
  9858. bool saw_leaf_cert = false;
  9859. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9860. if (ctx.cert) {
  9861. callback_count++;
  9862. // We should see at least one certificate (the leaf)
  9863. std::string cn = ctx.subject_cn();
  9864. if (!cn.empty()) { saw_leaf_cert = true; }
  9865. // Verify context fields are populated
  9866. EXPECT_NE(ctx.session, nullptr);
  9867. EXPECT_GE(ctx.depth, 0);
  9868. }
  9869. return true;
  9870. });
  9871. auto res = cli.Get("/test");
  9872. ASSERT_TRUE(res);
  9873. EXPECT_GT(callback_count, 0);
  9874. EXPECT_TRUE(saw_leaf_cert);
  9875. }
  9876. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9877. using httplib::tls::TlsError;
  9878. // Test that verify_error_to_string returns empty for success
  9879. std::string success_str = TlsError::verify_error_to_string(0);
  9880. EXPECT_TRUE(success_str.empty());
  9881. // Test that verify_error_to_string returns non-empty for error codes
  9882. // Using a common error code (certificate expired)
  9883. std::string error_str =
  9884. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9885. EXPECT_FALSE(error_str.empty());
  9886. }
  9887. TEST(SessionVerifierTest, CertificateAccepted) {
  9888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9889. ASSERT_TRUE(svr.is_valid());
  9890. svr.Get("/test", [](const Request &, Response &res) {
  9891. res.set_content("ok", "text/plain");
  9892. });
  9893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. t.join();
  9897. });
  9898. svr.wait_until_ready();
  9899. SSLClient cli(HOST, PORT);
  9900. cli.enable_server_certificate_verification(false);
  9901. cli.set_connection_timeout(30);
  9902. bool callback_called = false;
  9903. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9904. EXPECT_NE(session, nullptr);
  9905. callback_called = true;
  9906. return SSLVerifierResponse::CertificateAccepted;
  9907. });
  9908. auto res = cli.Get("/test");
  9909. ASSERT_TRUE(res);
  9910. EXPECT_EQ(200, res->status);
  9911. EXPECT_TRUE(callback_called);
  9912. }
  9913. TEST(SessionVerifierTest, CertificateRejected) {
  9914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9915. ASSERT_TRUE(svr.is_valid());
  9916. svr.Get("/test", [](const Request &, Response &res) {
  9917. res.set_content("ok", "text/plain");
  9918. });
  9919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9920. auto se = detail::scope_exit([&] {
  9921. svr.stop();
  9922. t.join();
  9923. });
  9924. svr.wait_until_ready();
  9925. SSLClient cli(HOST, PORT);
  9926. cli.enable_server_certificate_verification(false);
  9927. cli.set_connection_timeout(30);
  9928. bool callback_called = false;
  9929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9930. EXPECT_NE(session, nullptr);
  9931. callback_called = true;
  9932. return SSLVerifierResponse::CertificateRejected;
  9933. });
  9934. auto res = cli.Get("/test");
  9935. EXPECT_FALSE(res);
  9936. EXPECT_TRUE(callback_called);
  9937. }
  9938. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9940. ASSERT_TRUE(svr.is_valid());
  9941. svr.Get("/test", [](const Request &, Response &res) {
  9942. res.set_content("ok", "text/plain");
  9943. });
  9944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. t.join();
  9948. });
  9949. svr.wait_until_ready();
  9950. // NoDecisionMade with verification disabled should succeed (no default check)
  9951. SSLClient cli(HOST, PORT);
  9952. cli.enable_server_certificate_verification(false);
  9953. cli.set_connection_timeout(30);
  9954. bool callback_called = false;
  9955. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9956. EXPECT_NE(session, nullptr);
  9957. callback_called = true;
  9958. return SSLVerifierResponse::NoDecisionMade;
  9959. });
  9960. auto res = cli.Get("/test");
  9961. ASSERT_TRUE(res);
  9962. EXPECT_EQ(200, res->status);
  9963. EXPECT_TRUE(callback_called);
  9964. }
  9965. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9967. ASSERT_TRUE(svr.is_valid());
  9968. svr.Get("/test", [](const Request &, Response &res) {
  9969. res.set_content("ok", "text/plain");
  9970. });
  9971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. });
  9976. svr.wait_until_ready();
  9977. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9978. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9979. // so we only check that the request fails, not whether the callback was
  9980. // called.
  9981. SSLClient cli(HOST, PORT);
  9982. cli.enable_server_certificate_verification(true);
  9983. cli.set_connection_timeout(30);
  9984. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9985. EXPECT_NE(session, nullptr);
  9986. return SSLVerifierResponse::NoDecisionMade;
  9987. });
  9988. auto res = cli.Get("/test");
  9989. EXPECT_FALSE(res);
  9990. }
  9991. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9992. // Test SSL server using PemMemory constructor with client CA certificates
  9993. // Read PEM files
  9994. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9995. read_file(SERVER_CERT_FILE, server_cert_pem);
  9996. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9997. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9998. // Create SSLServer with PemMemory constructor including client CA
  9999. SSLServer::PemMemory server_pem = {
  10000. server_cert_pem.c_str(),
  10001. server_cert_pem.size(),
  10002. server_key_pem.c_str(),
  10003. server_key_pem.size(),
  10004. client_ca_pem.c_str(),
  10005. client_ca_pem.size(),
  10006. nullptr // no password for server key
  10007. };
  10008. SSLServer svr(server_pem);
  10009. ASSERT_TRUE(svr.is_valid());
  10010. // No SSL error should be recorded for valid setup
  10011. EXPECT_EQ(0, svr.ssl_last_error());
  10012. // Set up server endpoints
  10013. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10014. res.set_content("ok", "text/plain");
  10015. });
  10016. // Start server in a thread
  10017. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10018. svr.wait_until_ready();
  10019. // Connect with client certificate (using constructor with paths)
  10020. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10021. cli.enable_server_certificate_verification(false);
  10022. auto res = cli.Get("/test-pem-ca");
  10023. ASSERT_TRUE(res);
  10024. EXPECT_EQ(200, res->status);
  10025. EXPECT_EQ("ok", res->body);
  10026. svr.stop();
  10027. server_thread.join();
  10028. }
  10029. #endif
  10030. #ifdef _WIN32
  10031. TEST(CleanupTest, WSACleanup) {
  10032. int ret = WSACleanup();
  10033. ASSERT_EQ(0, ret);
  10034. }
  10035. #endif
  10036. #ifndef CPPHTTPLIB_SSL_ENABLED
  10037. TEST(NoSSLSupport, SimpleInterface) {
  10038. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10039. }
  10040. #endif
  10041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10042. TEST(InvalidScheme, SimpleInterface) {
  10043. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10044. }
  10045. #endif
  10046. TEST(NoScheme, SimpleInterface) {
  10047. Client cli("yahoo.com:80");
  10048. ASSERT_TRUE(cli.is_valid());
  10049. }
  10050. TEST(SendAPI, SimpleInterface_Online) {
  10051. Client cli("http://yahoo.com");
  10052. Request req;
  10053. req.method = "GET";
  10054. req.path = "/";
  10055. auto res = cli.send(req);
  10056. ASSERT_TRUE(res);
  10057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10058. }
  10059. TEST(SendAPI, WithParamsInRequest) {
  10060. Server svr;
  10061. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10062. EXPECT_TRUE(req.has_param("test"));
  10063. EXPECT_EQ("test_value", req.get_param_value("test"));
  10064. });
  10065. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10066. auto se = detail::scope_exit([&] {
  10067. svr.stop();
  10068. t.join();
  10069. ASSERT_FALSE(svr.is_running());
  10070. });
  10071. svr.wait_until_ready();
  10072. Client cli(HOST, PORT);
  10073. {
  10074. Request req;
  10075. req.method = "GET";
  10076. req.path = "/";
  10077. req.params.emplace("test", "test_value");
  10078. auto res = cli.send(req);
  10079. ASSERT_TRUE(res);
  10080. }
  10081. {
  10082. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10083. ASSERT_TRUE(res);
  10084. }
  10085. }
  10086. TEST(ClientImplMethods, GetSocketTest) {
  10087. httplib::Server svr;
  10088. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10089. res.status = StatusCode::OK_200;
  10090. });
  10091. auto port = svr.bind_to_any_port("127.0.0.1");
  10092. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. thread.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. });
  10098. svr.wait_until_ready();
  10099. {
  10100. httplib::Client cli("127.0.0.1", port);
  10101. cli.set_keep_alive(true);
  10102. // Use the behavior of cpp-httplib of opening the connection
  10103. // only when the first request happens. If that changes,
  10104. // this test would be obsolete.
  10105. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10106. // This also implicitly tests the server. But other tests would fail much
  10107. // earlier than this one to be considered.
  10108. auto res = cli.Get("/");
  10109. ASSERT_TRUE(res);
  10110. EXPECT_EQ(StatusCode::OK_200, res->status);
  10111. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10112. }
  10113. }
  10114. #ifdef CPPHTTPLIB_SSL_ENABLED
  10115. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10116. Client cli("http://yahoo.com");
  10117. auto res = cli.Get("/");
  10118. ASSERT_TRUE(res);
  10119. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10120. cli.set_follow_location(true);
  10121. res = cli.Get("/");
  10122. ASSERT_TRUE(res);
  10123. EXPECT_EQ(StatusCode::OK_200, res->status);
  10124. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10125. }
  10126. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10127. Client cli("https://yahoo.com");
  10128. auto res = cli.Get("/");
  10129. ASSERT_TRUE(res);
  10130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10131. cli.set_follow_location(true);
  10132. res = cli.Get("/");
  10133. ASSERT_TRUE(res);
  10134. EXPECT_EQ(StatusCode::OK_200, res->status);
  10135. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10136. }
  10137. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10138. Client cli("https://yahoo.com");
  10139. auto res = cli.Get("/");
  10140. ASSERT_TRUE(res);
  10141. ASSERT_FALSE(!res);
  10142. ASSERT_TRUE(res);
  10143. ASSERT_FALSE(res == nullptr);
  10144. ASSERT_TRUE(res != nullptr);
  10145. EXPECT_EQ(Error::Success, res.error());
  10146. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10147. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10148. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10149. cli.set_follow_location(true);
  10150. res = cli.Get("/");
  10151. ASSERT_TRUE(res);
  10152. EXPECT_EQ(Error::Success, res.error());
  10153. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10154. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10155. EXPECT_EQ(StatusCode::OK_200, res->status);
  10156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10157. }
  10158. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10159. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10160. Client cli("https://cdnjs.cloudflare.com");
  10161. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10162. Headers{{"Accept-Encoding", "br"}});
  10163. ASSERT_TRUE(res);
  10164. EXPECT_EQ(StatusCode::OK_200, res->status);
  10165. EXPECT_EQ(287630U, res->body.size());
  10166. EXPECT_EQ("application/javascript; charset=utf-8",
  10167. res->get_header_value("Content-Type"));
  10168. }
  10169. #endif
  10170. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10171. #undef REDIR_HOST // Silence compiler warning
  10172. #define REDIR_HOST "https://httpbingo.org"
  10173. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10174. Client cli(REDIR_HOST);
  10175. cli.set_follow_location(true);
  10176. auto res =
  10177. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10178. ASSERT_TRUE(res);
  10179. EXPECT_EQ(StatusCode::OK_200, res->status);
  10180. }
  10181. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10182. Client cli(REDIR_HOST);
  10183. cli.set_follow_location(true);
  10184. Params params;
  10185. params.emplace("url", "http://example.com");
  10186. params.emplace("status_code", "302");
  10187. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10188. ASSERT_TRUE(res);
  10189. EXPECT_EQ(StatusCode::OK_200, res->status);
  10190. }
  10191. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10192. Client cli(REDIR_HOST);
  10193. cli.set_follow_location(true);
  10194. Params params;
  10195. params.emplace("url", "http://example.com");
  10196. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10197. ASSERT_TRUE(res);
  10198. EXPECT_EQ(StatusCode::OK_200, res->status);
  10199. }
  10200. TEST(HttpToHttpsRedirectTest, CertFile) {
  10201. auto ssl_port = PORT + 1;
  10202. Server svr;
  10203. ASSERT_TRUE(svr.is_valid());
  10204. svr.Get("/index", [&](const Request &, Response &res) {
  10205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10206. "/index");
  10207. svr.stop();
  10208. });
  10209. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10210. ASSERT_TRUE(ssl_svr.is_valid());
  10211. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10212. res.set_content("test", "text/plain");
  10213. ssl_svr.stop();
  10214. });
  10215. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10216. thread t2 =
  10217. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10218. auto se = detail::scope_exit([&] {
  10219. t2.join();
  10220. t.join();
  10221. ASSERT_FALSE(svr.is_running());
  10222. });
  10223. svr.wait_until_ready();
  10224. ssl_svr.wait_until_ready();
  10225. Client cli("127.0.0.1", PORT);
  10226. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10227. cli.enable_server_certificate_verification(true);
  10228. cli.set_follow_location(true);
  10229. cli.set_connection_timeout(30);
  10230. auto res = cli.Get("/index");
  10231. ASSERT_TRUE(res);
  10232. ASSERT_EQ(StatusCode::OK_200, res->status);
  10233. }
  10234. TEST(SSLClientRedirectTest, CertFile) {
  10235. auto ssl_port = PORT + 1;
  10236. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(ssl_svr1.is_valid());
  10238. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10239. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10240. "/index");
  10241. ssl_svr1.stop();
  10242. });
  10243. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10244. ASSERT_TRUE(ssl_svr2.is_valid());
  10245. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10246. res.set_content("test", "text/plain");
  10247. ssl_svr2.stop();
  10248. });
  10249. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10250. thread t2 =
  10251. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10252. auto se = detail::scope_exit([&] {
  10253. t2.join();
  10254. t.join();
  10255. ASSERT_FALSE(ssl_svr1.is_running());
  10256. });
  10257. ssl_svr1.wait_until_ready();
  10258. ssl_svr2.wait_until_ready();
  10259. SSLClient cli("127.0.0.1", PORT);
  10260. std::string cert;
  10261. read_file(SERVER_CERT2_FILE, cert);
  10262. cli.load_ca_cert_store(cert.c_str(), cert.size());
  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. #endif
  10271. #ifdef CPPHTTPLIB_SSL_ENABLED
  10272. // Test that set_ca_cert_store() skips system certs (consistent with
  10273. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10274. // should be trusted - system certs should NOT be loaded.
  10275. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10276. // Load a specific cert that is NOT a system CA cert
  10277. std::string cert;
  10278. read_file(SERVER_CERT2_FILE, cert);
  10279. SSLClient cli("google.com");
  10280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10281. cli.enable_server_certificate_verification(true);
  10282. // This should FAIL because:
  10283. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10284. // 2. System certs should NOT be loaded when custom store is set
  10285. // If system certs WERE loaded, this would succeed
  10286. auto res = cli.Get("/");
  10287. ASSERT_FALSE(res);
  10288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10289. }
  10290. // Same as above, but through the native store handle path. Regression test:
  10291. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10292. // merged system certs into the user-provided store.
  10293. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10294. std::string cert;
  10295. read_file(SERVER_CERT2_FILE, cert);
  10296. SSLClient cli("google.com");
  10297. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10298. cli.enable_server_certificate_verification(true);
  10299. auto res = cli.Get("/");
  10300. ASSERT_FALSE(res);
  10301. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10302. }
  10303. // A custom store set via the native handle must still verify a server whose
  10304. // cert it does contain.
  10305. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10306. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10307. ASSERT_TRUE(svr.is_valid());
  10308. svr.Get("/test", [&](const Request &, Response &res) {
  10309. res.set_content("test", "text/plain");
  10310. });
  10311. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. t.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. SSLClient cli("127.0.0.1", PORT);
  10319. std::string cert;
  10320. read_file(SERVER_CERT2_FILE, cert);
  10321. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10322. cli.enable_server_certificate_verification(true);
  10323. cli.set_connection_timeout(30);
  10324. auto res = cli.Get("/test");
  10325. ASSERT_TRUE(res);
  10326. ASSERT_EQ(StatusCode::OK_200, res->status);
  10327. }
  10328. // CA certs loaded through the universal Client must be transferred to the
  10329. // client created internally for following an HTTPS redirect. Regression test:
  10330. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10331. // the CA data for redirect transfer.
  10332. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10333. auto ssl_port = PORT + 1;
  10334. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10335. ASSERT_TRUE(ssl_svr1.is_valid());
  10336. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10337. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10338. "/index");
  10339. });
  10340. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10341. ASSERT_TRUE(ssl_svr2.is_valid());
  10342. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10343. res.set_content("test", "text/plain");
  10344. });
  10345. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10346. thread t2 =
  10347. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10348. auto se = detail::scope_exit([&] {
  10349. ssl_svr2.stop();
  10350. ssl_svr1.stop();
  10351. t2.join();
  10352. t.join();
  10353. ASSERT_FALSE(ssl_svr1.is_running());
  10354. });
  10355. ssl_svr1.wait_until_ready();
  10356. ssl_svr2.wait_until_ready();
  10357. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10358. std::string cert;
  10359. read_file(SERVER_CERT2_FILE, cert);
  10360. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10361. cli.enable_server_certificate_verification(true);
  10362. cli.set_follow_location(true);
  10363. cli.set_connection_timeout(30);
  10364. auto res = cli.Get("/index");
  10365. ASSERT_TRUE(res);
  10366. ASSERT_EQ(StatusCode::OK_200, res->status);
  10367. }
  10368. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10369. // so a host signed by a system CA verifies even though a custom CA is set
  10370. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10371. std::string cert;
  10372. read_file(SERVER_CERT2_FILE, cert);
  10373. SSLClient cli("google.com");
  10374. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10375. cli.enable_system_ca(true);
  10376. cli.enable_server_certificate_verification(true);
  10377. auto res = cli.Get("/");
  10378. ASSERT_TRUE(res);
  10379. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10380. }
  10381. // The custom CA remains effective when combined with the system CA
  10382. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10383. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10384. ASSERT_TRUE(svr.is_valid());
  10385. svr.Get("/test", [&](const Request &, Response &res) {
  10386. res.set_content("test", "text/plain");
  10387. });
  10388. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. t.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. SSLClient cli("127.0.0.1", PORT);
  10396. std::string cert;
  10397. read_file(SERVER_CERT2_FILE, cert);
  10398. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10399. cli.enable_system_ca(true);
  10400. cli.enable_server_certificate_verification(true);
  10401. cli.set_connection_timeout(30);
  10402. auto res = cli.Get("/test");
  10403. ASSERT_TRUE(res);
  10404. ASSERT_EQ(StatusCode::OK_200, res->status);
  10405. }
  10406. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10407. // skip chain verification entirely (only the certificate identity was
  10408. // checked), so a server presenting an untrusted certificate with a matching
  10409. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10410. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10411. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.Get("/test", [&](const Request &, Response &res) {
  10414. res.set_content("test", "text/plain");
  10415. });
  10416. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. t.join();
  10420. ASSERT_FALSE(svr.is_running());
  10421. });
  10422. svr.wait_until_ready();
  10423. SSLClient cli("127.0.0.1", PORT);
  10424. std::string cert;
  10425. // A trusted CA that did not sign the server certificate. The server cert
  10426. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10427. // this connection.
  10428. read_file(CLIENT_CA_CERT_FILE, cert);
  10429. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10430. cli.enable_server_certificate_verification(true);
  10431. cli.set_connection_timeout(30);
  10432. auto res = cli.Get("/test");
  10433. ASSERT_FALSE(res);
  10434. }
  10435. // enable_system_ca(false) prevents system CA loading entirely
  10436. TEST(SSLClientTest, DisableSystemCa_Online) {
  10437. SSLClient cli("google.com");
  10438. cli.enable_system_ca(false);
  10439. cli.enable_server_certificate_verification(true);
  10440. auto res = cli.Get("/");
  10441. ASSERT_FALSE(res);
  10442. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10443. // itself when the CA chain is empty
  10444. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10445. res.error() == Error::SSLConnection);
  10446. }
  10447. // The universal Client forwards enable_system_ca()
  10448. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10449. std::string cert;
  10450. read_file(SERVER_CERT2_FILE, cert);
  10451. Client cli("https://google.com");
  10452. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10453. cli.enable_system_ca(true);
  10454. cli.enable_server_certificate_verification(true);
  10455. auto res = cli.Get("/");
  10456. ASSERT_TRUE(res);
  10457. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10458. }
  10459. // The system CA policy must carry over to the client created internally for
  10460. // following a cross-host HTTPS redirect
  10461. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10462. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10463. ASSERT_TRUE(svr.is_valid());
  10464. svr.Get("/index", [&](const Request &, Response &res) {
  10465. res.set_redirect("https://www.google.com/");
  10466. });
  10467. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10468. auto se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. t.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.wait_until_ready();
  10474. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10475. std::string cert;
  10476. read_file(SERVER_CERT2_FILE, cert);
  10477. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10478. cli.enable_system_ca(true);
  10479. cli.enable_server_certificate_verification(true);
  10480. cli.set_follow_location(true);
  10481. cli.set_connection_timeout(30);
  10482. // Receiving any response proves the redirect client completed the TLS
  10483. // handshake with a system-CA-signed host
  10484. auto res = cli.Get("/index");
  10485. ASSERT_TRUE(res);
  10486. }
  10487. TEST(MultipartFormDataTest, LargeData) {
  10488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10489. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10490. const ContentReader &content_reader) {
  10491. if (req.is_multipart_form_data()) {
  10492. std::vector<FormData> items;
  10493. content_reader(
  10494. [&](const FormData &file) {
  10495. items.push_back(file);
  10496. return true;
  10497. },
  10498. [&](const char *data, size_t data_length) {
  10499. items.back().content.append(data, data_length);
  10500. return true;
  10501. });
  10502. EXPECT_TRUE(std::string(items[0].name) == "document");
  10503. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10504. EXPECT_TRUE(items[0].filename == "2MB_data");
  10505. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10506. EXPECT_TRUE(items[1].name == "hello");
  10507. EXPECT_TRUE(items[1].content == "world");
  10508. EXPECT_TRUE(items[1].filename == "");
  10509. EXPECT_TRUE(items[1].content_type == "");
  10510. } else {
  10511. std::string body;
  10512. content_reader([&](const char *data, size_t data_length) {
  10513. body.append(data, data_length);
  10514. return true;
  10515. });
  10516. }
  10517. });
  10518. auto port = svr.bind_to_any_port(HOST);
  10519. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. t.join();
  10523. ASSERT_FALSE(svr.is_running());
  10524. });
  10525. svr.wait_until_ready();
  10526. {
  10527. std::string data(1024 * 1024 * 2, '.');
  10528. std::stringstream buffer;
  10529. buffer << data;
  10530. SSLClient cli(HOST, port);
  10531. cli.enable_server_certificate_verification(false);
  10532. UploadFormDataItems items{
  10533. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10534. {"hello", "world", "", ""},
  10535. };
  10536. auto res = cli.Post("/post", items);
  10537. ASSERT_TRUE(res);
  10538. ASSERT_EQ(StatusCode::OK_200, res->status);
  10539. }
  10540. }
  10541. TEST(MultipartFormDataTest, DataProviderItems) {
  10542. std::random_device seed_gen;
  10543. std::mt19937 random(seed_gen());
  10544. std::string rand1;
  10545. rand1.resize(1000);
  10546. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10547. std::string rand2;
  10548. rand2.resize(3000);
  10549. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10551. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10552. const ContentReader &content_reader) {
  10553. ASSERT_FALSE(req.is_multipart_form_data());
  10554. std::string body;
  10555. content_reader([&](const char *data, size_t data_length) {
  10556. body.append(data, data_length);
  10557. return true;
  10558. });
  10559. EXPECT_EQ(body, "");
  10560. });
  10561. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10562. const ContentReader &content_reader) {
  10563. ASSERT_TRUE(req.is_multipart_form_data());
  10564. std::vector<FormData> items;
  10565. content_reader(
  10566. [&](const FormData &file) {
  10567. items.push_back(file);
  10568. return true;
  10569. },
  10570. [&](const char *data, size_t data_length) {
  10571. items.back().content.append(data, data_length);
  10572. return true;
  10573. });
  10574. ASSERT_TRUE(items.size() == 2);
  10575. EXPECT_EQ(std::string(items[0].name), "name1");
  10576. EXPECT_EQ(items[0].content, "Testing123");
  10577. EXPECT_EQ(items[0].filename, "filename1");
  10578. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10579. EXPECT_EQ(items[1].name, "name2");
  10580. EXPECT_EQ(items[1].content, "Testing456");
  10581. EXPECT_EQ(items[1].filename, "");
  10582. EXPECT_EQ(items[1].content_type, "");
  10583. });
  10584. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10585. const ContentReader &content_reader) {
  10586. ASSERT_TRUE(req.is_multipart_form_data());
  10587. std::vector<FormData> items;
  10588. content_reader(
  10589. [&](const FormData &file) {
  10590. items.push_back(file);
  10591. return true;
  10592. },
  10593. [&](const char *data, size_t data_length) {
  10594. items.back().content.append(data, data_length);
  10595. return true;
  10596. });
  10597. ASSERT_TRUE(items.size() == 2);
  10598. EXPECT_EQ(items[0].name, "name3");
  10599. EXPECT_EQ(items[0].content, rand1);
  10600. EXPECT_EQ(items[0].filename, "filename3");
  10601. EXPECT_EQ(items[0].content_type, "");
  10602. EXPECT_EQ(items[1].name, "name4");
  10603. EXPECT_EQ(items[1].content, rand2);
  10604. EXPECT_EQ(items[1].filename, "filename4");
  10605. EXPECT_EQ(items[1].content_type, "");
  10606. });
  10607. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10608. const ContentReader &content_reader) {
  10609. ASSERT_TRUE(req.is_multipart_form_data());
  10610. std::vector<FormData> items;
  10611. content_reader(
  10612. [&](const FormData &file) {
  10613. items.push_back(file);
  10614. return true;
  10615. },
  10616. [&](const char *data, size_t data_length) {
  10617. items.back().content.append(data, data_length);
  10618. return true;
  10619. });
  10620. ASSERT_TRUE(items.size() == 4);
  10621. EXPECT_EQ(std::string(items[0].name), "name1");
  10622. EXPECT_EQ(items[0].content, "Testing123");
  10623. EXPECT_EQ(items[0].filename, "filename1");
  10624. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10625. EXPECT_EQ(items[1].name, "name2");
  10626. EXPECT_EQ(items[1].content, "Testing456");
  10627. EXPECT_EQ(items[1].filename, "");
  10628. EXPECT_EQ(items[1].content_type, "");
  10629. EXPECT_EQ(items[2].name, "name3");
  10630. EXPECT_EQ(items[2].content, rand1);
  10631. EXPECT_EQ(items[2].filename, "filename3");
  10632. EXPECT_EQ(items[2].content_type, "");
  10633. EXPECT_EQ(items[3].name, "name4");
  10634. EXPECT_EQ(items[3].content, rand2);
  10635. EXPECT_EQ(items[3].filename, "filename4");
  10636. EXPECT_EQ(items[3].content_type, "");
  10637. });
  10638. auto port = svr.bind_to_any_port("localhost");
  10639. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10640. auto se = detail::scope_exit([&] {
  10641. svr.stop();
  10642. t.join();
  10643. ASSERT_FALSE(svr.is_running());
  10644. });
  10645. svr.wait_until_ready();
  10646. {
  10647. SSLClient cli("localhost", port);
  10648. cli.enable_server_certificate_verification(false);
  10649. UploadFormDataItems items{
  10650. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10651. {"name2", "Testing456", "", ""}, // not a file
  10652. };
  10653. {
  10654. auto res = cli.Post("/post-none", {}, {}, {});
  10655. ASSERT_TRUE(res);
  10656. ASSERT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. FormDataProviderItems providers;
  10659. {
  10660. auto res =
  10661. cli.Post("/post-items", {}, items, providers); // empty providers
  10662. ASSERT_TRUE(res);
  10663. ASSERT_EQ(StatusCode::OK_200, res->status);
  10664. }
  10665. providers.push_back({"name3",
  10666. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10667. // test the offset is given correctly at each step
  10668. if (!offset)
  10669. sink.os.write(rand1.data(), 30);
  10670. else if (offset == 30)
  10671. sink.os.write(rand1.data() + 30, 300);
  10672. else if (offset == 330)
  10673. sink.os.write(rand1.data() + 330, 670);
  10674. else if (offset == rand1.size())
  10675. sink.done();
  10676. return true;
  10677. },
  10678. "filename3",
  10679. {}});
  10680. providers.push_back({"name4",
  10681. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10682. // test the offset is given correctly at each step
  10683. if (!offset)
  10684. sink.os.write(rand2.data(), 2000);
  10685. else if (offset == 2000)
  10686. sink.os.write(rand2.data() + 2000, 1);
  10687. else if (offset == 2001)
  10688. sink.os.write(rand2.data() + 2001, 999);
  10689. else if (offset == rand2.size())
  10690. sink.done();
  10691. return true;
  10692. },
  10693. "filename4",
  10694. {}});
  10695. {
  10696. auto res = cli.Post("/post-providers", {}, {}, providers);
  10697. ASSERT_TRUE(res);
  10698. ASSERT_EQ(StatusCode::OK_200, res->status);
  10699. }
  10700. {
  10701. auto res = cli.Post("/post-both", {}, items, providers);
  10702. ASSERT_TRUE(res);
  10703. ASSERT_EQ(StatusCode::OK_200, res->status);
  10704. }
  10705. }
  10706. }
  10707. TEST(MultipartFormDataTest, BadHeader) {
  10708. Server svr;
  10709. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10710. res.set_content("ok", "text/plain");
  10711. });
  10712. thread t = thread([&] { svr.listen(HOST, PORT); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. const std::string body =
  10720. "This is the preamble. It is to be ignored, though it\r\n"
  10721. "is a handy place for composition agents to include an\r\n"
  10722. "explanatory note to non-MIME conformant readers.\r\n"
  10723. "\r\n"
  10724. "\r\n"
  10725. "--simple boundary\r\n"
  10726. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10727. ": BAD...\r\n"
  10728. "\r\n"
  10729. "value1\r\n"
  10730. "--simple boundary\r\n"
  10731. "Content-Disposition: form-data; name=\"field2\"; "
  10732. "filename=\"example.txt\"\r\n"
  10733. "\r\n"
  10734. "value2\r\n"
  10735. "--simple boundary--\r\n"
  10736. "This is the epilogue. It is also to be ignored.\r\n";
  10737. std::string content_type =
  10738. R"(multipart/form-data; boundary="simple boundary")";
  10739. Client cli(HOST, PORT);
  10740. auto res = cli.Post("/post", body, content_type.c_str());
  10741. ASSERT_TRUE(res);
  10742. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10743. }
  10744. TEST(MultipartFormDataTest, WithPreamble) {
  10745. Server svr;
  10746. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10747. res.set_content("ok", "text/plain");
  10748. });
  10749. thread t = thread([&] { svr.listen(HOST, PORT); });
  10750. auto se = detail::scope_exit([&] {
  10751. svr.stop();
  10752. t.join();
  10753. ASSERT_FALSE(svr.is_running());
  10754. });
  10755. svr.wait_until_ready();
  10756. const std::string body =
  10757. "This is the preamble. It is to be ignored, though it\r\n"
  10758. "is a handy place for composition agents to include an\r\n"
  10759. "explanatory note to non-MIME conformant readers.\r\n"
  10760. "\r\n"
  10761. "\r\n"
  10762. "--simple boundary\r\n"
  10763. "Content-Disposition: form-data; name=\"field1\"\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::OK_200, res->status);
  10779. }
  10780. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10782. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10783. const ContentReader &content_reader) {
  10784. if (req.is_multipart_form_data()) {
  10785. std::vector<FormData> items;
  10786. content_reader(
  10787. [&](const FormData &file) {
  10788. items.push_back(file);
  10789. return true;
  10790. },
  10791. [&](const char *data, size_t data_length) {
  10792. items.back().content.append(data, data_length);
  10793. return true;
  10794. });
  10795. EXPECT_TRUE(std::string(items[0].name) == "document");
  10796. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10797. EXPECT_TRUE(items[0].filename == "2MB_data");
  10798. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10799. EXPECT_TRUE(items[1].name == "hello");
  10800. EXPECT_TRUE(items[1].content == "world");
  10801. EXPECT_TRUE(items[1].filename == "");
  10802. EXPECT_TRUE(items[1].content_type == "");
  10803. } else {
  10804. std::string body;
  10805. content_reader([&](const char *data, size_t data_length) {
  10806. body.append(data, data_length);
  10807. return true;
  10808. });
  10809. }
  10810. });
  10811. auto port = svr.bind_to_any_port("localhost");
  10812. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10813. auto se = detail::scope_exit([&] {
  10814. svr.stop();
  10815. t.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. {
  10820. std::string data(1024 * 1024 * 2, '.');
  10821. std::stringstream buffer;
  10822. buffer << data;
  10823. SSLClient cli("localhost", port);
  10824. cli.enable_server_certificate_verification(false);
  10825. UploadFormDataItems items{
  10826. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10827. {"hello", "world", "", ""},
  10828. };
  10829. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10830. ASSERT_TRUE(res);
  10831. ASSERT_EQ(StatusCode::OK_200, res->status);
  10832. }
  10833. }
  10834. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10835. std::string data(1024 * 1024 * 2, '&');
  10836. std::stringstream buffer;
  10837. buffer << data;
  10838. Client cli("https://localhost:8080");
  10839. UploadFormDataItems items{
  10840. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10841. {"hello", "world", "", ""},
  10842. };
  10843. for (const char &c : " \t\r\n") {
  10844. auto res =
  10845. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10846. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10847. ASSERT_FALSE(res);
  10848. }
  10849. }
  10850. TEST(MultipartFormDataTest, PutFormData) {
  10851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10852. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10853. const ContentReader &content_reader) {
  10854. if (req.is_multipart_form_data()) {
  10855. std::vector<FormData> items;
  10856. content_reader(
  10857. [&](const FormData &file) {
  10858. items.push_back(file);
  10859. return true;
  10860. },
  10861. [&](const char *data, size_t data_length) {
  10862. items.back().content.append(data, data_length);
  10863. return true;
  10864. });
  10865. EXPECT_TRUE(std::string(items[0].name) == "document");
  10866. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10867. EXPECT_TRUE(items[0].filename == "2MB_data");
  10868. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10869. EXPECT_TRUE(items[1].name == "hello");
  10870. EXPECT_TRUE(items[1].content == "world");
  10871. EXPECT_TRUE(items[1].filename == "");
  10872. EXPECT_TRUE(items[1].content_type == "");
  10873. } else {
  10874. std::string body;
  10875. content_reader([&](const char *data, size_t data_length) {
  10876. body.append(data, data_length);
  10877. return true;
  10878. });
  10879. }
  10880. });
  10881. auto port = svr.bind_to_any_port("localhost");
  10882. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. {
  10890. std::string data(1024 * 1024 * 2, '&');
  10891. std::stringstream buffer;
  10892. buffer << data;
  10893. SSLClient cli("localhost", port);
  10894. cli.enable_server_certificate_verification(false);
  10895. UploadFormDataItems items{
  10896. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10897. {"hello", "world", "", ""},
  10898. };
  10899. auto res = cli.Put("/put", items);
  10900. ASSERT_TRUE(res);
  10901. ASSERT_EQ(StatusCode::OK_200, res->status);
  10902. }
  10903. }
  10904. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10906. svr.Put("/put_customboundary",
  10907. [&](const Request &req, const Response & /*res*/,
  10908. const ContentReader &content_reader) {
  10909. if (req.is_multipart_form_data()) {
  10910. std::vector<FormData> items;
  10911. content_reader(
  10912. [&](const FormData &file) {
  10913. items.push_back(file);
  10914. return true;
  10915. },
  10916. [&](const char *data, size_t data_length) {
  10917. items.back().content.append(data, data_length);
  10918. return true;
  10919. });
  10920. EXPECT_TRUE(std::string(items[0].name) == "document");
  10921. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10922. EXPECT_TRUE(items[0].filename == "2MB_data");
  10923. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10924. EXPECT_TRUE(items[1].name == "hello");
  10925. EXPECT_TRUE(items[1].content == "world");
  10926. EXPECT_TRUE(items[1].filename == "");
  10927. EXPECT_TRUE(items[1].content_type == "");
  10928. } else {
  10929. std::string body;
  10930. content_reader([&](const char *data, size_t data_length) {
  10931. body.append(data, data_length);
  10932. return true;
  10933. });
  10934. }
  10935. });
  10936. auto port = svr.bind_to_any_port("localhost");
  10937. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. {
  10945. std::string data(1024 * 1024 * 2, '&');
  10946. std::stringstream buffer;
  10947. buffer << data;
  10948. SSLClient cli("localhost", port);
  10949. cli.enable_server_certificate_verification(false);
  10950. UploadFormDataItems items{
  10951. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10952. {"hello", "world", "", ""},
  10953. };
  10954. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10955. ASSERT_TRUE(res);
  10956. ASSERT_EQ(StatusCode::OK_200, res->status);
  10957. }
  10958. }
  10959. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10960. std::string data(1024 * 1024 * 2, '&');
  10961. std::stringstream buffer;
  10962. buffer << data;
  10963. Client cli("https://localhost:8080");
  10964. cli.enable_server_certificate_verification(false);
  10965. UploadFormDataItems items{
  10966. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10967. {"hello", "world", "", ""},
  10968. };
  10969. for (const char &c : " \t\r\n") {
  10970. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10971. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10972. ASSERT_FALSE(res);
  10973. }
  10974. }
  10975. TEST(MultipartFormDataTest, AlternateFilename) {
  10976. auto handled = false;
  10977. Server svr;
  10978. svr.Post("/test", [&](const Request &req, Response &res) {
  10979. ASSERT_EQ(2u, req.form.files.size());
  10980. ASSERT_EQ(1u, req.form.fields.size());
  10981. // Test files
  10982. const auto &file1 = req.form.get_file("file1");
  10983. ASSERT_EQ("file1", file1.name);
  10984. ASSERT_EQ("A.txt", file1.filename);
  10985. ASSERT_EQ("text/plain", file1.content_type);
  10986. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10987. const auto &file2 = req.form.get_file("file2");
  10988. ASSERT_EQ("file2", file2.name);
  10989. ASSERT_EQ("a.html", file2.filename);
  10990. ASSERT_EQ("text/html", file2.content_type);
  10991. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10992. file2.content);
  10993. // Test text field
  10994. const auto &text = req.form.get_field("text");
  10995. ASSERT_EQ("text default", text);
  10996. res.set_content("ok", "text/plain");
  10997. handled = true;
  10998. });
  10999. thread t = thread([&] { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. ASSERT_TRUE(handled);
  11005. });
  11006. svr.wait_until_ready();
  11007. auto req = "POST /test HTTP/1.1\r\n"
  11008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11009. "Content-Length: 399\r\n"
  11010. "\r\n"
  11011. "----------\r\n"
  11012. "Content-Disposition: form-data; name=\"text\"\r\n"
  11013. "\r\n"
  11014. "text default\r\n"
  11015. "----------\r\n"
  11016. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11017. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11018. "Content-Type: text/plain\r\n"
  11019. "\r\n"
  11020. "Content of a.txt.\r\n"
  11021. "\r\n"
  11022. "----------\r\n"
  11023. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11024. "\"a.html\"\r\n"
  11025. "Content-Type: text/html\r\n"
  11026. "\r\n"
  11027. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11028. "\r\n"
  11029. "------------\r\n";
  11030. ASSERT_TRUE(send_request(1, req));
  11031. }
  11032. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11033. auto handled = false;
  11034. Server svr;
  11035. svr.Post("/test", [&](const Request &req, Response &res) {
  11036. // Case-insensitive "utf-8''" prefix with a long value
  11037. const auto &file = req.form.get_file("file1");
  11038. ASSERT_EQ("file1", file.name);
  11039. // 8000 chars exercises both the Content-Disposition parser and the
  11040. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11041. // Prior to the fix, std::regex_match on this header would cause O(N)
  11042. // stack recursion in libstdc++, leading to SIGSEGV.
  11043. std::string expected_filename(8000, 'A');
  11044. ASSERT_EQ(expected_filename, file.filename);
  11045. res.set_content("ok", "text/plain");
  11046. handled = true;
  11047. });
  11048. thread t = thread([&] { svr.listen(HOST, PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. t.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. ASSERT_TRUE(handled);
  11054. });
  11055. svr.wait_until_ready();
  11056. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11057. // Regression test for GHSA-qq6v-r583-3h69
  11058. std::string long_filename(8000, 'A');
  11059. std::string body = "----------\r\n"
  11060. "Content-Disposition: form-data; name=\"file1\"; "
  11061. "filename*=\"Utf-8''" +
  11062. long_filename +
  11063. "\"\r\n"
  11064. "\r\n"
  11065. "hello\r\n"
  11066. "------------\r\n";
  11067. auto req = "POST /test HTTP/1.1\r\n"
  11068. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11069. "Content-Length: " +
  11070. std::to_string(body.size()) + "\r\n\r\n" + body;
  11071. ASSERT_TRUE(send_request(1, req));
  11072. }
  11073. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11074. auto handled = false;
  11075. Server svr;
  11076. svr.Post("/test", [&](const Request &req, Response &) {
  11077. ASSERT_EQ(2u, req.form.fields.size());
  11078. const auto &text1 = req.form.get_field("text1");
  11079. ASSERT_EQ("text1", text1);
  11080. const auto &text2 = req.form.get_field("text2");
  11081. ASSERT_EQ("text2", text2);
  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. auto req = "POST /test HTTP/1.1\r\n"
  11093. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11094. "Content-Length: 146\r\n"
  11095. "\r\n----------\r\n"
  11096. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11097. "\r\n"
  11098. "text1"
  11099. "\r\n----------\r\n"
  11100. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11101. "\r\n"
  11102. "text2"
  11103. "\r\n------------";
  11104. std::string response;
  11105. ASSERT_TRUE(send_request(1, req, &response));
  11106. ASSERT_EQ("200", response.substr(9, 3));
  11107. }
  11108. TEST(MultipartFormDataTest, ContentLength) {
  11109. auto handled = false;
  11110. Server svr;
  11111. svr.Post("/test", [&](const Request &req, Response &) {
  11112. ASSERT_EQ(2u, req.form.fields.size());
  11113. const auto &text1 = req.form.get_field("text1");
  11114. ASSERT_EQ("text1", text1);
  11115. const auto &text2 = req.form.get_field("text2");
  11116. ASSERT_EQ("text2", text2);
  11117. handled = true;
  11118. });
  11119. thread t = thread([&] { svr.listen(HOST, PORT); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. t.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. ASSERT_TRUE(handled);
  11125. });
  11126. svr.wait_until_ready();
  11127. auto req = "POST /test HTTP/1.1\r\n"
  11128. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11129. "Content-Length: 167\r\n"
  11130. "\r\n----------\r\n"
  11131. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11132. "Content-Length: 5\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------------\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, AccessPartHeaders) {
  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. // TODO: Add header access for text fields if needed
  11152. const auto &text2 = req.form.get_field("text2");
  11153. ASSERT_EQ("text2", text2);
  11154. // TODO: Header access for text fields needs to be implemented
  11155. // auto &headers = it->second.headers;
  11156. // ASSERT_EQ(3U, headers.size());
  11157. // auto custom_header = headers.find("x-whatever");
  11158. // ASSERT_TRUE(custom_header != headers.end());
  11159. // ASSERT_NE("customvalue", custom_header->second);
  11160. // ASSERT_EQ("CustomValue", custom_header->second);
  11161. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11162. handled = true;
  11163. });
  11164. thread t = thread([&] { svr.listen(HOST, PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. ASSERT_TRUE(handled);
  11170. });
  11171. svr.wait_until_ready();
  11172. auto req = "POST /test HTTP/1.1\r\n"
  11173. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11174. "Content-Length: 232\r\n"
  11175. "\r\n----------\r\n"
  11176. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11177. "Content-Length: 5\r\n"
  11178. "X-Test: 1\r\n"
  11179. "\r\n"
  11180. "text1"
  11181. "\r\n----------\r\n"
  11182. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11183. "Content-Type: text/plain\r\n"
  11184. "X-Whatever: CustomValue\r\n"
  11185. "\r\n"
  11186. "text2"
  11187. "\r\n------------\r\n"
  11188. "That should be disregarded. Not even read";
  11189. std::string response;
  11190. ASSERT_TRUE(send_request(1, req, &response));
  11191. ASSERT_EQ("200", response.substr(9, 3));
  11192. }
  11193. TEST(MultipartFormDataTest, LargeHeader) {
  11194. auto handled = false;
  11195. Server svr;
  11196. svr.Post("/test", [&](const Request &req, Response &) {
  11197. ASSERT_EQ(1u, req.form.fields.size());
  11198. const auto &text = req.form.get_field("name1");
  11199. ASSERT_EQ("text1", text);
  11200. handled = true;
  11201. });
  11202. thread t = thread([&] { svr.listen(HOST, PORT); });
  11203. auto se = detail::scope_exit([&] {
  11204. svr.stop();
  11205. t.join();
  11206. ASSERT_FALSE(svr.is_running());
  11207. ASSERT_TRUE(handled);
  11208. });
  11209. svr.wait_until_ready();
  11210. auto boundary = std::string("cpp-httplib-multipart-data");
  11211. std::string content = "--" + boundary +
  11212. "\r\n"
  11213. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11214. "\r\n"
  11215. "text1\r\n"
  11216. "--" +
  11217. boundary + "--\r\n";
  11218. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11219. "Content-Type: multipart/form-data;boundary=" +
  11220. boundary +
  11221. "\r\n"
  11222. "Content-Length: " +
  11223. std::to_string(content.size()) +
  11224. "\r\n"
  11225. "Dummy-Header: ";
  11226. std::string header_suffix = "\r\n"
  11227. "\r\n";
  11228. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11229. size_t header_dummy_size =
  11230. read_buff_size -
  11231. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11232. auto header_dummy = std::string(header_dummy_size, '@');
  11233. auto req = header_prefix + header_dummy + header_suffix + content;
  11234. std::string response;
  11235. ASSERT_TRUE(send_request(1, req, &response));
  11236. ASSERT_EQ("200", response.substr(9, 3));
  11237. }
  11238. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11239. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11240. // (not chunked Transfer-Encoding) after the streaming refactor.
  11241. auto handled = false;
  11242. Server svr;
  11243. svr.Post("/upload", [&](const Request &req, Response &res) {
  11244. auto cl_it = req.headers.find("Content-Length");
  11245. EXPECT_TRUE(cl_it != req.headers.end());
  11246. auto te_it = req.headers.find("Transfer-Encoding");
  11247. EXPECT_TRUE(te_it == req.headers.end());
  11248. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11249. res.set_content("ok", "text/plain");
  11250. handled = true;
  11251. });
  11252. auto port = svr.bind_to_any_port(HOST);
  11253. auto t = thread([&] { svr.listen_after_bind(); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. t.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. ASSERT_TRUE(handled);
  11259. });
  11260. svr.wait_until_ready();
  11261. UploadFormDataItems items = {
  11262. {"field1", "hello", "", "text/plain"},
  11263. {"file1", "world", "test.txt", "application/octet-stream"},
  11264. };
  11265. Client cli(HOST, port);
  11266. auto res = cli.Post("/upload", {}, items);
  11267. ASSERT_TRUE(res);
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. }
  11270. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11271. // Verify that make_multipart_content_provider coalesces many small segments
  11272. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11273. constexpr size_t kItemCount = 1000;
  11274. UploadFormDataItems items;
  11275. items.reserve(kItemCount);
  11276. for (size_t i = 0; i < kItemCount; i++) {
  11277. items.push_back(
  11278. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11279. }
  11280. const std::string boundary = "----test-boundary";
  11281. auto content_length = detail::get_multipart_content_length(items, boundary);
  11282. auto provider = detail::make_multipart_content_provider(items, boundary);
  11283. // Drive the provider the same way write_content_with_progress does
  11284. size_t write_count = 0;
  11285. size_t total_bytes = 0;
  11286. DataSink sink;
  11287. size_t offset = 0;
  11288. sink.write = [&](const char *d, size_t l) -> bool {
  11289. (void)d;
  11290. write_count++;
  11291. total_bytes += l;
  11292. offset += l;
  11293. return true;
  11294. };
  11295. sink.is_writable = []() -> bool { return true; };
  11296. while (offset < content_length) {
  11297. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11298. }
  11299. EXPECT_EQ(content_length, total_bytes);
  11300. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11301. // With buffering into 64KB blocks, write_count should be much smaller.
  11302. auto segment_count = 3 * kItemCount + 1;
  11303. EXPECT_LT(write_count, segment_count / 10);
  11304. }
  11305. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11306. // Integration test: send many UploadFormDataItems and verify the server
  11307. // receives all of them correctly (#2410).
  11308. constexpr size_t kItemCount = 500;
  11309. auto handled = false;
  11310. Server svr;
  11311. svr.Post("/upload", [&](const Request &req, Response &res) {
  11312. EXPECT_EQ(kItemCount, req.form.fields.size());
  11313. for (size_t i = 0; i < kItemCount; i++) {
  11314. auto key = "field" + std::to_string(i);
  11315. auto val = "value" + std::to_string(i);
  11316. auto it = req.form.fields.find(key);
  11317. if (it != req.form.fields.end()) {
  11318. EXPECT_EQ(val, it->second.content);
  11319. } else {
  11320. ADD_FAILURE() << "Missing field: " << key;
  11321. }
  11322. }
  11323. res.set_content("ok", "text/plain");
  11324. handled = true;
  11325. });
  11326. auto port = svr.bind_to_any_port(HOST);
  11327. auto t = thread([&] { svr.listen_after_bind(); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. t.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. ASSERT_TRUE(handled);
  11333. });
  11334. svr.wait_until_ready();
  11335. UploadFormDataItems items;
  11336. items.reserve(kItemCount);
  11337. for (size_t i = 0; i < kItemCount; i++) {
  11338. items.push_back(
  11339. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11340. }
  11341. Client cli(HOST, port);
  11342. auto res = cli.Post("/upload", items);
  11343. ASSERT_TRUE(res);
  11344. EXPECT_EQ(StatusCode::OK_200, res->status);
  11345. }
  11346. TEST(MultipartFormDataTest, MakeFileProvider) {
  11347. // Verify make_file_provider sends a file's contents correctly.
  11348. const std::string file_content(4096, 'Z');
  11349. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11350. {
  11351. std::ofstream ofs(tmp_path, std::ios::binary);
  11352. ofs.write(file_content.data(),
  11353. static_cast<std::streamsize>(file_content.size()));
  11354. }
  11355. auto handled = false;
  11356. Server svr;
  11357. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11358. const ContentReader &content_reader) {
  11359. ASSERT_TRUE(req.is_multipart_form_data());
  11360. std::vector<FormData> items;
  11361. content_reader(
  11362. [&](const FormData &file) {
  11363. items.push_back(file);
  11364. return true;
  11365. },
  11366. [&](const char *data, size_t data_length) {
  11367. items.back().content.append(data, data_length);
  11368. return true;
  11369. });
  11370. ASSERT_EQ(1u, items.size());
  11371. EXPECT_EQ("myfile", items[0].name);
  11372. EXPECT_EQ("data.bin", items[0].filename);
  11373. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11374. EXPECT_EQ(file_content, items[0].content);
  11375. handled = true;
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. auto t = thread([&] { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. ASSERT_FALSE(svr.is_running());
  11383. ASSERT_TRUE(handled);
  11384. std::remove(tmp_path.c_str());
  11385. });
  11386. svr.wait_until_ready();
  11387. FormDataProviderItems providers;
  11388. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11389. "application/octet-stream"));
  11390. Client cli(HOST, port);
  11391. auto res = cli.Post("/upload", {}, {}, providers);
  11392. ASSERT_TRUE(res);
  11393. EXPECT_EQ(StatusCode::OK_200, res->status);
  11394. }
  11395. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11396. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11397. // (100) headers is rejected with a 400 Bad Request response.
  11398. Server svr;
  11399. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11400. res.set_content("ok", "text/plain");
  11401. });
  11402. thread t = thread([&] { svr.listen(HOST, PORT); });
  11403. auto se = detail::scope_exit([&] {
  11404. svr.stop();
  11405. t.join();
  11406. ASSERT_FALSE(svr.is_running());
  11407. });
  11408. svr.wait_until_ready();
  11409. // Build a multipart part with 101 custom headers (exceeding CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11410. std::stringstream body;
  11411. body << "--simpleboundary\r\n"
  11412. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11413. for (int i = 0; i < 101; i++) {
  11414. body << "X-Custom-Header-" << i << ": value\r\n";
  11415. }
  11416. body << "\r\n"
  11417. << "value1\r\n"
  11418. << "--simpleboundary--\r\n";
  11419. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11420. Client cli(HOST, PORT);
  11421. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11422. ASSERT_TRUE(res);
  11423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11424. }
  11425. TEST(MakeFileBodyTest, Basic) {
  11426. const std::string file_content(4096, 'Z');
  11427. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11428. {
  11429. std::ofstream ofs(tmp_path, std::ios::binary);
  11430. ofs.write(file_content.data(),
  11431. static_cast<std::streamsize>(file_content.size()));
  11432. }
  11433. auto handled = false;
  11434. Server svr;
  11435. svr.Post("/upload", [&](const Request &req, Response &res) {
  11436. EXPECT_EQ(file_content, req.body);
  11437. handled = true;
  11438. res.status = StatusCode::OK_200;
  11439. });
  11440. auto port = svr.bind_to_any_port(HOST);
  11441. auto t = thread([&] { svr.listen_after_bind(); });
  11442. auto se = detail::scope_exit([&] {
  11443. svr.stop();
  11444. t.join();
  11445. ASSERT_FALSE(svr.is_running());
  11446. ASSERT_TRUE(handled);
  11447. std::remove(tmp_path.c_str());
  11448. });
  11449. svr.wait_until_ready();
  11450. auto fb = make_file_body(tmp_path);
  11451. ASSERT_GT(fb.first, 0u);
  11452. Client cli(HOST, port);
  11453. auto res =
  11454. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11455. ASSERT_TRUE(res);
  11456. EXPECT_EQ(StatusCode::OK_200, res->status);
  11457. }
  11458. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11459. static constexpr unsigned int number_of_tasks{1000000};
  11460. std::atomic_uint count{0};
  11461. std::unique_ptr<TaskQueue> task_queue{
  11462. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11463. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11464. auto queued = task_queue->enqueue(
  11465. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11466. EXPECT_TRUE(queued);
  11467. }
  11468. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11469. task_queue->shutdown();
  11470. #else
  11471. EXPECT_NO_THROW(task_queue->shutdown());
  11472. #endif
  11473. EXPECT_EQ(number_of_tasks, count.load());
  11474. }
  11475. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11476. static constexpr unsigned int number_of_tasks{1000000};
  11477. static constexpr unsigned int qlimit{2};
  11478. unsigned int queued_count{0};
  11479. std::atomic_uint count{0};
  11480. std::unique_ptr<TaskQueue> task_queue{
  11481. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11482. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11483. if (task_queue->enqueue(
  11484. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11485. queued_count++;
  11486. }
  11487. }
  11488. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11489. task_queue->shutdown();
  11490. #else
  11491. EXPECT_NO_THROW(task_queue->shutdown());
  11492. #endif
  11493. EXPECT_EQ(queued_count, count.load());
  11494. EXPECT_TRUE(queued_count <= number_of_tasks);
  11495. EXPECT_TRUE(queued_count >= qlimit);
  11496. }
  11497. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11498. // Use a short idle timeout so a dynamic thread spawns, times out and
  11499. // exits during the test, and the pool keeps working afterwards.
  11500. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11501. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11502. /*idle_timeout_sec=*/1}};
  11503. std::atomic_uint count{0};
  11504. std::condition_variable cv;
  11505. std::mutex mtx;
  11506. bool release = false;
  11507. // Block the base thread so the second task spawns a dynamic thread.
  11508. EXPECT_TRUE(task_queue->enqueue([&] {
  11509. std::unique_lock<std::mutex> lock(mtx);
  11510. while (!release) {
  11511. cv.wait(lock);
  11512. }
  11513. count++;
  11514. }));
  11515. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11516. // Let the dynamic thread finish its task and exceed the idle timeout.
  11517. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11518. {
  11519. std::unique_lock<std::mutex> lock(mtx);
  11520. release = true;
  11521. }
  11522. cv.notify_all();
  11523. // The pool must still accept and run tasks after the dynamic thread exited.
  11524. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11525. task_queue->shutdown();
  11526. EXPECT_EQ(3u, count.load());
  11527. }
  11528. TEST(TaskQueueTest, MaxQueuedRequests) {
  11529. static constexpr unsigned int qlimit{3};
  11530. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11531. std::condition_variable sem_cv;
  11532. std::mutex sem_mtx;
  11533. int credits = 0;
  11534. bool queued;
  11535. /* Fill up the queue with tasks that will block until we give them credits to
  11536. * complete. */
  11537. for (unsigned int n = 0; n <= qlimit;) {
  11538. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11539. std::unique_lock<std::mutex> lock(sem_mtx);
  11540. while (credits <= 0) {
  11541. sem_cv.wait(lock);
  11542. }
  11543. /* Consume the credit and signal the test code if they are all gone. */
  11544. if (--credits == 0) { sem_cv.notify_one(); }
  11545. });
  11546. if (n < qlimit) {
  11547. /* The first qlimit enqueues must succeed. */
  11548. EXPECT_TRUE(queued);
  11549. } else {
  11550. /* The last one will succeed only when the worker thread
  11551. * starts and dequeues the first blocking task. Although
  11552. * not necessary for the correctness of this test, we sleep for
  11553. * a short while to avoid busy waiting. */
  11554. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11555. }
  11556. if (queued) { n++; }
  11557. }
  11558. /* Further enqueues must fail since the queue is full. */
  11559. for (auto i = 0; i < 4; i++) {
  11560. queued = task_queue->enqueue([] {});
  11561. EXPECT_FALSE(queued);
  11562. }
  11563. /* Give the credits to allow the previous tasks to complete. */
  11564. {
  11565. std::unique_lock<std::mutex> lock(sem_mtx);
  11566. credits += qlimit + 1;
  11567. }
  11568. sem_cv.notify_all();
  11569. /* Wait for all the credits to be consumed. */
  11570. {
  11571. std::unique_lock<std::mutex> lock(sem_mtx);
  11572. while (credits > 0) {
  11573. sem_cv.wait(lock);
  11574. }
  11575. }
  11576. /* Check that we are able again to enqueue at least qlimit tasks. */
  11577. for (unsigned int i = 0; i < qlimit; i++) {
  11578. queued = task_queue->enqueue([] {});
  11579. EXPECT_TRUE(queued);
  11580. }
  11581. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11582. task_queue->shutdown();
  11583. #else
  11584. EXPECT_NO_THROW(task_queue->shutdown());
  11585. #endif
  11586. }
  11587. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11588. Server svr;
  11589. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11590. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11591. });
  11592. svr.Get("/hello", [](const Request &req, Response &res) {
  11593. res.set_content(req.get_param_value("key"), "text/plain");
  11594. });
  11595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11596. auto se = detail::scope_exit([&] {
  11597. svr.stop();
  11598. thread.join();
  11599. ASSERT_FALSE(svr.is_running());
  11600. });
  11601. svr.wait_until_ready();
  11602. {
  11603. Client cli(HOST, PORT);
  11604. cli.set_follow_location(true);
  11605. auto res = cli.Get("/");
  11606. ASSERT_TRUE(res);
  11607. EXPECT_EQ(StatusCode::OK_200, res->status);
  11608. EXPECT_EQ("val&key2=val2", res->body);
  11609. }
  11610. }
  11611. #endif
  11612. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11613. Server svr;
  11614. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11615. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11616. });
  11617. svr.Get("/hello", [](const Request &req, Response &res) {
  11618. res.set_content(req.get_param_value("key"), "text/plain");
  11619. });
  11620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11621. auto se = detail::scope_exit([&] {
  11622. svr.stop();
  11623. thread.join();
  11624. ASSERT_FALSE(svr.is_running());
  11625. });
  11626. svr.wait_until_ready();
  11627. {
  11628. Client cli(HOST, PORT);
  11629. cli.set_follow_location(true);
  11630. auto res = cli.Get("/");
  11631. ASSERT_TRUE(res);
  11632. EXPECT_EQ(StatusCode::OK_200, res->status);
  11633. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11634. }
  11635. }
  11636. TEST(RedirectTest, RedirectWithPlusInPath) {
  11637. Server svr;
  11638. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11639. res.set_redirect("/a+b");
  11640. });
  11641. // Route pattern uses regex; escape + as \\+
  11642. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11643. res.set_content(req.path, "text/plain");
  11644. });
  11645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. thread.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. });
  11651. svr.wait_until_ready();
  11652. {
  11653. Client cli(HOST, PORT);
  11654. cli.set_follow_location(true);
  11655. auto res = cli.Get("/");
  11656. ASSERT_TRUE(res);
  11657. EXPECT_EQ(StatusCode::OK_200, res->status);
  11658. EXPECT_EQ("/a+b", res->body);
  11659. }
  11660. }
  11661. #ifdef CPPHTTPLIB_SSL_ENABLED
  11662. TEST(RedirectTest, Issue2185_Online) {
  11663. SSLClient client("github.com");
  11664. client.set_follow_location(true);
  11665. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11666. "Coollab-Windows.zip");
  11667. ASSERT_TRUE(res);
  11668. EXPECT_EQ(StatusCode::OK_200, res->status);
  11669. EXPECT_EQ(9920427U, res->body.size());
  11670. }
  11671. #endif
  11672. TEST(VulnerabilityTest, CRLFInjection) {
  11673. Server svr;
  11674. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11675. res.set_content("Hello 1", "text/plain");
  11676. });
  11677. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11678. res.set_content("Hello 2", "text/plain");
  11679. });
  11680. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11681. res.set_content("Hello 3", "text/plain");
  11682. });
  11683. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11684. res.set_content("Hello 4", "text/plain");
  11685. });
  11686. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11687. for (const auto &x : req.headers) {
  11688. auto key = x.first;
  11689. EXPECT_STRNE("evil", key.c_str());
  11690. }
  11691. });
  11692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11693. auto se = detail::scope_exit([&] {
  11694. svr.stop();
  11695. thread.join();
  11696. ASSERT_FALSE(svr.is_running());
  11697. });
  11698. svr.wait_until_ready();
  11699. {
  11700. Client cli(HOST, PORT);
  11701. cli.Post("/test1", "A=B",
  11702. "application/x-www-form-urlencoded\r\nevil: hello1");
  11703. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11704. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11705. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11706. }
  11707. }
  11708. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11709. auto server_thread = std::thread([] {
  11710. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11711. default_socket_options(srv);
  11712. sockaddr_in addr{};
  11713. addr.sin_family = AF_INET;
  11714. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11715. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11716. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11717. ::listen(srv, 1);
  11718. sockaddr_in cli_addr{};
  11719. socklen_t cli_len = sizeof(cli_addr);
  11720. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11721. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11722. std::string buf_all;
  11723. char buf[2048];
  11724. ssize_t n;
  11725. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11726. buf_all.append(buf, static_cast<size_t>(n));
  11727. size_t pos;
  11728. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11729. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11730. auto e = request_block.find("\r\n");
  11731. if (e != std::string::npos) {
  11732. auto request_line = request_block.substr(0, e);
  11733. std::string msg =
  11734. "CRLF injection detected in request line: '" + request_line + "'";
  11735. EXPECT_FALSE(true) << msg;
  11736. }
  11737. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11738. ::send(cli,
  11739. #ifdef _WIN32
  11740. static_cast<const char *>(resp.c_str()),
  11741. static_cast<int>(resp.size()),
  11742. #else
  11743. resp.c_str(), resp.size(),
  11744. #endif
  11745. 0);
  11746. buf_all.erase(0, pos + 4);
  11747. }
  11748. }
  11749. detail::close_socket(cli);
  11750. detail::close_socket(srv);
  11751. });
  11752. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11753. auto cli = Client("127.0.0.1", PORT + 1);
  11754. auto headers = Headers{
  11755. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11756. {"Connection", "keep-alive"}};
  11757. auto res = cli.Get("/hi", headers);
  11758. EXPECT_FALSE(res);
  11759. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11760. server_thread.join();
  11761. }
  11762. TEST(PathParamsTest, StaticMatch) {
  11763. const auto pattern = "/users/all";
  11764. detail::PathParamsMatcher matcher(pattern);
  11765. Request request;
  11766. request.path = "/users/all";
  11767. ASSERT_TRUE(matcher.match(request));
  11768. std::unordered_map<std::string, std::string> expected_params = {};
  11769. EXPECT_EQ(request.path_params, expected_params);
  11770. }
  11771. TEST(PathParamsTest, StaticMismatch) {
  11772. const auto pattern = "/users/all";
  11773. detail::PathParamsMatcher matcher(pattern);
  11774. Request request;
  11775. request.path = "/users/1";
  11776. ASSERT_FALSE(matcher.match(request));
  11777. }
  11778. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11779. const auto pattern = "/users/:id/subscriptions";
  11780. detail::PathParamsMatcher matcher(pattern);
  11781. Request request;
  11782. request.path = "/users/42/subscriptions";
  11783. ASSERT_TRUE(matcher.match(request));
  11784. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11785. EXPECT_EQ(request.path_params, expected_params);
  11786. }
  11787. TEST(PathParamsTest, SingleParamInTheEnd) {
  11788. const auto pattern = "/users/:id";
  11789. detail::PathParamsMatcher matcher(pattern);
  11790. Request request;
  11791. request.path = "/users/24";
  11792. ASSERT_TRUE(matcher.match(request));
  11793. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11794. EXPECT_EQ(request.path_params, expected_params);
  11795. }
  11796. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11797. const auto pattern = "/users/:id/";
  11798. detail::PathParamsMatcher matcher(pattern);
  11799. Request request;
  11800. request.path = "/users/42/";
  11801. ASSERT_TRUE(matcher.match(request));
  11802. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11803. EXPECT_EQ(request.path_params, expected_params);
  11804. }
  11805. TEST(PathParamsTest, EmptyParam) {
  11806. const auto pattern = "/users/:id/";
  11807. detail::PathParamsMatcher matcher(pattern);
  11808. Request request;
  11809. request.path = "/users//";
  11810. ASSERT_TRUE(matcher.match(request));
  11811. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11812. EXPECT_EQ(request.path_params, expected_params);
  11813. }
  11814. TEST(PathParamsTest, FragmentMismatch) {
  11815. const auto pattern = "/users/:id/";
  11816. detail::PathParamsMatcher matcher(pattern);
  11817. Request request;
  11818. request.path = "/admins/24/";
  11819. ASSERT_FALSE(matcher.match(request));
  11820. }
  11821. TEST(PathParamsTest, ExtraFragments) {
  11822. const auto pattern = "/users/:id";
  11823. detail::PathParamsMatcher matcher(pattern);
  11824. Request request;
  11825. request.path = "/users/42/subscriptions";
  11826. ASSERT_FALSE(matcher.match(request));
  11827. }
  11828. TEST(PathParamsTest, MissingTrailingParam) {
  11829. const auto pattern = "/users/:id";
  11830. detail::PathParamsMatcher matcher(pattern);
  11831. Request request;
  11832. request.path = "/users";
  11833. ASSERT_FALSE(matcher.match(request));
  11834. }
  11835. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11836. const auto pattern = "/users/:id/subscriptions";
  11837. detail::PathParamsMatcher matcher(pattern);
  11838. Request request;
  11839. request.path = "/users/subscriptions";
  11840. ASSERT_FALSE(matcher.match(request));
  11841. }
  11842. TEST(PathParamsTest, MultipleParams) {
  11843. const auto pattern = "/users/:userid/subscriptions/:subid";
  11844. detail::PathParamsMatcher matcher(pattern);
  11845. Request request;
  11846. request.path = "/users/42/subscriptions/2";
  11847. ASSERT_TRUE(matcher.match(request));
  11848. std::unordered_map<std::string, std::string> expected_params = {
  11849. {"userid", "42"}, {"subid", "2"}};
  11850. EXPECT_EQ(request.path_params, expected_params);
  11851. }
  11852. TEST(PathParamsTest, SequenceOfParams) {
  11853. const auto pattern = "/values/:x/:y/:z";
  11854. detail::PathParamsMatcher matcher(pattern);
  11855. Request request;
  11856. request.path = "/values/1/2/3";
  11857. ASSERT_TRUE(matcher.match(request));
  11858. std::unordered_map<std::string, std::string> expected_params = {
  11859. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11860. EXPECT_EQ(request.path_params, expected_params);
  11861. }
  11862. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11863. const auto pattern = "/prefix:suffix";
  11864. detail::PathParamsMatcher matcher(pattern);
  11865. Request request;
  11866. request.path = "/prefix:suffix";
  11867. ASSERT_TRUE(matcher.match(request));
  11868. const std::unordered_map<std::string, std::string> expected_params = {};
  11869. EXPECT_EQ(request.path_params, expected_params);
  11870. }
  11871. TEST(ParseUrlTest, VariousPatterns) {
  11872. {
  11873. detail::UrlComponents uc;
  11874. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11875. EXPECT_EQ("http", uc.scheme);
  11876. EXPECT_EQ("example.com", uc.host);
  11877. EXPECT_EQ("8080", uc.port);
  11878. EXPECT_EQ("/path", uc.path);
  11879. EXPECT_EQ("?q=1", uc.query);
  11880. }
  11881. {
  11882. detail::UrlComponents uc;
  11883. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11884. EXPECT_EQ("https", uc.scheme);
  11885. EXPECT_EQ("example.com", uc.host);
  11886. EXPECT_TRUE(uc.port.empty());
  11887. EXPECT_EQ("/path", uc.path);
  11888. }
  11889. {
  11890. detail::UrlComponents uc;
  11891. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11892. EXPECT_EQ("::1", uc.host);
  11893. EXPECT_EQ("8080", uc.port);
  11894. EXPECT_EQ("/path", uc.path);
  11895. }
  11896. {
  11897. detail::UrlComponents uc;
  11898. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11899. }
  11900. {
  11901. detail::UrlComponents uc;
  11902. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11903. EXPECT_TRUE(uc.scheme.empty());
  11904. EXPECT_EQ("example.com", uc.host);
  11905. EXPECT_EQ("/path", uc.path);
  11906. EXPECT_EQ("?q=1", uc.query);
  11907. }
  11908. {
  11909. detail::UrlComponents uc;
  11910. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11911. EXPECT_TRUE(uc.host.empty());
  11912. EXPECT_EQ("/path", uc.path);
  11913. EXPECT_EQ("?q=1", uc.query);
  11914. }
  11915. {
  11916. detail::UrlComponents uc;
  11917. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11918. EXPECT_EQ("example.com", uc.host);
  11919. EXPECT_EQ("8080", uc.port);
  11920. }
  11921. {
  11922. // Unix socket path — must not be parsed as host
  11923. detail::UrlComponents uc;
  11924. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11925. EXPECT_TRUE(uc.host.empty());
  11926. }
  11927. {
  11928. detail::UrlComponents uc;
  11929. ASSERT_TRUE(detail::parse_url("", uc));
  11930. EXPECT_TRUE(uc.host.empty());
  11931. EXPECT_TRUE(uc.path.empty());
  11932. }
  11933. {
  11934. detail::UrlComponents uc;
  11935. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11936. }
  11937. {
  11938. detail::UrlComponents uc;
  11939. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11940. }
  11941. {
  11942. // Accepted by parse_url; callers restrict to http/https
  11943. detail::UrlComponents uc;
  11944. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11945. EXPECT_EQ("ftp", uc.scheme);
  11946. }
  11947. {
  11948. detail::UrlComponents uc;
  11949. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11950. }
  11951. {
  11952. detail::UrlComponents uc;
  11953. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11954. }
  11955. }
  11956. TEST(ParseUrlTest, FragmentHandling) {
  11957. {
  11958. detail::UrlComponents uc;
  11959. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11960. EXPECT_EQ("/path", uc.path);
  11961. EXPECT_TRUE(uc.query.empty());
  11962. }
  11963. {
  11964. detail::UrlComponents uc;
  11965. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11966. EXPECT_TRUE(uc.path.empty());
  11967. EXPECT_TRUE(uc.query.empty());
  11968. }
  11969. }
  11970. TEST(ParseUrlTest, UserinfoHandling) {
  11971. // Userinfo with @ but no colon — host includes @
  11972. detail::UrlComponents uc;
  11973. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11974. EXPECT_EQ("user@host.com", uc.host);
  11975. EXPECT_EQ("/path", uc.path);
  11976. }
  11977. TEST(ParseUrlTest, IPv6EdgeCases) {
  11978. {
  11979. detail::UrlComponents uc;
  11980. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11981. EXPECT_TRUE(uc.scheme.empty());
  11982. EXPECT_EQ("::1", uc.host);
  11983. EXPECT_EQ("8080", uc.port);
  11984. }
  11985. {
  11986. // Zone ID '%25' is not in [a-fA-F0-9:]
  11987. detail::UrlComponents uc;
  11988. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11989. }
  11990. }
  11991. TEST(ParseUrlTest, SchemeEdgeCases) {
  11992. {
  11993. detail::UrlComponents uc;
  11994. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11995. }
  11996. {
  11997. detail::UrlComponents uc;
  11998. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11999. }
  12000. {
  12001. detail::UrlComponents uc;
  12002. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12003. }
  12004. }
  12005. TEST(ParseUrlTest, PortEdgeCases) {
  12006. {
  12007. detail::UrlComponents uc;
  12008. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12009. EXPECT_TRUE(uc.port.empty());
  12010. EXPECT_EQ("/path", uc.path);
  12011. }
  12012. {
  12013. // parse_url accepts any port string; validation is done by parse_port
  12014. detail::UrlComponents uc;
  12015. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12016. EXPECT_EQ("abc", uc.port);
  12017. }
  12018. }
  12019. TEST(ParseUrlTest, WebSocketPatterns) {
  12020. {
  12021. detail::UrlComponents uc;
  12022. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12023. EXPECT_EQ("ws", uc.scheme);
  12024. EXPECT_EQ("echo.example.com", uc.host);
  12025. EXPECT_EQ("8080", uc.port);
  12026. EXPECT_EQ("/ws", uc.path);
  12027. }
  12028. {
  12029. detail::UrlComponents uc;
  12030. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12031. EXPECT_EQ("wss", uc.scheme);
  12032. EXPECT_EQ("echo.example.com", uc.host);
  12033. EXPECT_TRUE(uc.port.empty());
  12034. EXPECT_EQ("/ws", uc.path);
  12035. }
  12036. }
  12037. TEST(ParseUrlTest, QueryOnly) {
  12038. detail::UrlComponents uc;
  12039. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12040. EXPECT_TRUE(uc.host.empty());
  12041. EXPECT_TRUE(uc.path.empty());
  12042. EXPECT_EQ("?q=1&r=2", uc.query);
  12043. }
  12044. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12045. detail::UrlComponents uc;
  12046. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12047. EXPECT_TRUE(uc.scheme.empty());
  12048. EXPECT_EQ("example.com", uc.host);
  12049. EXPECT_EQ("443", uc.port);
  12050. EXPECT_EQ("/path", uc.path);
  12051. }
  12052. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12053. // If ipv6 regex working, regex match codepath is taken.
  12054. // else port will default to 80 in Client impl
  12055. int clientImplMagicPort = 80;
  12056. int port = 4321;
  12057. // above ports must be different to avoid false negative
  12058. EXPECT_NE(clientImplMagicPort, port);
  12059. std::string ipV6TestURL = "http://[ff06::c3]";
  12060. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12061. CLIENT_PRIVATE_KEY_FILE);
  12062. EXPECT_EQ(cli.port(), port);
  12063. }
  12064. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12065. auto file_path = "./www/dir/index.html";
  12066. auto dir_path = "./www/dir";
  12067. detail::FileStat stat_file(file_path);
  12068. EXPECT_TRUE(stat_file.is_file());
  12069. EXPECT_FALSE(stat_file.is_dir());
  12070. detail::FileStat stat_dir(dir_path);
  12071. EXPECT_FALSE(stat_dir.is_file());
  12072. EXPECT_TRUE(stat_dir.is_dir());
  12073. }
  12074. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12075. // IPv4 with default HTTP port (80)
  12076. EXPECT_EQ("example.com",
  12077. detail::make_host_and_port_string("example.com", 80, false));
  12078. // IPv4 with default HTTPS port (443)
  12079. EXPECT_EQ("example.com",
  12080. detail::make_host_and_port_string("example.com", 443, true));
  12081. // IPv4 with non-default HTTP port
  12082. EXPECT_EQ("example.com:8080",
  12083. detail::make_host_and_port_string("example.com", 8080, false));
  12084. // IPv4 with non-default HTTPS port
  12085. EXPECT_EQ("example.com:8443",
  12086. detail::make_host_and_port_string("example.com", 8443, true));
  12087. // IPv6 with default HTTP port (80)
  12088. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12089. // IPv6 with default HTTPS port (443)
  12090. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12091. // IPv6 with non-default HTTP port
  12092. EXPECT_EQ("[::1]:8080",
  12093. detail::make_host_and_port_string("::1", 8080, false));
  12094. // IPv6 with non-default HTTPS port
  12095. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12096. // IPv6 full address with default port
  12097. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12098. detail::make_host_and_port_string(
  12099. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12100. // IPv6 full address with non-default port
  12101. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12102. detail::make_host_and_port_string(
  12103. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12104. // IPv6 localhost with non-default port
  12105. EXPECT_EQ("[::1]:3000",
  12106. detail::make_host_and_port_string("::1", 3000, false));
  12107. // IPv6 with zone ID (link-local address) with default port
  12108. EXPECT_EQ("[fe80::1%eth0]",
  12109. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12110. // IPv6 with zone ID (link-local address) with non-default port
  12111. EXPECT_EQ("[fe80::1%eth0]:8080",
  12112. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12113. // Edge case: Port 443 with is_ssl=false (should add port)
  12114. EXPECT_EQ("example.com:443",
  12115. detail::make_host_and_port_string("example.com", 443, false));
  12116. // Edge case: Port 80 with is_ssl=true (should add port)
  12117. EXPECT_EQ("example.com:80",
  12118. detail::make_host_and_port_string("example.com", 80, true));
  12119. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12120. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12121. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12122. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12123. // Security fix: Already bracketed IPv6 should not get double brackets
  12124. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12125. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12126. EXPECT_EQ("[::1]:8080",
  12127. detail::make_host_and_port_string("[::1]", 8080, false));
  12128. EXPECT_EQ("[2001:db8::1]:8080",
  12129. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12130. EXPECT_EQ("[fe80::1%eth0]",
  12131. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12132. EXPECT_EQ("[fe80::1%eth0]:8080",
  12133. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12134. // Edge case: Empty host (should return as-is)
  12135. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12136. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12137. // This is a known limitation but shouldn't crash
  12138. EXPECT_EQ("[host:name]",
  12139. detail::make_host_and_port_string("host:name", 80, false));
  12140. // Port number edge cases (no validation, but should not crash)
  12141. EXPECT_EQ("example.com:0",
  12142. detail::make_host_and_port_string("example.com", 0, false));
  12143. EXPECT_EQ("example.com:-1",
  12144. detail::make_host_and_port_string("example.com", -1, false));
  12145. EXPECT_EQ("example.com:65535",
  12146. detail::make_host_and_port_string("example.com", 65535, false));
  12147. EXPECT_EQ("example.com:65536",
  12148. detail::make_host_and_port_string("example.com", 65536, false));
  12149. }
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12152. httplib::SSLClient cli("roblox.com", 443);
  12153. cli.set_follow_location(true);
  12154. auto res = cli.Get("/");
  12155. ASSERT_TRUE(res);
  12156. EXPECT_EQ(StatusCode::OK_200, res->status);
  12157. }
  12158. #endif
  12159. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12160. Server svr;
  12161. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12162. EXPECT_EQ(res.status, 400);
  12163. });
  12164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12165. auto se = detail::scope_exit([&] {
  12166. svr.stop();
  12167. thread.join();
  12168. ASSERT_FALSE(svr.is_running());
  12169. });
  12170. svr.wait_until_ready();
  12171. Client cli(HOST, PORT);
  12172. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12173. }
  12174. TEST(InvalidHeaderCharsTest, is_field_name) {
  12175. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12176. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12177. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12178. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12179. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12180. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12181. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12182. EXPECT_FALSE(detail::fields::is_field_name(""));
  12183. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12184. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12185. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12186. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12187. }
  12188. TEST(InvalidHeaderCharsTest, is_field_value) {
  12189. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12190. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12191. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12192. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12193. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12194. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12195. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12196. EXPECT_TRUE(detail::fields::is_field_value(""));
  12197. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12198. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12199. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12200. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12201. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12202. }
  12203. TEST(InvalidHeaderCharsTest, OnServer) {
  12204. Server svr;
  12205. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12206. std::string header = "Not Set";
  12207. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12208. res.set_header(header, "value");
  12209. res.set_content("Page Content Page Content", "text/plain");
  12210. });
  12211. svr.Get("/test_value", [&](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("X-Test", header);
  12215. res.set_content("Page Content Page Content", "text/plain");
  12216. });
  12217. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12218. auto se = detail::scope_exit([&] {
  12219. svr.stop();
  12220. thread.join();
  12221. ASSERT_FALSE(svr.is_running());
  12222. });
  12223. svr.wait_until_ready();
  12224. Client cli(HOST, PORT);
  12225. {
  12226. auto res = cli.Get(
  12227. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12228. ASSERT_TRUE(res);
  12229. EXPECT_EQ("Page Content Page Content", res->body);
  12230. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12231. }
  12232. {
  12233. auto res = cli.Get(
  12234. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12235. ASSERT_TRUE(res);
  12236. EXPECT_EQ("Page Content Page Content", res->body);
  12237. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12238. }
  12239. }
  12240. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12241. auto handled = false;
  12242. Server svr;
  12243. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12244. thread t = thread([&] { svr.listen(HOST, PORT); });
  12245. auto se = detail::scope_exit([&] {
  12246. svr.stop();
  12247. t.join();
  12248. ASSERT_FALSE(svr.is_running());
  12249. ASSERT_FALSE(handled);
  12250. });
  12251. svr.wait_until_ready();
  12252. auto req = "POST /test HTTP/1.1\r\n"
  12253. "Content-Length: x\r\n"
  12254. "\r\n";
  12255. std::string response;
  12256. ASSERT_TRUE(send_request(1, req, &response));
  12257. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12258. response.substr(0, response.find("\r\n")));
  12259. }
  12260. #ifndef _WIN32
  12261. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12262. static constexpr char reject[] = "Unauthorized";
  12263. static constexpr char accept[] = "Upload accepted";
  12264. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12265. Server svr;
  12266. svr.set_expect_100_continue_handler(
  12267. [](const Request & /*req*/, Response &res) {
  12268. res.status = StatusCode::Unauthorized_401;
  12269. res.set_content(reject, "text/plain");
  12270. return res.status;
  12271. });
  12272. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12273. res.set_content(accept, "text/plain");
  12274. });
  12275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12276. auto se = detail::scope_exit([&] {
  12277. svr.stop();
  12278. thread.join();
  12279. ASSERT_FALSE(svr.is_running());
  12280. });
  12281. svr.wait_until_ready();
  12282. {
  12283. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12284. curl_easy_init(), &curl_easy_cleanup};
  12285. ASSERT_NE(curl, nullptr);
  12286. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12287. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12288. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12289. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12290. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12291. &curl_slist_free_all};
  12292. ASSERT_NE(list, nullptr);
  12293. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12294. struct read_data {
  12295. size_t read_size;
  12296. size_t total_size;
  12297. } data = {0, total_size};
  12298. using read_callback_t =
  12299. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12300. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12301. void *userdata) -> size_t {
  12302. read_data *d = (read_data *)userdata;
  12303. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12304. std::fill_n(ptr, size * nmemb, 'A');
  12305. d->read_size += size * nmemb;
  12306. return size * nmemb;
  12307. };
  12308. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12309. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12310. std::vector<char> buffer;
  12311. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12312. using write_callback_t =
  12313. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12314. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12315. void *userdata) -> size_t {
  12316. std::vector<char> *buf = (std::vector<char> *)userdata;
  12317. buf->reserve(buf->size() + size * nmemb + 1);
  12318. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12319. return size * nmemb;
  12320. };
  12321. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12322. {
  12323. const auto res = curl_easy_perform(curl.get());
  12324. ASSERT_EQ(res, CURLE_OK);
  12325. }
  12326. {
  12327. auto response_code = long{};
  12328. const auto res =
  12329. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12330. ASSERT_EQ(res, CURLE_OK);
  12331. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12332. }
  12333. {
  12334. auto dl = curl_off_t{};
  12335. const auto res =
  12336. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12337. ASSERT_EQ(res, CURLE_OK);
  12338. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12339. }
  12340. {
  12341. buffer.push_back('\0');
  12342. ASSERT_STRCASEEQ(buffer.data(), reject);
  12343. }
  12344. }
  12345. }
  12346. #endif
  12347. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12348. // Regression test for #2458.
  12349. //
  12350. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12351. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12352. // ticket can make the client socket spuriously readable during the
  12353. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12354. // the client withholds the body and then blocks reading a response that never
  12355. // comes, failing with `Failed to read connection`.
  12356. //
  12357. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12358. // within the timeout. This raw OpenSSL server deliberately never sends
  12359. // `100 Continue`; the client must still deliver the body and receive 200.
  12360. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12361. signal(SIGPIPE, SIG_IGN);
  12362. const auto port = PORT + 4;
  12363. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12364. ASSERT_NE(srv, INVALID_SOCKET);
  12365. int opt = 1;
  12366. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12367. sockaddr_in addr{};
  12368. addr.sin_family = AF_INET;
  12369. addr.sin_port = htons(static_cast<uint16_t>(port));
  12370. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12371. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12372. ASSERT_EQ(0, ::listen(srv, 1));
  12373. std::atomic<size_t> server_body_bytes{0};
  12374. auto server_thread = std::thread([&] {
  12375. sockaddr_in cli_addr{};
  12376. socklen_t cli_len = sizeof(cli_addr);
  12377. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12378. if (cli == INVALID_SOCKET) { return; }
  12379. // Bound the lifetime of the server side so a buggy client (which never
  12380. // sends the body) cannot make this thread block forever on join.
  12381. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12382. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12383. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12384. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12385. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12386. SSL *ssl = SSL_new(ctx);
  12387. SSL_set_fd(ssl, static_cast<int>(cli));
  12388. if (SSL_accept(ssl) > 0) {
  12389. // Read the request headers. Reading here also flushes the TLS 1.3
  12390. // session tickets to the client. Deliberately do NOT send
  12391. // `100 Continue`.
  12392. std::string buf;
  12393. char tmp[1024];
  12394. while (buf.find("\r\n\r\n") == std::string::npos) {
  12395. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12396. if (n <= 0) { break; }
  12397. buf.append(tmp, static_cast<size_t>(n));
  12398. }
  12399. // A correct client sends the body now; count what arrives.
  12400. auto pos = buf.find("\r\n\r\n");
  12401. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12402. while (body < 4096) {
  12403. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12404. if (n <= 0) { break; }
  12405. body += static_cast<size_t>(n);
  12406. }
  12407. server_body_bytes = body;
  12408. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12409. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12410. SSL_shutdown(ssl);
  12411. }
  12412. SSL_free(ssl);
  12413. detail::close_socket(cli);
  12414. SSL_CTX_free(ctx);
  12415. });
  12416. auto se = detail::scope_exit([&] {
  12417. server_thread.join();
  12418. detail::close_socket(srv);
  12419. });
  12420. SSLClient cli("127.0.0.1", port);
  12421. cli.enable_server_certificate_verification(false);
  12422. cli.set_connection_timeout(5, 0);
  12423. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12424. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12425. std::string body(4096, 'A');
  12426. auto res = cli.Put("/api/test", body, "application/json");
  12427. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12428. EXPECT_EQ(StatusCode::OK_200, res->status);
  12429. EXPECT_EQ(body.size(), server_body_bytes.load());
  12430. }
  12431. #endif
  12432. template <typename S, typename C>
  12433. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12434. svr.Get("/stream", [&](const Request &, Response &res) {
  12435. auto data = new std::string("01234567890123456789");
  12436. res.set_content_provider(
  12437. data->size(), "text/plain",
  12438. [&, data](size_t offset, size_t length, DataSink &sink) {
  12439. const size_t DATA_CHUNK_SIZE = 4;
  12440. const auto &d = *data;
  12441. std::this_thread::sleep_for(std::chrono::seconds(1));
  12442. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12443. return true;
  12444. },
  12445. [data](bool success) {
  12446. EXPECT_FALSE(success);
  12447. delete data;
  12448. });
  12449. });
  12450. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12451. auto i = new size_t(0);
  12452. res.set_content_provider(
  12453. "text/plain",
  12454. [i](size_t, DataSink &sink) {
  12455. if (*i < 5) {
  12456. std::this_thread::sleep_for(std::chrono::seconds(1));
  12457. sink.write("abcd", 4);
  12458. (*i)++;
  12459. } else {
  12460. sink.done();
  12461. }
  12462. return true;
  12463. },
  12464. [i](bool success) {
  12465. EXPECT_FALSE(success);
  12466. delete i;
  12467. });
  12468. });
  12469. svr.Get("/chunked", [&](const Request &, Response &res) {
  12470. auto i = new size_t(0);
  12471. res.set_chunked_content_provider(
  12472. "text/plain",
  12473. [i](size_t, DataSink &sink) {
  12474. if (*i < 5) {
  12475. std::this_thread::sleep_for(std::chrono::seconds(1));
  12476. sink.os << "abcd";
  12477. (*i)++;
  12478. } else {
  12479. sink.done();
  12480. }
  12481. return true;
  12482. },
  12483. [i](bool success) {
  12484. EXPECT_FALSE(success);
  12485. delete i;
  12486. });
  12487. });
  12488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12489. auto se = detail::scope_exit([&] {
  12490. svr.stop();
  12491. listen_thread.join();
  12492. ASSERT_FALSE(svr.is_running());
  12493. });
  12494. svr.wait_until_ready();
  12495. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12496. {
  12497. auto start = std::chrono::steady_clock::now();
  12498. auto res = cli.Get("/stream");
  12499. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12500. std::chrono::steady_clock::now() - start)
  12501. .count();
  12502. ASSERT_FALSE(res);
  12503. EXPECT_EQ(Error::Read, res.error());
  12504. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12505. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12506. }
  12507. {
  12508. auto start = std::chrono::steady_clock::now();
  12509. auto res = cli.Get("/stream_without_length");
  12510. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12511. std::chrono::steady_clock::now() - start)
  12512. .count();
  12513. ASSERT_FALSE(res);
  12514. EXPECT_EQ(Error::Read, res.error());
  12515. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12516. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12517. }
  12518. {
  12519. auto start = std::chrono::steady_clock::now();
  12520. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12521. EXPECT_EQ("abcd", string(data, data_length));
  12522. return true;
  12523. });
  12524. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12525. std::chrono::steady_clock::now() - start)
  12526. .count();
  12527. ASSERT_FALSE(res);
  12528. EXPECT_EQ(Error::Read, res.error());
  12529. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12530. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12531. }
  12532. }
  12533. TEST(MaxTimeoutTest, ContentStream) {
  12534. time_t timeout = 2000;
  12535. time_t threshold = 200;
  12536. Server svr;
  12537. Client cli("localhost", PORT);
  12538. max_timeout_test(svr, cli, timeout, threshold);
  12539. }
  12540. #ifdef CPPHTTPLIB_SSL_ENABLED
  12541. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12542. time_t timeout = 2000;
  12543. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12545. SSLClient cli("localhost", PORT);
  12546. cli.enable_server_certificate_verification(false);
  12547. max_timeout_test(svr, cli, timeout, threshold);
  12548. }
  12549. #endif
  12550. class EventDispatcher {
  12551. public:
  12552. EventDispatcher() {}
  12553. bool wait_event(DataSink *sink) {
  12554. unique_lock<mutex> lk(m_);
  12555. int id = id_;
  12556. // Wait with timeout to prevent hanging if client disconnects
  12557. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12558. [&] { return cid_ == id; })) {
  12559. return false; // Timeout occurred
  12560. }
  12561. sink->write(message_.data(), message_.size());
  12562. return true;
  12563. }
  12564. void send_event(const string &message) {
  12565. lock_guard<mutex> lk(m_);
  12566. cid_ = id_++;
  12567. message_ = message;
  12568. cv_.notify_all();
  12569. }
  12570. private:
  12571. mutex m_;
  12572. condition_variable cv_;
  12573. atomic_int id_{0};
  12574. atomic_int cid_{-1};
  12575. string message_;
  12576. };
  12577. TEST(ClientInThreadTest, Issue2068) {
  12578. EventDispatcher ed;
  12579. Server svr;
  12580. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12581. res.set_chunked_content_provider("text/event-stream",
  12582. [&](size_t /*offset*/, DataSink &sink) {
  12583. return ed.wait_event(&sink);
  12584. });
  12585. });
  12586. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12587. svr.wait_until_ready();
  12588. thread event_thread([&] {
  12589. int id = 0;
  12590. while (svr.is_running()) {
  12591. this_thread::sleep_for(chrono::milliseconds(500));
  12592. std::stringstream ss;
  12593. ss << "data: " << id << "\n\n";
  12594. ed.send_event(ss.str());
  12595. id++;
  12596. }
  12597. });
  12598. auto se = detail::scope_exit([&] {
  12599. svr.stop();
  12600. listen_thread.join();
  12601. event_thread.join();
  12602. ASSERT_FALSE(svr.is_running());
  12603. });
  12604. {
  12605. auto client = detail::make_unique<Client>(HOST, PORT);
  12606. client->set_read_timeout(std::chrono::minutes(10));
  12607. std::atomic<bool> stop{false};
  12608. std::thread t([&] {
  12609. client->Get("/event1",
  12610. [&](const char *, size_t) -> bool { return !stop; });
  12611. });
  12612. std::this_thread::sleep_for(std::chrono::seconds(2));
  12613. stop = true;
  12614. client->stop();
  12615. t.join();
  12616. // Reset client after thread has finished
  12617. client.reset();
  12618. }
  12619. }
  12620. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12621. auto handled = false;
  12622. Server svr;
  12623. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12624. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12625. auto se = detail::scope_exit([&] {
  12626. svr.stop();
  12627. t.join();
  12628. ASSERT_FALSE(svr.is_running());
  12629. ASSERT_FALSE(handled);
  12630. });
  12631. svr.wait_until_ready();
  12632. // Two Content-Length headers with different values — must be rejected
  12633. auto req = "POST /test HTTP/1.1\r\n"
  12634. "Content-Length: 5\r\n"
  12635. "Content-Length: 10\r\n"
  12636. "\r\n"
  12637. "hello";
  12638. std::string response;
  12639. ASSERT_TRUE(send_request(1, req, &response));
  12640. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12641. response.substr(0, response.find("\r\n")));
  12642. }
  12643. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12644. auto handled = false;
  12645. Server svr;
  12646. svr.Post("/test", [&](const Request &, Response &res) {
  12647. handled = true;
  12648. res.set_content("ok", "text/plain");
  12649. });
  12650. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12651. auto se = detail::scope_exit([&] {
  12652. svr.stop();
  12653. t.join();
  12654. ASSERT_FALSE(svr.is_running());
  12655. ASSERT_TRUE(handled);
  12656. });
  12657. svr.wait_until_ready();
  12658. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12659. auto req = "POST /test HTTP/1.1\r\n"
  12660. "Content-Length: 5\r\n"
  12661. "Content-Length: 5\r\n"
  12662. "\r\n"
  12663. "hello";
  12664. std::string response;
  12665. ASSERT_TRUE(send_request(1, req, &response));
  12666. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12667. }
  12668. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12669. Server svr;
  12670. svr.Get("/", [](const Request &req, Response &res) {
  12671. EXPECT_EQ(2U, req.trailers.size());
  12672. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12673. // Denied
  12674. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12675. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12676. // Accepted
  12677. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12678. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12679. EXPECT_TRUE(req.has_trailer("X-World"));
  12680. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12681. res.set_content("ok", "text/plain");
  12682. });
  12683. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12684. auto se = detail::scope_exit([&] {
  12685. svr.stop();
  12686. t.join();
  12687. ASSERT_FALSE(svr.is_running());
  12688. });
  12689. svr.wait_until_ready();
  12690. const std::string req = "GET / HTTP/1.1\r\n"
  12691. "Transfer-Encoding: chunked\r\n"
  12692. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12693. "\r\n"
  12694. "0\r\n"
  12695. "Content-Length: 10\r\n"
  12696. "Host: internal.local\r\n"
  12697. "Content-Type: malicious/content\r\n"
  12698. "Cookie: any\r\n"
  12699. "Set-Cookie: any\r\n"
  12700. "X-Forwarded-For: attacker.com\r\n"
  12701. "X-Real-Ip: 1.1.1.1\r\n"
  12702. "X-Hello: hello\r\n"
  12703. "X-World: world\r\n"
  12704. "\r\n";
  12705. std::string res;
  12706. ASSERT_TRUE(send_request(1, req, &res));
  12707. }
  12708. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12709. Server svr;
  12710. std::string observed_remote_addr;
  12711. std::string observed_xff;
  12712. svr.Get("/ip", [&](const Request &req, Response &res) {
  12713. observed_remote_addr = req.remote_addr;
  12714. observed_xff = req.get_header_value("X-Forwarded-For");
  12715. res.set_content("ok", "text/plain");
  12716. });
  12717. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12718. auto se = detail::scope_exit([&] {
  12719. svr.stop();
  12720. t.join();
  12721. ASSERT_FALSE(svr.is_running());
  12722. });
  12723. svr.wait_until_ready();
  12724. Client cli(HOST, PORT);
  12725. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12726. ASSERT_TRUE(res);
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. EXPECT_EQ(observed_xff, "203.0.113.66");
  12729. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12730. observed_remote_addr == "127.0.0.1");
  12731. }
  12732. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12733. Server svr;
  12734. svr.set_trusted_proxies({"203.0.113.66"});
  12735. std::string observed_remote_addr;
  12736. std::string observed_xff;
  12737. svr.Get("/ip", [&](const Request &req, Response &res) {
  12738. observed_remote_addr = req.remote_addr;
  12739. observed_xff = req.get_header_value("X-Forwarded-For");
  12740. res.set_content("ok", "text/plain");
  12741. });
  12742. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12743. auto se = detail::scope_exit([&] {
  12744. svr.stop();
  12745. t.join();
  12746. ASSERT_FALSE(svr.is_running());
  12747. });
  12748. svr.wait_until_ready();
  12749. Client cli(HOST, PORT);
  12750. auto res = cli.Get("/ip");
  12751. ASSERT_TRUE(res);
  12752. EXPECT_EQ(StatusCode::OK_200, res->status);
  12753. EXPECT_EQ(observed_xff, "");
  12754. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12755. observed_remote_addr == "127.0.0.1");
  12756. }
  12757. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12758. Server svr;
  12759. svr.set_trusted_proxies({"203.0.113.66"});
  12760. std::string observed_remote_addr;
  12761. std::string observed_xff;
  12762. svr.Get("/ip", [&](const Request &req, Response &res) {
  12763. observed_remote_addr = req.remote_addr;
  12764. observed_xff = req.get_header_value("X-Forwarded-For");
  12765. res.set_content("ok", "text/plain");
  12766. });
  12767. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. Client cli(HOST, PORT);
  12775. auto res = cli.Get(
  12776. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12777. ASSERT_TRUE(res);
  12778. EXPECT_EQ(StatusCode::OK_200, res->status);
  12779. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12780. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12781. }
  12782. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12783. Server svr;
  12784. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12785. std::string observed_remote_addr;
  12786. std::string observed_xff;
  12787. svr.Get("/ip", [&](const Request &req, Response &res) {
  12788. observed_remote_addr = req.remote_addr;
  12789. observed_xff = req.get_header_value("X-Forwarded-For");
  12790. res.set_content("ok", "text/plain");
  12791. });
  12792. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12793. auto se = detail::scope_exit([&] {
  12794. svr.stop();
  12795. t.join();
  12796. ASSERT_FALSE(svr.is_running());
  12797. });
  12798. svr.wait_until_ready();
  12799. Client cli(HOST, PORT);
  12800. auto res = cli.Get(
  12801. "/ip",
  12802. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12803. ASSERT_TRUE(res);
  12804. EXPECT_EQ(StatusCode::OK_200, res->status);
  12805. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12806. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12807. }
  12808. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12809. Server svr;
  12810. svr.set_trusted_proxies({"192.0.2.45"});
  12811. std::string observed_remote_addr;
  12812. std::string observed_xff;
  12813. svr.Get("/ip", [&](const Request &req, Response &res) {
  12814. observed_remote_addr = req.remote_addr;
  12815. observed_xff = req.get_header_value("X-Forwarded-For");
  12816. res.set_content("ok", "text/plain");
  12817. });
  12818. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12819. auto se = detail::scope_exit([&] {
  12820. svr.stop();
  12821. t.join();
  12822. ASSERT_FALSE(svr.is_running());
  12823. });
  12824. svr.wait_until_ready();
  12825. Client cli(HOST, PORT);
  12826. auto res = cli.Get(
  12827. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12828. ASSERT_TRUE(res);
  12829. EXPECT_EQ(StatusCode::OK_200, res->status);
  12830. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12831. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12832. }
  12833. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12834. Server svr;
  12835. svr.set_trusted_proxies({"192.0.2.45"});
  12836. std::string observed_remote_addr;
  12837. std::string observed_xff;
  12838. svr.Get("/ip", [&](const Request &req, Response &res) {
  12839. observed_remote_addr = req.remote_addr;
  12840. observed_xff = req.get_header_value("X-Forwarded-For");
  12841. res.set_content("ok", "text/plain");
  12842. });
  12843. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. ASSERT_FALSE(svr.is_running());
  12848. });
  12849. svr.wait_until_ready();
  12850. Client cli(HOST, PORT);
  12851. auto res = cli.Get(
  12852. "/ip",
  12853. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12854. ASSERT_TRUE(res);
  12855. EXPECT_EQ(StatusCode::OK_200, res->status);
  12856. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12857. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12858. }
  12859. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12860. Server svr;
  12861. svr.set_trusted_proxies({"192.0.2.45"});
  12862. std::string observed_remote_addr;
  12863. std::string observed_xff;
  12864. svr.Get("/ip", [&](const Request &req, Response &res) {
  12865. observed_remote_addr = req.remote_addr;
  12866. observed_xff = req.get_header_value("X-Forwarded-For");
  12867. res.set_content("ok", "text/plain");
  12868. });
  12869. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12870. auto se = detail::scope_exit([&] {
  12871. svr.stop();
  12872. t.join();
  12873. ASSERT_FALSE(svr.is_running());
  12874. });
  12875. svr.wait_until_ready();
  12876. std::string raw_req =
  12877. "GET /ip HTTP/1.1\r\n"
  12878. "Host: localhost\r\n"
  12879. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12880. "Connection: close\r\n"
  12881. "\r\n";
  12882. std::string out;
  12883. ASSERT_TRUE(send_request(5, raw_req, &out));
  12884. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12885. // Header parser trims surrounding whitespace of the header value
  12886. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12887. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12888. }
  12889. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12890. // crash the server (it used to call front() on an empty vector inside
  12891. // get_client_ip). The connection-level remote address must be retained instead.
  12892. static void run_malformed_xff_test(const std::string &xff_value) {
  12893. Server svr;
  12894. svr.set_trusted_proxies({"192.0.2.45"});
  12895. std::string observed_remote_addr;
  12896. svr.Get("/ip", [&](const Request &req, Response &res) {
  12897. observed_remote_addr = req.remote_addr;
  12898. res.set_content("ok", "text/plain");
  12899. });
  12900. int port = 0;
  12901. thread t = thread([&]() {
  12902. port = svr.bind_to_any_port(HOST);
  12903. svr.listen_after_bind();
  12904. });
  12905. auto se = detail::scope_exit([&] {
  12906. svr.stop();
  12907. t.join();
  12908. ASSERT_FALSE(svr.is_running());
  12909. });
  12910. svr.wait_until_ready();
  12911. Client cli(HOST, port);
  12912. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12913. ASSERT_TRUE(res);
  12914. EXPECT_EQ(StatusCode::OK_200, res->status);
  12915. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12916. observed_remote_addr == "127.0.0.1");
  12917. }
  12918. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12919. run_malformed_xff_test("");
  12920. }
  12921. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12922. run_malformed_xff_test(",");
  12923. }
  12924. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12925. run_malformed_xff_test(", , ,");
  12926. }
  12927. #ifndef _WIN32
  12928. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12929. Server svr;
  12930. svr.Post("/post", [&](const Request &req, Response &res) {
  12931. res.set_content(req.body, "text/plain");
  12932. });
  12933. svr.Put("/put", [&](const Request &req, Response &res) {
  12934. res.set_content(req.body, "text/plain");
  12935. });
  12936. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12937. res.set_content(req.body, "text/plain");
  12938. });
  12939. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12940. res.set_content(req.body, "text/plain");
  12941. });
  12942. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12943. auto se = detail::scope_exit([&] {
  12944. svr.stop();
  12945. t.join();
  12946. ASSERT_FALSE(svr.is_running());
  12947. });
  12948. svr.wait_until_ready();
  12949. std::string resp;
  12950. // POST without Content-Length
  12951. ASSERT_TRUE(send_request(5,
  12952. "POST /post HTTP/1.1\r\n"
  12953. "Host: localhost\r\n"
  12954. "Connection: close\r\n"
  12955. "\r\n",
  12956. &resp));
  12957. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12958. // PUT without Content-Length
  12959. resp.clear();
  12960. ASSERT_TRUE(send_request(5,
  12961. "PUT /put HTTP/1.1\r\n"
  12962. "Host: localhost\r\n"
  12963. "Connection: close\r\n"
  12964. "\r\n",
  12965. &resp));
  12966. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12967. // PATCH without Content-Length
  12968. resp.clear();
  12969. ASSERT_TRUE(send_request(5,
  12970. "PATCH /patch HTTP/1.1\r\n"
  12971. "Host: localhost\r\n"
  12972. "Connection: close\r\n"
  12973. "\r\n",
  12974. &resp));
  12975. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12976. // DELETE without Content-Length
  12977. resp.clear();
  12978. ASSERT_TRUE(send_request(5,
  12979. "DELETE /delete HTTP/1.1\r\n"
  12980. "Host: localhost\r\n"
  12981. "Connection: close\r\n"
  12982. "\r\n",
  12983. &resp));
  12984. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12985. }
  12986. #endif
  12987. //==============================================================================
  12988. // open_stream() Tests
  12989. //==============================================================================
  12990. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12991. std::string result;
  12992. char buf[8192];
  12993. ssize_t n;
  12994. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12995. result.append(buf, static_cast<size_t>(n));
  12996. }
  12997. return result;
  12998. }
  12999. // Mock stream for unit tests
  13000. class MockStream : public Stream {
  13001. public:
  13002. std::string data;
  13003. size_t pos = 0;
  13004. ssize_t error_after = -1; // -1 = no error
  13005. explicit MockStream(const std::string &d, ssize_t err = -1)
  13006. : data(d), error_after(err) {}
  13007. bool is_readable() const override { return true; }
  13008. bool wait_readable() const override { return true; }
  13009. bool wait_writable() const override { return true; }
  13010. ssize_t read(char *ptr, size_t size) override {
  13011. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13012. if (pos >= data.size()) return 0;
  13013. size_t limit =
  13014. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13015. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13016. std::memcpy(ptr, data.data() + pos, to_read);
  13017. pos += to_read;
  13018. return static_cast<ssize_t>(to_read);
  13019. }
  13020. ssize_t write(const char *, size_t) override { return -1; }
  13021. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13022. ip = "127.0.0.1";
  13023. port = 0;
  13024. }
  13025. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13026. ip = "127.0.0.1";
  13027. port = 0;
  13028. }
  13029. socket_t socket() const override { return INVALID_SOCKET; }
  13030. time_t duration() const override { return 0; }
  13031. };
  13032. TEST(StreamHandleTest, Basic) {
  13033. ClientImpl::StreamHandle handle;
  13034. EXPECT_FALSE(handle.is_valid());
  13035. handle.response = detail::make_unique<Response>();
  13036. handle.error = Error::Connection;
  13037. EXPECT_FALSE(handle.is_valid());
  13038. handle.error = Error::Success;
  13039. EXPECT_TRUE(handle.is_valid());
  13040. }
  13041. TEST(BodyReaderTest, Basic) {
  13042. MockStream stream("Hello, World!");
  13043. detail::BodyReader reader;
  13044. reader.stream = &stream;
  13045. reader.content_length = 13;
  13046. char buf[32];
  13047. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13048. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13049. EXPECT_TRUE(reader.eof);
  13050. }
  13051. TEST(BodyReaderTest, NoStream) {
  13052. detail::BodyReader reader;
  13053. char buf[32];
  13054. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13055. EXPECT_EQ(Error::Connection, reader.last_error);
  13056. }
  13057. TEST(BodyReaderTest, Error) {
  13058. MockStream stream("Hello, World!", 5);
  13059. detail::BodyReader reader;
  13060. reader.stream = &stream;
  13061. reader.content_length = 13;
  13062. char buf[32];
  13063. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13064. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13065. EXPECT_EQ(Error::Read, reader.last_error);
  13066. }
  13067. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13068. // Mock-based StreamHandle tests relying on private internals are removed.
  13069. class OpenStreamTest : public ::testing::Test {
  13070. protected:
  13071. void SetUp() override {
  13072. svr_.Get("/hello", [](const Request &, Response &res) {
  13073. res.set_content("Hello World!", "text/plain");
  13074. });
  13075. svr_.Get("/large", [](const Request &, Response &res) {
  13076. res.set_content(std::string(10000, 'X'), "text/plain");
  13077. });
  13078. svr_.Get("/chunked", [](const Request &, Response &res) {
  13079. res.set_chunked_content_provider("text/plain",
  13080. [](size_t offset, DataSink &sink) {
  13081. if (offset < 15) {
  13082. sink.write("chunk", 5);
  13083. return true;
  13084. }
  13085. sink.done();
  13086. return true;
  13087. });
  13088. });
  13089. svr_.Get("/compressible", [](const Request &, Response &res) {
  13090. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13091. DataSink &sink) {
  13092. if (offset < 100 * 1024) {
  13093. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13094. sink.write(chunk.data(), chunk.size());
  13095. return true;
  13096. }
  13097. sink.done();
  13098. return true;
  13099. });
  13100. });
  13101. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13102. [](const Request & /*req*/, Response &res) {
  13103. auto i = new int(0);
  13104. res.set_header("Trailer", "Content-Length, X-Allowed");
  13105. res.set_chunked_content_provider(
  13106. "text/plain",
  13107. [i](size_t /*offset*/, DataSink &sink) {
  13108. switch (*i) {
  13109. case 0: sink.os << "123"; break;
  13110. case 1: sink.os << "456"; break;
  13111. case 2: sink.os << "789"; break;
  13112. case 3: {
  13113. sink.done_with_trailer(
  13114. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13115. } break;
  13116. }
  13117. (*i)++;
  13118. return true;
  13119. },
  13120. [i](bool success) {
  13121. EXPECT_TRUE(success);
  13122. delete i;
  13123. });
  13124. });
  13125. // Echo headers endpoint for header-related tests
  13126. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13127. std::string body;
  13128. for (const auto &h : req.headers) {
  13129. body.append(h.first);
  13130. body.push_back(':');
  13131. body.append(h.second);
  13132. body.push_back('\n');
  13133. }
  13134. res.set_content(body, "text/plain");
  13135. });
  13136. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13137. std::string body;
  13138. for (const auto &h : req.headers) {
  13139. body.append(h.first);
  13140. body.push_back(':');
  13141. body.append(h.second);
  13142. body.push_back('\n');
  13143. }
  13144. res.set_content(body, "text/plain");
  13145. });
  13146. port_ = svr_.bind_to_any_port("127.0.0.1");
  13147. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13148. svr_.wait_until_ready();
  13149. }
  13150. void TearDown() override {
  13151. svr_.stop();
  13152. if (thread_.joinable()) thread_.join();
  13153. }
  13154. Server svr_;
  13155. std::thread thread_;
  13156. int port_ = 0;
  13157. };
  13158. TEST_F(OpenStreamTest, Basic) {
  13159. Client cli("127.0.0.1", port_);
  13160. auto handle = cli.open_stream("GET", "/hello");
  13161. EXPECT_TRUE(handle.is_valid());
  13162. EXPECT_EQ("Hello World!", read_all(handle));
  13163. }
  13164. TEST_F(OpenStreamTest, SmallBuffer) {
  13165. Client cli("127.0.0.1", port_);
  13166. auto handle = cli.open_stream("GET", "/hello");
  13167. std::string result;
  13168. char buf[4];
  13169. ssize_t n;
  13170. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13171. result.append(buf, static_cast<size_t>(n));
  13172. EXPECT_EQ("Hello World!", result);
  13173. }
  13174. TEST_F(OpenStreamTest, DefaultHeaders) {
  13175. Client cli("127.0.0.1", port_);
  13176. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13177. {
  13178. auto handle = cli.open_stream("GET", "/echo-headers");
  13179. ASSERT_TRUE(handle.is_valid());
  13180. auto body = read_all(handle);
  13181. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13182. std::string::npos);
  13183. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13184. std::string::npos);
  13185. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13186. }
  13187. // open_stream POST with body and no explicit content_type should NOT add
  13188. // text/plain Content-Type (behavior differs from non-streaming path), but
  13189. // should include Content-Length
  13190. {
  13191. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13192. ASSERT_TRUE(handle.is_valid());
  13193. auto body = read_all(handle);
  13194. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13195. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13196. }
  13197. // open_stream POST with explicit Content-Type should preserve it
  13198. {
  13199. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13200. {{"Content-Type", "application/custom"}},
  13201. "{}", "application/custom");
  13202. ASSERT_TRUE(handle.is_valid());
  13203. auto body = read_all(handle);
  13204. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13205. }
  13206. // User-specified User-Agent must not be overwritten for stream API
  13207. {
  13208. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13209. {{"User-Agent", "MyAgent/1.2"}});
  13210. ASSERT_TRUE(handle.is_valid());
  13211. auto body = read_all(handle);
  13212. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13213. }
  13214. }
  13215. TEST_F(OpenStreamTest, Large) {
  13216. Client cli("127.0.0.1", port_);
  13217. auto handle = cli.open_stream("GET", "/large");
  13218. EXPECT_EQ(10000u, read_all(handle).size());
  13219. }
  13220. TEST_F(OpenStreamTest, ConnectionError) {
  13221. Client cli("127.0.0.1", 9999);
  13222. auto handle = cli.open_stream("GET", "/hello");
  13223. EXPECT_FALSE(handle.is_valid());
  13224. }
  13225. TEST_F(OpenStreamTest, Chunked) {
  13226. Client cli("127.0.0.1", port_);
  13227. auto handle = cli.open_stream("GET", "/chunked");
  13228. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13229. "Transfer-Encoding") == "chunked");
  13230. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13231. }
  13232. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13233. Client cli("127.0.0.1", port_);
  13234. auto handle =
  13235. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13236. ASSERT_TRUE(handle.is_valid());
  13237. // Consume body to allow trailers to be received/parsed
  13238. auto body = read_all(handle);
  13239. // Explicitly parse trailers (ensure trailers are available for assertion)
  13240. handle.parse_trailers_if_needed();
  13241. EXPECT_EQ(std::string("123456789"), body);
  13242. // The response should include a Trailer header declaring both names
  13243. ASSERT_TRUE(handle.response);
  13244. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13245. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13246. handle.response->get_header_value("Trailer"));
  13247. // Prohibited trailer must not be present
  13248. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13249. // Allowed trailer should be present
  13250. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13251. EXPECT_EQ(std::string("yes"),
  13252. handle.response->get_trailer_value("X-Allowed"));
  13253. // Verify trailers are NOT present as regular headers
  13254. EXPECT_EQ(std::string(""),
  13255. handle.response->get_header_value("Content-Length"));
  13256. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13257. }
  13258. static std::thread serve_single_response(std::promise<int> &port_promise,
  13259. const std::string &response) {
  13260. return std::thread([&port_promise, response] {
  13261. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13262. default_socket_options(srv);
  13263. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13264. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13265. sockaddr_in addr{};
  13266. addr.sin_family = AF_INET;
  13267. addr.sin_port = htons(0); // Let OS assign a free port
  13268. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13269. int opt = 1;
  13270. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13271. #ifdef _WIN32
  13272. reinterpret_cast<const char *>(&opt),
  13273. #else
  13274. &opt,
  13275. #endif
  13276. sizeof(opt));
  13277. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13278. ::listen(srv, 1) != 0) {
  13279. port_promise.set_value(-1);
  13280. detail::close_socket(srv);
  13281. return;
  13282. }
  13283. socklen_t addr_len = sizeof(addr);
  13284. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13285. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13286. sockaddr_in cli_addr{};
  13287. socklen_t cli_len = sizeof(cli_addr);
  13288. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13289. if (cli != INVALID_SOCKET) {
  13290. // Read the complete HTTP request (until the blank line that terminates
  13291. // headers) before sending the response. If the server closes the socket
  13292. // while the client's request data is still unread in the kernel receive
  13293. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13294. // connection on both sides: it discards the client's receive buffer
  13295. // (which already holds our response) and causes any in-progress write on
  13296. // the client to fail with ECONNRESET. Reading all request data first
  13297. // ensures close() emits a graceful FIN.
  13298. {
  13299. char rbuf[256];
  13300. std::string req;
  13301. while (req.find("\r\n\r\n") == std::string::npos) {
  13302. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13303. if (n <= 0) { break; }
  13304. req.append(rbuf, static_cast<size_t>(n));
  13305. }
  13306. }
  13307. ::send(cli,
  13308. #ifdef _WIN32
  13309. static_cast<const char *>(response.c_str()),
  13310. static_cast<int>(response.size()),
  13311. #else
  13312. response.c_str(), response.size(),
  13313. #endif
  13314. 0);
  13315. detail::close_socket(cli);
  13316. }
  13317. detail::close_socket(srv);
  13318. });
  13319. }
  13320. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13321. #ifndef _WIN32
  13322. signal(SIGPIPE, SIG_IGN);
  13323. #endif
  13324. std::promise<int> port_promise;
  13325. auto port_future = port_promise.get_future();
  13326. auto server_thread =
  13327. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13328. "Content-Type: text/plain\r\n"
  13329. "Content-Length: not-a-number\r\n"
  13330. "Connection: close\r\n"
  13331. "\r\n"
  13332. "hello");
  13333. auto port = port_future.get();
  13334. ASSERT_GT(port, 0);
  13335. Client cli("127.0.0.1", port);
  13336. auto handle = cli.open_stream("GET", "/");
  13337. EXPECT_FALSE(handle.is_valid());
  13338. server_thread.join();
  13339. }
  13340. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13341. #ifndef _WIN32
  13342. signal(SIGPIPE, SIG_IGN);
  13343. #endif
  13344. std::promise<int> port_promise;
  13345. auto port_future = port_promise.get_future();
  13346. auto server_thread = serve_single_response(
  13347. port_promise, "HTTP/1.1 200 OK\r\n"
  13348. "Content-Type: text/plain\r\n"
  13349. "Content-Length: 99999999999999999999999999\r\n"
  13350. "Connection: close\r\n"
  13351. "\r\n"
  13352. "hello");
  13353. auto port = port_future.get();
  13354. ASSERT_GT(port, 0);
  13355. // Before the fix, std::stoull would throw std::out_of_range here and
  13356. // crash the process. After the fix, strtoull silently clamps to
  13357. // ULLONG_MAX so the stream opens without crashing. The important thing
  13358. // is that the process does NOT terminate.
  13359. Client cli("127.0.0.1", port);
  13360. auto handle = cli.open_stream("GET", "/");
  13361. EXPECT_TRUE(handle.is_valid());
  13362. server_thread.join();
  13363. }
  13364. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13365. TEST_F(OpenStreamTest, Gzip) {
  13366. Client cli("127.0.0.1", port_);
  13367. auto handle = cli.open_stream("GET", "/compressible", {},
  13368. {{"Accept-Encoding", "gzip"}});
  13369. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13370. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13371. }
  13372. #endif
  13373. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13374. TEST_F(OpenStreamTest, Brotli) {
  13375. Client cli("127.0.0.1", port_);
  13376. auto handle =
  13377. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13378. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13379. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13380. }
  13381. #endif
  13382. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13383. TEST_F(OpenStreamTest, Zstd) {
  13384. Client cli("127.0.0.1", port_);
  13385. auto handle = cli.open_stream("GET", "/compressible", {},
  13386. {{"Accept-Encoding", "zstd"}});
  13387. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13388. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13389. }
  13390. #endif
  13391. #ifdef CPPHTTPLIB_SSL_ENABLED
  13392. class SSLOpenStreamTest : public ::testing::Test {
  13393. protected:
  13394. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13395. void SetUp() override {
  13396. svr_.Get("/hello", [](const Request &, Response &res) {
  13397. res.set_content("Hello SSL World!", "text/plain");
  13398. });
  13399. svr_.Get("/chunked", [](const Request &, Response &res) {
  13400. res.set_chunked_content_provider("text/plain",
  13401. [](size_t offset, DataSink &sink) {
  13402. if (offset < 15) {
  13403. sink.write("chunk", 5);
  13404. return true;
  13405. }
  13406. sink.done();
  13407. return true;
  13408. });
  13409. });
  13410. svr_.Post("/echo", [](const Request &req, Response &res) {
  13411. res.set_content(req.body, req.get_header_value("Content-Type"));
  13412. });
  13413. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13414. std::string body = req.body;
  13415. res.set_chunked_content_provider(
  13416. "text/plain", [body](size_t offset, DataSink &sink) {
  13417. if (offset < body.size()) {
  13418. sink.write(body.data() + offset, body.size() - offset);
  13419. }
  13420. sink.done();
  13421. return true;
  13422. });
  13423. });
  13424. port_ = svr_.bind_to_any_port("127.0.0.1");
  13425. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13426. svr_.wait_until_ready();
  13427. }
  13428. void TearDown() override {
  13429. svr_.stop();
  13430. if (thread_.joinable()) thread_.join();
  13431. }
  13432. SSLServer svr_;
  13433. std::thread thread_;
  13434. int port_ = 0;
  13435. };
  13436. TEST_F(SSLOpenStreamTest, Basic) {
  13437. SSLClient cli("127.0.0.1", port_);
  13438. cli.enable_server_certificate_verification(false);
  13439. auto handle = cli.open_stream("GET", "/hello");
  13440. ASSERT_TRUE(handle.is_valid());
  13441. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13442. }
  13443. TEST_F(SSLOpenStreamTest, Chunked) {
  13444. SSLClient cli("127.0.0.1", port_);
  13445. cli.enable_server_certificate_verification(false);
  13446. auto handle = cli.open_stream("GET", "/chunked");
  13447. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13448. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13449. "Transfer-Encoding") == "chunked");
  13450. auto body = read_all(handle);
  13451. EXPECT_EQ("chunkchunkchunk", body);
  13452. }
  13453. TEST_F(SSLOpenStreamTest, Post) {
  13454. SSLClient cli("127.0.0.1", port_);
  13455. cli.enable_server_certificate_verification(false);
  13456. auto handle =
  13457. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13458. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13459. EXPECT_EQ(200, handle.response->status);
  13460. auto body = read_all(handle);
  13461. EXPECT_EQ("Hello SSL POST", body);
  13462. }
  13463. TEST_F(SSLOpenStreamTest, PostChunked) {
  13464. SSLClient cli("127.0.0.1", port_);
  13465. cli.enable_server_certificate_verification(false);
  13466. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13467. "Chunked SSL Data", "text/plain");
  13468. ASSERT_TRUE(handle.is_valid());
  13469. EXPECT_EQ(200, handle.response->status);
  13470. auto body = read_all(handle);
  13471. EXPECT_EQ("Chunked SSL Data", body);
  13472. }
  13473. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13474. // Content-Length is terminated by the server closing the connection. When the
  13475. // SSL peer sends a close_notify after the body, the client must treat it as a
  13476. // clean EOF and return a successful response rather than an error.
  13477. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13479. ASSERT_TRUE(svr.is_valid());
  13480. svr.set_keep_alive_max_count(1);
  13481. const std::string expected_body = "Hello from connection-close response!";
  13482. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13483. res.set_content_provider("text/plain",
  13484. [&](size_t offset, DataSink &sink) -> bool {
  13485. if (offset < expected_body.size()) {
  13486. sink.write(expected_body.data() + offset,
  13487. expected_body.size() - offset);
  13488. }
  13489. sink.done();
  13490. return true;
  13491. });
  13492. });
  13493. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13494. auto se = detail::scope_exit([&] {
  13495. svr.stop();
  13496. listen_thread.join();
  13497. ASSERT_FALSE(svr.is_running());
  13498. });
  13499. svr.wait_until_ready();
  13500. SSLClient cli(HOST, PORT);
  13501. cli.enable_server_certificate_verification(false);
  13502. auto res = cli.Get("/no-content-length");
  13503. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13504. EXPECT_EQ(StatusCode::OK_200, res->status);
  13505. EXPECT_EQ(expected_body, res->body);
  13506. }
  13507. #endif // CPPHTTPLIB_SSL_ENABLED
  13508. //==============================================================================
  13509. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13510. // results for various scenarios.
  13511. //==============================================================================
  13512. TEST(ParityTest, GetVsOpenStream) {
  13513. Server svr;
  13514. const std::string path = "/parity";
  13515. const std::string content = "Parity test content: hello world";
  13516. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13517. res.set_content(content, "text/plain");
  13518. });
  13519. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13520. auto se = detail::scope_exit([&] {
  13521. svr.stop();
  13522. t.join();
  13523. ASSERT_FALSE(svr.is_running());
  13524. });
  13525. svr.wait_until_ready();
  13526. Client cli(HOST, PORT);
  13527. // Non-stream path
  13528. auto r1 = cli.Get(path);
  13529. ASSERT_TRUE(r1);
  13530. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13531. // Stream path
  13532. auto h = cli.open_stream("GET", path);
  13533. ASSERT_TRUE(h.is_valid());
  13534. EXPECT_EQ(r1->body, read_all(h));
  13535. }
  13536. // Helper to compress data with provided compressor type T
  13537. template <typename Compressor>
  13538. static std::string compress_payload_for_parity(const std::string &in) {
  13539. std::string out;
  13540. Compressor compressor;
  13541. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13542. [&](const char *data, size_t n) {
  13543. out.append(data, n);
  13544. return true;
  13545. });
  13546. EXPECT_TRUE(ok);
  13547. return out;
  13548. }
  13549. // Helper function for compression parity tests
  13550. template <typename Compressor>
  13551. static void test_compression_parity(const std::string &original,
  13552. const std::string &path,
  13553. const std::string &encoding) {
  13554. const std::string compressed =
  13555. compress_payload_for_parity<Compressor>(original);
  13556. Server svr;
  13557. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13558. res.set_content(compressed, "application/octet-stream");
  13559. res.set_header("Content-Encoding", encoding);
  13560. });
  13561. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13562. auto se = detail::scope_exit([&] {
  13563. svr.stop();
  13564. t.join();
  13565. ASSERT_FALSE(svr.is_running());
  13566. });
  13567. svr.wait_until_ready();
  13568. Client cli(HOST, PORT);
  13569. // Non-streaming
  13570. {
  13571. auto res = cli.Get(path);
  13572. ASSERT_TRUE(res);
  13573. EXPECT_EQ(StatusCode::OK_200, res->status);
  13574. EXPECT_EQ(original, res->body);
  13575. }
  13576. // Streaming
  13577. {
  13578. auto h = cli.open_stream("GET", path);
  13579. ASSERT_TRUE(h.is_valid());
  13580. EXPECT_EQ(original, read_all(h));
  13581. }
  13582. }
  13583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13584. TEST(ParityTest, Gzip) {
  13585. test_compression_parity<detail::gzip_compressor>(
  13586. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13587. }
  13588. #endif
  13589. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13590. TEST(ParityTest, Brotli) {
  13591. test_compression_parity<detail::brotli_compressor>(
  13592. "Hello, brotli parity test payload", "/parity-br", "br");
  13593. }
  13594. #endif
  13595. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13596. TEST(ParityTest, Zstd) {
  13597. test_compression_parity<detail::zstd_compressor>(
  13598. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13599. }
  13600. #endif
  13601. //==============================================================================
  13602. // New Stream API Tests
  13603. //==============================================================================
  13604. inline std::string read_body(httplib::stream::Result &result) {
  13605. std::string body;
  13606. while (result.next()) {
  13607. body.append(result.data(), result.size());
  13608. }
  13609. return body;
  13610. }
  13611. TEST(ClientConnectionTest, Basic) {
  13612. httplib::ClientConnection conn;
  13613. EXPECT_FALSE(conn.is_open());
  13614. conn.sock = 1;
  13615. EXPECT_TRUE(conn.is_open());
  13616. httplib::ClientConnection conn2(std::move(conn));
  13617. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13618. conn2.sock = INVALID_SOCKET;
  13619. }
  13620. // Unified test server for all stream::* tests
  13621. class StreamApiTest : public ::testing::Test {
  13622. protected:
  13623. void SetUp() override {
  13624. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13625. res.set_content("Hello World!", "text/plain");
  13626. });
  13627. svr_.Get("/echo-params",
  13628. [](const httplib::Request &req, httplib::Response &res) {
  13629. std::string r;
  13630. for (const auto &p : req.params) {
  13631. if (!r.empty()) r += "&";
  13632. r += p.first + "=" + p.second;
  13633. }
  13634. res.set_content(r, "text/plain");
  13635. });
  13636. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13637. res.set_content(req.body, req.get_header_value("Content-Type"));
  13638. });
  13639. svr_.Post("/echo-headers",
  13640. [](const httplib::Request &req, httplib::Response &res) {
  13641. std::string r;
  13642. for (const auto &h : req.headers)
  13643. r += h.first + ": " + h.second + "\n";
  13644. res.set_content(r, "text/plain");
  13645. });
  13646. svr_.Post("/echo-params",
  13647. [](const httplib::Request &req, httplib::Response &res) {
  13648. std::string r = "params:";
  13649. for (const auto &p : req.params)
  13650. r += p.first + "=" + p.second + ";";
  13651. res.set_content(r + " body:" + req.body, "text/plain");
  13652. });
  13653. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13654. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13655. });
  13656. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13657. res.set_content("PUT:" + req.body, "text/plain");
  13658. });
  13659. svr_.Patch("/echo",
  13660. [](const httplib::Request &req, httplib::Response &res) {
  13661. res.set_content("PATCH:" + req.body, "text/plain");
  13662. });
  13663. svr_.Delete(
  13664. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13665. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13666. "text/plain");
  13667. });
  13668. svr_.Get("/head-test",
  13669. [](const httplib::Request &, httplib::Response &res) {
  13670. res.set_content("body for HEAD", "text/plain");
  13671. });
  13672. svr_.Options("/options",
  13673. [](const httplib::Request &, httplib::Response &res) {
  13674. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13675. });
  13676. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13677. svr_.wait_until_ready();
  13678. }
  13679. void TearDown() override {
  13680. svr_.stop();
  13681. if (thread_.joinable()) thread_.join();
  13682. }
  13683. httplib::Server svr_;
  13684. std::thread thread_;
  13685. };
  13686. // stream::Get tests
  13687. TEST_F(StreamApiTest, GetBasic) {
  13688. httplib::Client cli(HOST, PORT);
  13689. auto result = httplib::stream::Get(cli, "/hello");
  13690. ASSERT_TRUE(result.is_valid());
  13691. EXPECT_EQ(200, result.status());
  13692. EXPECT_EQ("Hello World!", read_body(result));
  13693. }
  13694. TEST_F(StreamApiTest, GetWithParams) {
  13695. httplib::Client cli(HOST, PORT);
  13696. httplib::Params params{{"foo", "bar"}};
  13697. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13698. ASSERT_TRUE(result.is_valid());
  13699. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13700. }
  13701. TEST_F(StreamApiTest, GetConnectionError) {
  13702. httplib::Client cli(HOST, 9999);
  13703. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13704. }
  13705. TEST_F(StreamApiTest, Get404) {
  13706. httplib::Client cli(HOST, PORT);
  13707. auto result = httplib::stream::Get(cli, "/nonexistent");
  13708. EXPECT_TRUE(result.is_valid());
  13709. EXPECT_EQ(404, result.status());
  13710. }
  13711. // stream::Post tests
  13712. TEST_F(StreamApiTest, PostBasic) {
  13713. httplib::Client cli(HOST, PORT);
  13714. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13715. "application/json");
  13716. ASSERT_TRUE(result.is_valid());
  13717. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13718. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13719. }
  13720. TEST_F(StreamApiTest, PostWithHeaders) {
  13721. httplib::Client cli(HOST, PORT);
  13722. httplib::Headers headers{{"X-Custom", "value"}};
  13723. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13724. "text/plain");
  13725. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13726. }
  13727. TEST_F(StreamApiTest, PostWithParams) {
  13728. httplib::Client cli(HOST, PORT);
  13729. httplib::Params params{{"k", "v"}};
  13730. auto result =
  13731. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13732. auto body = read_body(result);
  13733. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13734. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13735. }
  13736. TEST_F(StreamApiTest, PostLarge) {
  13737. httplib::Client cli(HOST, PORT);
  13738. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13739. size_t total = 0;
  13740. while (result.next()) {
  13741. total += result.size();
  13742. }
  13743. EXPECT_EQ(100u * 1024u, total);
  13744. }
  13745. // stream::Put/Patch tests
  13746. TEST_F(StreamApiTest, PutAndPatch) {
  13747. httplib::Client cli(HOST, PORT);
  13748. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13749. EXPECT_EQ("PUT:test", read_body(put));
  13750. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13751. EXPECT_EQ("PATCH:test", read_body(patch));
  13752. }
  13753. // stream::Delete tests
  13754. TEST_F(StreamApiTest, Delete) {
  13755. httplib::Client cli(HOST, PORT);
  13756. auto del1 = httplib::stream::Delete(cli, "/resource");
  13757. EXPECT_EQ("Deleted", read_body(del1));
  13758. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13759. EXPECT_EQ("Deleted:data", read_body(del2));
  13760. }
  13761. // stream::Head/Options tests
  13762. TEST_F(StreamApiTest, HeadAndOptions) {
  13763. httplib::Client cli(HOST, PORT);
  13764. auto head = httplib::stream::Head(cli, "/head-test");
  13765. EXPECT_TRUE(head.is_valid());
  13766. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13767. auto opts = httplib::stream::Options(cli, "/options");
  13768. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13769. }
  13770. // SSL stream::* tests
  13771. #ifdef CPPHTTPLIB_SSL_ENABLED
  13772. class SSLStreamApiTest : public ::testing::Test {
  13773. protected:
  13774. void SetUp() override {
  13775. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13776. res.set_content("Hello SSL!", "text/plain");
  13777. });
  13778. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13779. res.set_content(req.body, "text/plain");
  13780. });
  13781. port_ = svr_.bind_to_any_port("127.0.0.1");
  13782. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13783. svr_.wait_until_ready();
  13784. }
  13785. void TearDown() override {
  13786. svr_.stop();
  13787. if (thread_.joinable()) thread_.join();
  13788. }
  13789. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13790. std::thread thread_;
  13791. int port_ = 0;
  13792. };
  13793. TEST_F(SSLStreamApiTest, GetAndPost) {
  13794. httplib::SSLClient cli("127.0.0.1", port_);
  13795. cli.enable_server_certificate_verification(false);
  13796. auto get = httplib::stream::Get(cli, "/hello");
  13797. EXPECT_EQ("Hello SSL!", read_body(get));
  13798. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13799. EXPECT_EQ("test", read_body(post));
  13800. }
  13801. #endif
  13802. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13803. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13804. // BodyReader
  13805. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13806. // Test that read timeout during streaming is detected
  13807. // Use a large content-length response where server delays mid-stream
  13808. Server svr;
  13809. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13810. // Send a large response with delay in the middle
  13811. res.set_content_provider(
  13812. 1000, // content_length
  13813. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13814. if (offset < 100) {
  13815. // Send first 100 bytes immediately
  13816. std::string data(100, 'A');
  13817. sink.write(data.c_str(), data.size());
  13818. return true;
  13819. }
  13820. // Then delay longer than client timeout
  13821. std::this_thread::sleep_for(std::chrono::seconds(3));
  13822. std::string data(900, 'B');
  13823. sink.write(data.c_str(), data.size());
  13824. return true;
  13825. });
  13826. });
  13827. auto port = 8091;
  13828. std::thread t([&]() { svr.listen("localhost", port); });
  13829. svr.wait_until_ready();
  13830. Client cli("localhost", port);
  13831. cli.set_read_timeout(1, 0); // 1 second timeout
  13832. auto handle = cli.open_stream("GET", "/slow-stream");
  13833. ASSERT_TRUE(handle.is_valid());
  13834. char buf[256];
  13835. ssize_t total = 0;
  13836. ssize_t n;
  13837. bool got_error = false;
  13838. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13839. total += n;
  13840. }
  13841. if (n < 0) {
  13842. got_error = true;
  13843. // Should be timeout or read error
  13844. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13845. handle.get_read_error() == Error::Read)
  13846. << "Actual error: " << to_string(handle.get_read_error());
  13847. }
  13848. // Either we got an error, or we got less data than expected
  13849. EXPECT_TRUE(got_error || total < 1000)
  13850. << "Expected timeout but got all " << total << " bytes";
  13851. svr.stop();
  13852. t.join();
  13853. }
  13854. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13855. // Test connection closed detection via BodyReader
  13856. Server svr;
  13857. std::atomic<bool> close_now{false};
  13858. svr.Get("/will-close", [&](const Request &, Response &res) {
  13859. res.set_content_provider(
  13860. 10000, // Large content_length that we won't fully send
  13861. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13862. if (offset < 100) {
  13863. std::string data(100, 'X');
  13864. sink.write(data.c_str(), data.size());
  13865. return true;
  13866. }
  13867. // Wait for signal then abort
  13868. while (!close_now) {
  13869. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13870. }
  13871. return false; // Abort - server will close connection
  13872. });
  13873. });
  13874. auto port = 8092;
  13875. std::thread t([&]() { svr.listen("localhost", port); });
  13876. svr.wait_until_ready();
  13877. Client cli("localhost", port);
  13878. auto handle = cli.open_stream("GET", "/will-close");
  13879. ASSERT_TRUE(handle.is_valid());
  13880. char buf[256];
  13881. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13882. EXPECT_GT(n, 0) << "First read should succeed";
  13883. // Signal server to close
  13884. close_now = true;
  13885. // Keep reading until error or EOF
  13886. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13887. // Keep reading
  13888. }
  13889. // Should get an error since content_length wasn't satisfied
  13890. if (n < 0) {
  13891. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13892. handle.get_read_error() == Error::Read)
  13893. << "Actual error: " << to_string(handle.get_read_error());
  13894. }
  13895. svr.stop();
  13896. t.join();
  13897. }
  13898. #ifdef CPPHTTPLIB_SSL_ENABLED
  13899. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13900. // Test that read timeout during SSL streaming is detected
  13901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13902. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13903. res.set_content_provider(
  13904. 1000, "text/plain",
  13905. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13906. if (offset < 100) {
  13907. std::string data(100, 'A');
  13908. sink.write(data.c_str(), data.size());
  13909. return true;
  13910. }
  13911. std::this_thread::sleep_for(std::chrono::seconds(3));
  13912. std::string data(900, 'B');
  13913. sink.write(data.c_str(), data.size());
  13914. return true;
  13915. });
  13916. });
  13917. auto port = 8093;
  13918. std::thread t([&]() { svr.listen("localhost", port); });
  13919. svr.wait_until_ready();
  13920. SSLClient cli("localhost", port);
  13921. cli.enable_server_certificate_verification(false);
  13922. cli.set_read_timeout(1, 0); // 1 second timeout
  13923. auto handle = cli.open_stream("GET", "/slow-stream");
  13924. ASSERT_TRUE(handle.is_valid());
  13925. char buf[256];
  13926. ssize_t total = 0;
  13927. ssize_t n;
  13928. bool got_error = false;
  13929. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13930. total += n;
  13931. }
  13932. if (n < 0) {
  13933. got_error = true;
  13934. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13935. handle.get_read_error() == Error::Read)
  13936. << "Actual error: " << to_string(handle.get_read_error());
  13937. }
  13938. EXPECT_TRUE(got_error || total < 1000)
  13939. << "Expected timeout but got all " << total << " bytes";
  13940. svr.stop();
  13941. t.join();
  13942. }
  13943. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13944. // Test SSL connection closed detection
  13945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13946. std::atomic<bool> close_now{false};
  13947. svr.Get("/will-close", [&](const Request &, Response &res) {
  13948. res.set_content_provider(
  13949. 10000, "text/plain",
  13950. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13951. if (offset < 100) {
  13952. std::string data(100, 'X');
  13953. sink.write(data.c_str(), data.size());
  13954. return true;
  13955. }
  13956. while (!close_now) {
  13957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13958. }
  13959. return false;
  13960. });
  13961. });
  13962. auto port = 8094;
  13963. std::thread t([&]() { svr.listen("localhost", port); });
  13964. svr.wait_until_ready();
  13965. SSLClient cli("localhost", port);
  13966. cli.enable_server_certificate_verification(false);
  13967. auto handle = cli.open_stream("GET", "/will-close");
  13968. ASSERT_TRUE(handle.is_valid());
  13969. char buf[256];
  13970. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13971. EXPECT_GT(n, 0);
  13972. // Signal server to close
  13973. close_now = true;
  13974. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13975. // Keep reading
  13976. }
  13977. if (n < 0) {
  13978. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13979. handle.get_read_error() == Error::Read)
  13980. << "Actual error: " << to_string(handle.get_read_error());
  13981. }
  13982. svr.stop();
  13983. t.join();
  13984. }
  13985. #endif
  13986. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13987. using namespace httplib;
  13988. // Create a test file
  13989. const char *fname = "etag_testfile.txt";
  13990. const char *content = "etag-content";
  13991. {
  13992. std::ofstream ofs(fname);
  13993. ofs << content;
  13994. ASSERT_TRUE(ofs.good());
  13995. }
  13996. Server svr;
  13997. svr.set_mount_point("/static", ".");
  13998. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13999. svr.wait_until_ready();
  14000. Client cli(HOST, PORT);
  14001. // First request: should get 200 with ETag header
  14002. auto res1 = cli.Get("/static/etag_testfile.txt");
  14003. ASSERT_TRUE(res1);
  14004. ASSERT_EQ(200, res1->status);
  14005. ASSERT_TRUE(res1->has_header("ETag"));
  14006. std::string etag = res1->get_header_value("ETag");
  14007. EXPECT_FALSE(etag.empty());
  14008. // Verify ETag format: W/"hex-hex"
  14009. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14010. EXPECT_EQ('W', etag[0]);
  14011. EXPECT_EQ('/', etag[1]);
  14012. EXPECT_EQ('"', etag[2]);
  14013. EXPECT_EQ('"', etag.back());
  14014. // Exact match: expect 304 Not Modified
  14015. Headers h2 = {{"If-None-Match", etag}};
  14016. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14017. ASSERT_TRUE(res2);
  14018. EXPECT_EQ(304, res2->status);
  14019. // Wildcard match: expect 304 Not Modified
  14020. Headers h3 = {{"If-None-Match", "*"}};
  14021. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14022. ASSERT_TRUE(res3);
  14023. EXPECT_EQ(304, res3->status);
  14024. // Non-matching ETag: expect 200
  14025. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14026. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14027. ASSERT_TRUE(res4);
  14028. EXPECT_EQ(200, res4->status);
  14029. // Multiple ETags with one matching: expect 304
  14030. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14031. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14032. ASSERT_TRUE(res5);
  14033. EXPECT_EQ(304, res5->status);
  14034. svr.stop();
  14035. t.join();
  14036. std::remove(fname);
  14037. }
  14038. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14039. using namespace httplib;
  14040. Server svr;
  14041. svr.set_mount_point("/static", ".");
  14042. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14043. svr.wait_until_ready();
  14044. Client cli(HOST, PORT);
  14045. // Send If-None-Match: * to a non-existent file
  14046. Headers h = {{"If-None-Match", "*"}};
  14047. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14048. ASSERT_TRUE(res);
  14049. EXPECT_EQ(404, res->status);
  14050. svr.stop();
  14051. t.join();
  14052. }
  14053. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14054. using namespace httplib;
  14055. // Create a test file
  14056. const char *fname = "etag_boundary_testfile.txt";
  14057. const char *content = "boundary-test";
  14058. {
  14059. std::ofstream ofs(fname);
  14060. ofs << content;
  14061. ASSERT_TRUE(ofs.good());
  14062. }
  14063. Server svr;
  14064. svr.set_mount_point("/static", ".");
  14065. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14066. svr.wait_until_ready();
  14067. Client cli(HOST, PORT);
  14068. // Get the actual ETag
  14069. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14070. ASSERT_TRUE(res1);
  14071. ASSERT_EQ(200, res1->status);
  14072. ASSERT_TRUE(res1->has_header("ETag"));
  14073. std::string etag = res1->get_header_value("ETag");
  14074. // Test 1: Very long ETag value (longer than actual ETag)
  14075. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14076. Headers h1 = {{"If-None-Match", "W/"
  14077. "\"very-long-etag-value-that-is-much-longer-"
  14078. "than-the-actual-etag-value\""}};
  14079. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14080. ASSERT_TRUE(res2);
  14081. EXPECT_EQ(200, res2->status); // Should not match
  14082. // Test 2: Long string followed by wildcard
  14083. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14084. // string)
  14085. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14086. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14087. ASSERT_TRUE(res3);
  14088. EXPECT_EQ(304, res3->status); // Should match on "*"
  14089. // Test 3: Wildcard followed by long string
  14090. // Should match on "*" immediately and return 304
  14091. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14092. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14093. ASSERT_TRUE(res4);
  14094. EXPECT_EQ(304, res4->status); // Should match on "*"
  14095. // Test 4: Multiple long non-matching values
  14096. // Should NOT match and return 200 (test that all comparisons are safe)
  14097. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14098. "W/\"second-long-non-matching-value\", "
  14099. "W/\"third-long-non-matching-value\""}};
  14100. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14101. ASSERT_TRUE(res5);
  14102. EXPECT_EQ(200, res5->status); // Should not match
  14103. // Test 5: Single character that is not "*" (edge case)
  14104. Headers h5 = {{"If-None-Match", "X"}};
  14105. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14106. ASSERT_TRUE(res6);
  14107. EXPECT_EQ(200, res6->status); // Should not match
  14108. svr.stop();
  14109. t.join();
  14110. std::remove(fname);
  14111. }
  14112. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14113. using namespace httplib;
  14114. // Create a test file
  14115. const char *fname = "ims_testfile.txt";
  14116. const char *content = "if-modified-since-test";
  14117. {
  14118. std::ofstream ofs(fname);
  14119. ofs << content;
  14120. ASSERT_TRUE(ofs.good());
  14121. }
  14122. Server svr;
  14123. svr.set_mount_point("/static", ".");
  14124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14125. svr.wait_until_ready();
  14126. Client cli(HOST, PORT);
  14127. // First request: should get 200 with Last-Modified header
  14128. auto res1 = cli.Get("/static/ims_testfile.txt");
  14129. ASSERT_TRUE(res1);
  14130. ASSERT_EQ(200, res1->status);
  14131. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14132. std::string last_modified = res1->get_header_value("Last-Modified");
  14133. EXPECT_FALSE(last_modified.empty());
  14134. // If-Modified-Since with same time: expect 304
  14135. Headers h2 = {{"If-Modified-Since", last_modified}};
  14136. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14137. ASSERT_TRUE(res2);
  14138. EXPECT_EQ(304, res2->status);
  14139. // If-Modified-Since with future time: expect 304
  14140. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14141. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14142. ASSERT_TRUE(res3);
  14143. EXPECT_EQ(304, res3->status);
  14144. // If-Modified-Since with past time: expect 200
  14145. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14146. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14147. ASSERT_TRUE(res4);
  14148. EXPECT_EQ(200, res4->status);
  14149. // If-None-Match takes precedence over If-Modified-Since
  14150. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14151. ASSERT_TRUE(res1->has_header("ETag"));
  14152. std::string etag = res1->get_header_value("ETag");
  14153. Headers h5 = {{"If-None-Match", etag},
  14154. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14155. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14156. ASSERT_TRUE(res5);
  14157. EXPECT_EQ(304, res5->status);
  14158. svr.stop();
  14159. t.join();
  14160. std::remove(fname);
  14161. }
  14162. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14163. using namespace httplib;
  14164. Server svr;
  14165. // Endpoint that returns compressible content
  14166. svr.Get("/compressible", [](const Request &, Response &res) {
  14167. // Return a large enough body to trigger compression
  14168. std::string body(1000, 'a');
  14169. res.set_content(body, "text/plain");
  14170. });
  14171. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14172. svr.wait_until_ready();
  14173. Client cli(HOST, PORT);
  14174. // Request with gzip support: should get Vary header when compressed
  14175. cli.set_compress(true);
  14176. auto res1 = cli.Get("/compressible");
  14177. ASSERT_TRUE(res1);
  14178. EXPECT_EQ(200, res1->status);
  14179. // If Content-Encoding is set, Vary should also be set
  14180. if (res1->has_header("Content-Encoding")) {
  14181. EXPECT_TRUE(res1->has_header("Vary"));
  14182. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14183. }
  14184. // Request without Accept-Encoding header: should not have compression
  14185. Headers h_no_compress;
  14186. auto res2 = cli.Get("/compressible", h_no_compress);
  14187. ASSERT_TRUE(res2);
  14188. EXPECT_EQ(200, res2->status);
  14189. // Verify Vary header is present when compression is applied
  14190. // (the exact behavior depends on server configuration)
  14191. svr.stop();
  14192. t.join();
  14193. }
  14194. TEST(ETagTest, IfRangeWithETag) {
  14195. using namespace httplib;
  14196. // Create a test file with known content
  14197. const char *fname = "if_range_testfile.txt";
  14198. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14199. {
  14200. std::ofstream ofs(fname);
  14201. ofs << content;
  14202. ASSERT_TRUE(ofs.good());
  14203. }
  14204. Server svr;
  14205. svr.set_mount_point("/static", ".");
  14206. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14207. svr.wait_until_ready();
  14208. Client cli(HOST, PORT);
  14209. // First request: get ETag
  14210. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14211. ASSERT_TRUE(res1);
  14212. ASSERT_EQ(200, res1->status);
  14213. ASSERT_TRUE(res1->has_header("ETag"));
  14214. std::string etag = res1->get_header_value("ETag");
  14215. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14216. // Since our server generates weak ETags (W/"..."), If-Range with our
  14217. // ETag should NOT result in partial content - it should return full content.
  14218. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14219. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14220. ASSERT_TRUE(res2);
  14221. // Weak ETag in If-Range -> full content (200), not partial (206)
  14222. EXPECT_EQ(200, res2->status);
  14223. EXPECT_EQ(content, res2->body);
  14224. EXPECT_FALSE(res2->has_header("Content-Range"));
  14225. // Range request with non-matching If-Range (ETag): should get 200 (full
  14226. // content)
  14227. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14228. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14229. ASSERT_TRUE(res3);
  14230. EXPECT_EQ(200, res3->status);
  14231. EXPECT_EQ(content, res3->body);
  14232. EXPECT_FALSE(res3->has_header("Content-Range"));
  14233. // Range request with strong ETag (hypothetical - our server doesn't generate
  14234. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14235. // should return full content)
  14236. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14237. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14238. ASSERT_TRUE(res4);
  14239. EXPECT_EQ(200, res4->status);
  14240. EXPECT_EQ(content, res4->body);
  14241. EXPECT_FALSE(res4->has_header("Content-Range"));
  14242. svr.stop();
  14243. t.join();
  14244. std::remove(fname);
  14245. }
  14246. TEST(ETagTest, IfRangeWithDate) {
  14247. using namespace httplib;
  14248. // Create a test file
  14249. const char *fname = "if_range_date_testfile.txt";
  14250. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14251. {
  14252. std::ofstream ofs(fname);
  14253. ofs << content;
  14254. ASSERT_TRUE(ofs.good());
  14255. }
  14256. Server svr;
  14257. svr.set_mount_point("/static", ".");
  14258. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14259. svr.wait_until_ready();
  14260. Client cli(HOST, PORT);
  14261. // First request: get Last-Modified
  14262. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14263. ASSERT_TRUE(res1);
  14264. ASSERT_EQ(200, res1->status);
  14265. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14266. std::string last_modified = res1->get_header_value("Last-Modified");
  14267. // Range request with matching If-Range (date): should get 206
  14268. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14269. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14270. ASSERT_TRUE(res2);
  14271. EXPECT_EQ(206, res2->status);
  14272. EXPECT_EQ("FGHIJ", res2->body);
  14273. // Range request with old If-Range date: should get 200 (full content)
  14274. Headers h3 = {{"Range", "bytes=5-9"},
  14275. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14276. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14277. ASSERT_TRUE(res3);
  14278. EXPECT_EQ(200, res3->status);
  14279. EXPECT_EQ(content, res3->body);
  14280. // Range request with future If-Range date: should get 206
  14281. Headers h4 = {{"Range", "bytes=0-4"},
  14282. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14283. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14284. ASSERT_TRUE(res4);
  14285. EXPECT_EQ(206, res4->status);
  14286. EXPECT_EQ("ABCDE", res4->body);
  14287. svr.stop();
  14288. t.join();
  14289. std::remove(fname);
  14290. }
  14291. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14292. using namespace httplib;
  14293. const char *fname = "etag_malformed.txt";
  14294. const char *content = "malformed-etag";
  14295. {
  14296. std::ofstream ofs(fname);
  14297. ofs << content;
  14298. ASSERT_TRUE(ofs.good());
  14299. }
  14300. Server svr;
  14301. svr.set_mount_point("/static", ".");
  14302. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14303. svr.wait_until_ready();
  14304. Client cli(HOST, PORT);
  14305. // baseline: should get 200 and an ETag
  14306. auto res1 = cli.Get("/static/etag_malformed.txt");
  14307. ASSERT_TRUE(res1);
  14308. ASSERT_EQ(200, res1->status);
  14309. ASSERT_TRUE(res1->has_header("ETag"));
  14310. // Malformed ETag value (missing quotes) should be treated as non-matching
  14311. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14312. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14313. ASSERT_TRUE(res_bad);
  14314. EXPECT_EQ(200, res_bad->status);
  14315. // Whitespace-only header value should be considered invalid / non-matching
  14316. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14317. "Host: localhost\r\n"
  14318. "If-None-Match: \r\n"
  14319. "Connection: close\r\n"
  14320. "\r\n";
  14321. std::string out;
  14322. ASSERT_TRUE(send_request(5, raw_req, &out));
  14323. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14324. svr.stop();
  14325. t.join();
  14326. std::remove(fname);
  14327. }
  14328. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14329. using namespace httplib;
  14330. const char *fname = "ims_invalid_format.txt";
  14331. const char *content = "ims-bad-format";
  14332. {
  14333. std::ofstream ofs(fname);
  14334. ofs << content;
  14335. ASSERT_TRUE(ofs.good());
  14336. }
  14337. Server svr;
  14338. svr.set_mount_point("/static", ".");
  14339. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14340. svr.wait_until_ready();
  14341. Client cli(HOST, PORT);
  14342. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14343. ASSERT_TRUE(res1);
  14344. ASSERT_EQ(200, res1->status);
  14345. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14346. // If-Modified-Since with invalid format should not result in 304
  14347. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14348. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14349. ASSERT_TRUE(res_bad);
  14350. EXPECT_EQ(200, res_bad->status);
  14351. // If-Range with invalid date format should be treated as mismatch -> full
  14352. // content (200)
  14353. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14354. {"If-Range", "invalid-date"}};
  14355. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14356. ASSERT_TRUE(res_ifrange);
  14357. EXPECT_EQ(200, res_ifrange->status);
  14358. svr.stop();
  14359. t.join();
  14360. std::remove(fname);
  14361. }
  14362. TEST(ETagTest, IfRangeWithMalformedETag) {
  14363. using namespace httplib;
  14364. const char *fname = "ifrange_malformed.txt";
  14365. const std::string content = "0123456789";
  14366. {
  14367. std::ofstream ofs(fname);
  14368. ofs << content;
  14369. ASSERT_TRUE(ofs.good());
  14370. }
  14371. Server svr;
  14372. svr.set_mount_point("/static", ".");
  14373. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14374. svr.wait_until_ready();
  14375. Client cli(HOST, PORT);
  14376. // First request: get ETag
  14377. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14378. ASSERT_TRUE(res1);
  14379. ASSERT_EQ(200, res1->status);
  14380. ASSERT_TRUE(res1->has_header("ETag"));
  14381. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14382. // full content (200)
  14383. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14384. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14385. ASSERT_TRUE(res2);
  14386. EXPECT_EQ(200, res2->status);
  14387. EXPECT_EQ(content, res2->body);
  14388. svr.stop();
  14389. t.join();
  14390. std::remove(fname);
  14391. }
  14392. TEST(ETagTest, ExtremeLargeDateValues) {
  14393. using namespace httplib;
  14394. const char *fname = "ims_extreme_date.txt";
  14395. const char *content = "ims-extreme-date";
  14396. {
  14397. std::ofstream ofs(fname);
  14398. ofs << content;
  14399. ASSERT_TRUE(ofs.good());
  14400. }
  14401. Server svr;
  14402. svr.set_mount_point("/static", ".");
  14403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14404. svr.wait_until_ready();
  14405. Client cli(HOST, PORT);
  14406. auto res1 = cli.Get(std::string("/static/") + fname);
  14407. ASSERT_TRUE(res1);
  14408. ASSERT_EQ(200, res1->status);
  14409. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14410. // Extremely large year that may overflow date parsing routines.
  14411. Headers h_large_date = {
  14412. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14413. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14414. ASSERT_TRUE(res_bad);
  14415. // Expect server to treat this as invalid/mismatch and return full content
  14416. EXPECT_EQ(200, res_bad->status);
  14417. // If-Range with extremely large date should be treated as mismatch -> full
  14418. // content (200)
  14419. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14420. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14421. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14422. ASSERT_TRUE(res_ifrange);
  14423. EXPECT_EQ(200, res_ifrange->status);
  14424. svr.stop();
  14425. t.join();
  14426. std::remove(fname);
  14427. }
  14428. TEST(ETagTest, NegativeFileModificationTime) {
  14429. using namespace httplib;
  14430. const char *fname = "ims_negative_mtime.txt";
  14431. const std::string content = "negative-mtime";
  14432. {
  14433. std::ofstream ofs(fname);
  14434. ofs << content;
  14435. ASSERT_TRUE(ofs.good());
  14436. }
  14437. // Try to set file mtime to a negative value. This may fail on some
  14438. // platforms/filesystems; if it fails, the test will still verify server
  14439. // behaves safely by performing a regular conditional request.
  14440. #if defined(__APPLE__) || defined(__linux__)
  14441. bool set_negative = false;
  14442. do {
  14443. struct timeval times[2];
  14444. // access time: now
  14445. times[0].tv_sec = time(nullptr);
  14446. times[0].tv_usec = 0;
  14447. // modification time: negative (e.g., -1)
  14448. times[1].tv_sec = -1;
  14449. times[1].tv_usec = 0;
  14450. if (utimes(fname, times) == 0) { set_negative = true; }
  14451. } while (0);
  14452. #else
  14453. bool set_negative = false;
  14454. #endif
  14455. Server svr;
  14456. svr.set_mount_point("/static", ".");
  14457. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14458. svr.wait_until_ready();
  14459. Client cli(HOST, PORT);
  14460. auto res1 = cli.Get(std::string("/static/") + fname);
  14461. ASSERT_TRUE(res1);
  14462. ASSERT_EQ(200, res1->status);
  14463. bool has_last_modified = res1->has_header("Last-Modified");
  14464. std::string last_modified;
  14465. if (has_last_modified) {
  14466. last_modified = res1->get_header_value("Last-Modified");
  14467. }
  14468. if (set_negative) {
  14469. // If we successfully set a negative mtime, ensure server returns a
  14470. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14471. // with an old date and ensure server handles it without crash.
  14472. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14473. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14474. ASSERT_TRUE(res2);
  14475. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14476. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14477. } else {
  14478. // Could not set negative mtime on this platform; fall back to verifying
  14479. // that normal invalid/malformed dates are treated safely (non-304).
  14480. Headers h_bad_date = {
  14481. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14482. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14483. ASSERT_TRUE(res_bad);
  14484. EXPECT_EQ(200, res_bad->status);
  14485. }
  14486. svr.stop();
  14487. t.join();
  14488. std::remove(fname);
  14489. }
  14490. //==============================================================================
  14491. // SSE Parsing Tests
  14492. //==============================================================================
  14493. class SSEParsingTest : public ::testing::Test {
  14494. protected:
  14495. // Test helper that mimics SSE parsing behavior
  14496. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14497. int &retry_ms) {
  14498. // Blank line signals end of event
  14499. if (line.empty() || line == "\r") { return true; }
  14500. // Lines starting with ':' are comments (ignored)
  14501. if (!line.empty() && line[0] == ':') { return false; }
  14502. // Find the colon separator
  14503. auto colon_pos = line.find(':');
  14504. if (colon_pos == std::string::npos) {
  14505. // Line with no colon is treated as field name with empty value
  14506. return false;
  14507. }
  14508. std::string field = line.substr(0, colon_pos);
  14509. std::string value;
  14510. // Value starts after colon, skip optional single space
  14511. if (colon_pos + 1 < line.size()) {
  14512. size_t value_start = colon_pos + 1;
  14513. if (line[value_start] == ' ') { value_start++; }
  14514. value = line.substr(value_start);
  14515. // Remove trailing \r if present
  14516. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14517. }
  14518. // Handle known fields
  14519. if (field == "event") {
  14520. msg.event = value;
  14521. } else if (field == "data") {
  14522. // Multiple data lines are concatenated with newlines
  14523. if (!msg.data.empty()) { msg.data += "\n"; }
  14524. msg.data += value;
  14525. } else if (field == "id") {
  14526. // Empty id is valid (clears the last event ID)
  14527. msg.id = value;
  14528. } else if (field == "retry") {
  14529. // Parse retry interval in milliseconds
  14530. {
  14531. int v = 0;
  14532. auto res =
  14533. detail::from_chars(value.data(), value.data() + value.size(), v);
  14534. if (res.ec == std::errc{}) { retry_ms = v; }
  14535. }
  14536. }
  14537. // Unknown fields are ignored per SSE spec
  14538. return false;
  14539. }
  14540. };
  14541. // Test: Single-line data
  14542. TEST_F(SSEParsingTest, SingleLineData) {
  14543. sse::SSEMessage msg;
  14544. int retry_ms = 3000;
  14545. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14546. EXPECT_EQ(msg.data, "hello");
  14547. EXPECT_EQ(msg.event, "message");
  14548. // Blank line ends event
  14549. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14550. }
  14551. // Test: Multi-line data
  14552. TEST_F(SSEParsingTest, MultiLineData) {
  14553. sse::SSEMessage msg;
  14554. int retry_ms = 3000;
  14555. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14556. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14557. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14558. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14559. }
  14560. // Test: Custom event types
  14561. TEST_F(SSEParsingTest, CustomEventType) {
  14562. sse::SSEMessage msg;
  14563. int retry_ms = 3000;
  14564. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14565. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14566. EXPECT_EQ(msg.event, "update");
  14567. EXPECT_EQ(msg.data, "payload");
  14568. }
  14569. // Test: Event ID handling
  14570. TEST_F(SSEParsingTest, EventIdHandling) {
  14571. sse::SSEMessage msg;
  14572. int retry_ms = 3000;
  14573. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14574. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14575. EXPECT_EQ(msg.id, "12345");
  14576. }
  14577. // Test: Empty event ID (clears last event ID)
  14578. TEST_F(SSEParsingTest, EmptyEventId) {
  14579. sse::SSEMessage msg;
  14580. msg.id = "previous";
  14581. int retry_ms = 3000;
  14582. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14583. EXPECT_EQ(msg.id, "");
  14584. }
  14585. // Test: Retry field parsing
  14586. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14587. sse::SSEMessage msg;
  14588. int retry_ms = 3000;
  14589. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14590. EXPECT_EQ(retry_ms, 5000);
  14591. }
  14592. // Test: Invalid retry value
  14593. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14594. sse::SSEMessage msg;
  14595. int retry_ms = 3000;
  14596. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14597. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14598. }
  14599. // Test: Comments (lines starting with :)
  14600. TEST_F(SSEParsingTest, CommentsIgnored) {
  14601. sse::SSEMessage msg;
  14602. int retry_ms = 3000;
  14603. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14604. EXPECT_EQ(msg.data, "");
  14605. EXPECT_EQ(msg.event, "message");
  14606. }
  14607. // Test: Colon in value
  14608. TEST_F(SSEParsingTest, ColonInValue) {
  14609. sse::SSEMessage msg;
  14610. int retry_ms = 3000;
  14611. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14612. EXPECT_EQ(msg.data, "hello:world:test");
  14613. }
  14614. // Test: Line with no colon (field name only)
  14615. TEST_F(SSEParsingTest, FieldNameOnly) {
  14616. sse::SSEMessage msg;
  14617. int retry_ms = 3000;
  14618. // According to SSE spec, this is treated as field name with empty value
  14619. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14620. // Since we don't recognize "data" without colon, data should be empty
  14621. EXPECT_EQ(msg.data, "");
  14622. }
  14623. // Test: Trailing \r handling
  14624. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14625. sse::SSEMessage msg;
  14626. int retry_ms = 3000;
  14627. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14628. EXPECT_EQ(msg.data, "hello");
  14629. }
  14630. // Test: Unknown fields ignored
  14631. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14632. sse::SSEMessage msg;
  14633. int retry_ms = 3000;
  14634. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14635. EXPECT_EQ(msg.data, "");
  14636. EXPECT_EQ(msg.event, "message");
  14637. }
  14638. // Test: Space after colon is optional
  14639. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14640. sse::SSEMessage msg1, msg2;
  14641. int retry_ms = 3000;
  14642. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14643. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14644. EXPECT_EQ(msg1.data, "hello");
  14645. EXPECT_EQ(msg2.data, "hello");
  14646. }
  14647. // Test: SSEMessage clear
  14648. TEST_F(SSEParsingTest, MessageClear) {
  14649. sse::SSEMessage msg;
  14650. msg.event = "custom";
  14651. msg.data = "some data";
  14652. msg.id = "123";
  14653. msg.clear();
  14654. EXPECT_EQ(msg.event, "message");
  14655. EXPECT_EQ(msg.data, "");
  14656. EXPECT_EQ(msg.id, "");
  14657. }
  14658. // Test: Complete event parsing
  14659. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14660. sse::SSEMessage msg;
  14661. int retry_ms = 3000;
  14662. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14663. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14664. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14665. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14666. // Blank line ends event
  14667. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14668. EXPECT_EQ(msg.event, "notification");
  14669. EXPECT_EQ(msg.id, "evt-42");
  14670. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14671. EXPECT_EQ(retry_ms, 1000);
  14672. }
  14673. //==============================================================================
  14674. // Integration Tests with Server
  14675. //==============================================================================
  14676. class SSEIntegrationTest : public ::testing::Test {
  14677. protected:
  14678. void SetUp() override {
  14679. stop_server_.store(false);
  14680. events_.clear();
  14681. server_ = httplib::detail::make_unique<Server>();
  14682. setup_server();
  14683. start_server();
  14684. }
  14685. void TearDown() override {
  14686. stop_server_.store(true);
  14687. event_cv_.notify_all();
  14688. server_->stop();
  14689. if (server_thread_.joinable()) { server_thread_.join(); }
  14690. }
  14691. void setup_server() {
  14692. // Simple SSE endpoint
  14693. server_->Get("/events", [this](const Request &req, Response &res) {
  14694. auto last_id = req.get_header_value("Last-Event-ID");
  14695. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14696. res.set_chunked_content_provider(
  14697. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14698. std::unique_lock<std::mutex> lock(event_mutex_);
  14699. if (event_cv_.wait_for(
  14700. lock, std::chrono::milliseconds(200), [this] {
  14701. return !events_.empty() || stop_server_.load();
  14702. })) {
  14703. if (stop_server_.load()) { return false; }
  14704. if (!events_.empty()) {
  14705. std::string event = events_.front();
  14706. events_.erase(events_.begin());
  14707. sink.write(event.data(), event.size());
  14708. return true;
  14709. }
  14710. }
  14711. return !stop_server_.load();
  14712. });
  14713. });
  14714. // Endpoint that returns error
  14715. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14716. res.status = 500;
  14717. res.set_content("Internal Server Error", "text/plain");
  14718. });
  14719. // Endpoint for custom event types
  14720. server_->Get("/custom-events", [](const Request &, Response &res) {
  14721. res.set_chunked_content_provider(
  14722. "text/event-stream", [](size_t offset, DataSink &sink) {
  14723. if (offset == 0) {
  14724. std::string event = "event: update\ndata: updated\n\n"
  14725. "event: delete\ndata: deleted\n\n";
  14726. sink.write(event.data(), event.size());
  14727. }
  14728. return false; // End stream after sending
  14729. });
  14730. });
  14731. }
  14732. void start_server() {
  14733. port_ = server_->bind_to_any_port(HOST);
  14734. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14735. // Wait for server to start
  14736. while (!server_->is_running()) {
  14737. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14738. }
  14739. }
  14740. int get_port() const { return port_; }
  14741. void send_event(const std::string &event) {
  14742. std::lock_guard<std::mutex> lock(event_mutex_);
  14743. events_.push_back(event);
  14744. event_cv_.notify_all();
  14745. }
  14746. std::unique_ptr<Server> server_;
  14747. std::thread server_thread_;
  14748. std::mutex event_mutex_;
  14749. std::condition_variable event_cv_;
  14750. std::vector<std::string> events_;
  14751. std::atomic<bool> stop_server_{false};
  14752. std::string last_received_event_id_;
  14753. int port_ = 0;
  14754. };
  14755. // Test: Successful connection and on_open callback
  14756. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14757. // Add a simple endpoint that sends one event and closes
  14758. server_->Get("/simple-event", [](const Request &, Response &res) {
  14759. res.set_chunked_content_provider(
  14760. "text/event-stream", [](size_t offset, DataSink &sink) {
  14761. if (offset == 0) {
  14762. std::string event = "data: hello\n\n";
  14763. sink.write(event.data(), event.size());
  14764. }
  14765. return false; // Close stream after sending
  14766. });
  14767. });
  14768. Client client("localhost", get_port());
  14769. sse::SSEClient sse(client, "/simple-event");
  14770. std::atomic<bool> open_called{false};
  14771. std::atomic<bool> message_received{false};
  14772. sse.on_open([&open_called]() { open_called.store(true); });
  14773. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14774. if (msg.data == "hello") { message_received.store(true); }
  14775. });
  14776. sse.set_reconnect_interval(100);
  14777. sse.set_max_reconnect_attempts(1);
  14778. // Start async
  14779. sse.start_async();
  14780. // Wait for message to be processed
  14781. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14782. sse.stop();
  14783. EXPECT_TRUE(open_called.load());
  14784. EXPECT_TRUE(message_received.load());
  14785. }
  14786. // Test: on_message callback
  14787. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14788. // Endpoint that sends multiple events then closes
  14789. server_->Get("/multi-event", [](const Request &, Response &res) {
  14790. res.set_chunked_content_provider(
  14791. "text/event-stream", [](size_t offset, DataSink &sink) {
  14792. if (offset == 0) {
  14793. std::string events = "data: message1\n\ndata: message2\n\n";
  14794. sink.write(events.data(), events.size());
  14795. }
  14796. return false;
  14797. });
  14798. });
  14799. Client client("localhost", get_port());
  14800. sse::SSEClient sse(client, "/multi-event");
  14801. std::vector<std::string> received_messages;
  14802. std::mutex messages_mutex;
  14803. sse.on_message([&](const sse::SSEMessage &msg) {
  14804. std::lock_guard<std::mutex> lock(messages_mutex);
  14805. received_messages.push_back(msg.data);
  14806. });
  14807. sse.set_reconnect_interval(100);
  14808. sse.set_max_reconnect_attempts(1);
  14809. sse.start_async();
  14810. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14811. sse.stop();
  14812. std::lock_guard<std::mutex> lock(messages_mutex);
  14813. EXPECT_GE(received_messages.size(), 2u);
  14814. if (received_messages.size() >= 2) {
  14815. EXPECT_EQ(received_messages[0], "message1");
  14816. EXPECT_EQ(received_messages[1], "message2");
  14817. }
  14818. }
  14819. // Test: on_event for specific types
  14820. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14821. Client client("localhost", get_port());
  14822. sse::SSEClient sse(client, "/custom-events");
  14823. std::atomic<bool> update_received{false};
  14824. std::atomic<bool> delete_received{false};
  14825. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14826. if (msg.data == "updated") { update_received.store(true); }
  14827. });
  14828. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14829. if (msg.data == "deleted") { delete_received.store(true); }
  14830. });
  14831. sse.set_max_reconnect_attempts(1);
  14832. sse.start_async();
  14833. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14834. sse.stop();
  14835. EXPECT_TRUE(update_received.load());
  14836. EXPECT_TRUE(delete_received.load());
  14837. }
  14838. // Test: on_error callback on connection failure
  14839. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14840. // Connect to a non-existent port
  14841. Client client("localhost", 59999);
  14842. sse::SSEClient sse(client, "/events");
  14843. std::atomic<bool> error_called{false};
  14844. Error received_error = Error::Success;
  14845. sse.on_error([&](Error err) {
  14846. error_called.store(true);
  14847. received_error = err;
  14848. });
  14849. sse.set_reconnect_interval(50);
  14850. sse.set_max_reconnect_attempts(1);
  14851. sse.start_async();
  14852. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14853. sse.stop();
  14854. EXPECT_TRUE(error_called.load());
  14855. EXPECT_NE(received_error, Error::Success);
  14856. }
  14857. // Test: Last-Event-ID header sent on reconnect
  14858. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14859. // Endpoint that sends event with ID
  14860. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14861. res.set_chunked_content_provider(
  14862. "text/event-stream", [](size_t offset, DataSink &sink) {
  14863. if (offset == 0) {
  14864. std::string event = "id: evt-123\ndata: test\n\n";
  14865. sink.write(event.data(), event.size());
  14866. }
  14867. return false;
  14868. });
  14869. });
  14870. Client client("localhost", get_port());
  14871. sse::SSEClient sse(client, "/event-with-id");
  14872. std::atomic<bool> id_received{false};
  14873. sse.on_message([&](const sse::SSEMessage &msg) {
  14874. if (!msg.id.empty()) { id_received.store(true); }
  14875. });
  14876. sse.set_reconnect_interval(100);
  14877. sse.set_max_reconnect_attempts(1);
  14878. sse.start_async();
  14879. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14880. sse.stop();
  14881. EXPECT_TRUE(id_received.load());
  14882. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14883. }
  14884. // Test: Manual stop
  14885. TEST_F(SSEIntegrationTest, ManualStop) {
  14886. // Endpoint that sends one event and stays open briefly
  14887. std::atomic<bool> handler_running{true};
  14888. server_->Get("/stay-open", [&handler_running](const Request &,
  14889. Response &res) {
  14890. res.set_chunked_content_provider(
  14891. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14892. if (offset == 0) {
  14893. std::string event = "data: connected\n\n";
  14894. sink.write(event.data(), event.size());
  14895. }
  14896. // Keep connection open while handler_running is true
  14897. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14898. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14899. }
  14900. return false;
  14901. });
  14902. });
  14903. Client client("localhost", get_port());
  14904. sse::SSEClient sse(client, "/stay-open");
  14905. std::atomic<bool> connected{false};
  14906. sse.on_open([&connected]() { connected.store(true); });
  14907. sse.set_reconnect_interval(100);
  14908. sse.set_max_reconnect_attempts(1);
  14909. sse.start_async();
  14910. // Wait for connection to establish
  14911. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14912. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14913. }
  14914. EXPECT_TRUE(connected.load());
  14915. EXPECT_TRUE(sse.is_connected());
  14916. // Signal handler to stop
  14917. handler_running.store(false);
  14918. // Stop SSE client
  14919. sse.stop();
  14920. EXPECT_FALSE(sse.is_connected());
  14921. }
  14922. // Test: SSEClient with custom headers
  14923. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14924. // Setup a server endpoint that checks for custom header
  14925. std::atomic<bool> header_received{false};
  14926. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14927. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14928. header_received.store(true);
  14929. }
  14930. res.set_chunked_content_provider("text/event-stream",
  14931. [](size_t, DataSink &) { return false; });
  14932. });
  14933. Client client("localhost", get_port());
  14934. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14935. sse::SSEClient sse(client, "/header-check", headers);
  14936. sse.set_max_reconnect_attempts(1);
  14937. sse.start_async();
  14938. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14939. sse.stop();
  14940. EXPECT_TRUE(header_received.load());
  14941. }
  14942. // Test: Reconnect interval configuration
  14943. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14944. Client client("localhost", get_port());
  14945. sse::SSEClient sse(client, "/events");
  14946. auto &result = sse.set_reconnect_interval(500);
  14947. // Builder pattern should return reference to self
  14948. EXPECT_EQ(&result, &sse);
  14949. }
  14950. // Test: Max reconnect attempts
  14951. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14952. // Connect to non-existent port to force reconnects
  14953. Client client("localhost", 59998);
  14954. sse::SSEClient sse(client, "/events");
  14955. std::atomic<int> error_count{0};
  14956. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14957. sse.set_reconnect_interval(50);
  14958. sse.set_max_reconnect_attempts(2);
  14959. auto start = std::chrono::steady_clock::now();
  14960. sse.start(); // Blocking call
  14961. auto end = std::chrono::steady_clock::now();
  14962. // Should have stopped after 2 failed attempts
  14963. EXPECT_GE(error_count.load(), 2);
  14964. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14965. auto duration =
  14966. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14967. #ifdef _WIN32
  14968. // Windows is much slower for socket connection failures
  14969. EXPECT_LT(duration.count(), 7000);
  14970. #else
  14971. EXPECT_LT(duration.count(), 1000);
  14972. #endif
  14973. }
  14974. // Test: Multi-line data in integration
  14975. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14976. // Endpoint with multi-line data
  14977. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14978. res.set_chunked_content_provider(
  14979. "text/event-stream", [](size_t offset, DataSink &sink) {
  14980. if (offset == 0) {
  14981. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14982. sink.write(event.data(), event.size());
  14983. }
  14984. return false;
  14985. });
  14986. });
  14987. Client client("localhost", get_port());
  14988. sse::SSEClient sse(client, "/multiline-data");
  14989. std::string received_data;
  14990. std::mutex data_mutex;
  14991. sse.on_message([&](const sse::SSEMessage &msg) {
  14992. std::lock_guard<std::mutex> lock(data_mutex);
  14993. received_data = msg.data;
  14994. });
  14995. sse.set_reconnect_interval(100);
  14996. sse.set_max_reconnect_attempts(1);
  14997. sse.start_async();
  14998. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14999. sse.stop();
  15000. std::lock_guard<std::mutex> lock(data_mutex);
  15001. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15002. }
  15003. // Test: Auto-reconnect after server disconnection
  15004. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15005. std::atomic<int> connection_count{0};
  15006. std::atomic<int> message_count{0};
  15007. // Endpoint that sends one event and closes, forcing reconnect
  15008. server_->Get("/reconnect-test",
  15009. [&connection_count](const Request &, Response &res) {
  15010. connection_count.fetch_add(1);
  15011. res.set_chunked_content_provider(
  15012. "text/event-stream", [](size_t offset, DataSink &sink) {
  15013. if (offset == 0) {
  15014. std::string event = "data: hello\n\n";
  15015. sink.write(event.data(), event.size());
  15016. }
  15017. return false; // Close connection after sending
  15018. });
  15019. });
  15020. Client client("localhost", get_port());
  15021. sse::SSEClient sse(client, "/reconnect-test");
  15022. sse.on_message([&message_count](const sse::SSEMessage &) {
  15023. message_count.fetch_add(1);
  15024. });
  15025. sse.set_reconnect_interval(100);
  15026. sse.set_max_reconnect_attempts(3);
  15027. sse.start_async();
  15028. // Wait long enough for multiple reconnects
  15029. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15030. sse.stop();
  15031. // Should have connected multiple times (initial + reconnects)
  15032. EXPECT_GE(connection_count.load(), 2);
  15033. // Should have received messages from multiple connections
  15034. EXPECT_GE(message_count.load(), 2);
  15035. }
  15036. // Test: Last-Event-ID sent on reconnect
  15037. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15038. std::atomic<int> connection_count{0};
  15039. std::vector<std::string> received_last_event_ids;
  15040. std::mutex id_mutex;
  15041. // Endpoint that checks Last-Event-ID header and sends event with ID
  15042. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15043. int conn = connection_count.fetch_add(1);
  15044. // Capture the Last-Event-ID header from each connection
  15045. {
  15046. std::lock_guard<std::mutex> lock(id_mutex);
  15047. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15048. }
  15049. res.set_chunked_content_provider(
  15050. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15051. if (offset == 0) {
  15052. std::string event =
  15053. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15054. sink.write(event.data(), event.size());
  15055. }
  15056. return false;
  15057. });
  15058. });
  15059. Client client("localhost", get_port());
  15060. sse::SSEClient sse(client, "/reconnect-with-id");
  15061. sse.set_reconnect_interval(100);
  15062. sse.set_max_reconnect_attempts(3);
  15063. sse.start_async();
  15064. // Wait for at least 2 connections
  15065. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15066. sse.stop();
  15067. // Verify behavior
  15068. std::lock_guard<std::mutex> lock(id_mutex);
  15069. EXPECT_GE(received_last_event_ids.size(), 2u);
  15070. // First connection should have no Last-Event-ID
  15071. if (!received_last_event_ids.empty()) {
  15072. EXPECT_EQ(received_last_event_ids[0], "");
  15073. }
  15074. // Second connection should have Last-Event-ID from first connection
  15075. if (received_last_event_ids.size() >= 2) {
  15076. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15077. }
  15078. }
  15079. // Test: set_headers updates headers used on reconnect
  15080. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15081. std::vector<std::string> received_tokens;
  15082. std::mutex token_mutex;
  15083. // Endpoint that captures Authorization header
  15084. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15085. {
  15086. std::lock_guard<std::mutex> lock(token_mutex);
  15087. received_tokens.push_back(req.get_header_value("Authorization"));
  15088. }
  15089. res.set_chunked_content_provider(
  15090. "text/event-stream", [](size_t offset, DataSink &sink) {
  15091. if (offset == 0) {
  15092. std::string event = "data: hello\n\n";
  15093. sink.write(event.data(), event.size());
  15094. }
  15095. return false; // Close connection to trigger reconnect
  15096. });
  15097. });
  15098. Client client("localhost", get_port());
  15099. Headers headers = {{"Authorization", "Bearer old-token"}};
  15100. sse::SSEClient sse(client, "/auth-check", headers);
  15101. // Update headers on each successful connection
  15102. sse.on_open(
  15103. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15104. sse.set_reconnect_interval(100);
  15105. sse.set_max_reconnect_attempts(3);
  15106. sse.start_async();
  15107. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15108. sse.stop();
  15109. std::lock_guard<std::mutex> lock(token_mutex);
  15110. ASSERT_GE(received_tokens.size(), 2u);
  15111. // First connection uses original header
  15112. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15113. // Second connection uses updated header from set_headers
  15114. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15115. }
  15116. // Test: 401 allows reconnection (so on_error can refresh headers)
  15117. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15118. std::atomic<int> connection_count{0};
  15119. // Endpoint: returns 401 on first attempt, 200 on second
  15120. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15121. int conn = connection_count.fetch_add(1);
  15122. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15123. res.status = StatusCode::Unauthorized_401;
  15124. res.set_content("Unauthorized", "text/plain");
  15125. return;
  15126. }
  15127. res.set_chunked_content_provider(
  15128. "text/event-stream", [](size_t offset, DataSink &sink) {
  15129. if (offset == 0) {
  15130. std::string event = "data: authenticated\n\n";
  15131. sink.write(event.data(), event.size());
  15132. }
  15133. return false;
  15134. });
  15135. });
  15136. Client client("localhost", get_port());
  15137. Headers headers = {{"Authorization", "Bearer expired"}};
  15138. sse::SSEClient sse(client, "/auth-retry", headers);
  15139. std::atomic<bool> message_received{false};
  15140. // Refresh token on error
  15141. sse.on_error(
  15142. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15143. sse.on_message([&](const sse::SSEMessage &msg) {
  15144. if (msg.data == "authenticated") { message_received.store(true); }
  15145. });
  15146. sse.set_reconnect_interval(100);
  15147. sse.set_max_reconnect_attempts(3);
  15148. sse.start_async();
  15149. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15150. sse.stop();
  15151. // Should have reconnected after 401 and succeeded with new token
  15152. EXPECT_GE(connection_count.load(), 2);
  15153. EXPECT_TRUE(message_received.load());
  15154. }
  15155. TEST(Issue2318Test, EmptyHostString) {
  15156. {
  15157. httplib::Client cli_empty("", PORT);
  15158. auto res = cli_empty.Get("/");
  15159. ASSERT_FALSE(res);
  15160. EXPECT_EQ(httplib::Error::Connection, res.error());
  15161. }
  15162. {
  15163. httplib::Client cli(" ", PORT);
  15164. auto res = cli.Get("/");
  15165. ASSERT_FALSE(res);
  15166. EXPECT_EQ(httplib::Error::Connection, res.error());
  15167. }
  15168. }
  15169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15170. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15171. Server svr;
  15172. // Set a small payload limit (1KB)
  15173. svr.set_payload_max_length(1024);
  15174. svr.Post("/test", [&](const Request &req, Response &res) {
  15175. res.set_content("Body size: " + std::to_string(req.body.size()),
  15176. "text/plain");
  15177. });
  15178. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15179. auto se = detail::scope_exit([&] {
  15180. svr.stop();
  15181. listen_thread.join();
  15182. });
  15183. svr.wait_until_ready();
  15184. // Create data that compresses well but exceeds limit when decompressed
  15185. // 8KB of repeated null bytes compresses to a very small size
  15186. std::string original_data(8 * 1024, '\0');
  15187. // Compress the data using gzip
  15188. std::string compressed_data;
  15189. detail::gzip_compressor compressor;
  15190. compressor.compress(original_data.data(), original_data.size(), true,
  15191. [&](const char *data, size_t size) {
  15192. compressed_data.append(data, size);
  15193. return true;
  15194. });
  15195. // Verify compression worked (compressed should be much smaller)
  15196. ASSERT_LT(compressed_data.size(), original_data.size());
  15197. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15198. // Send compressed data with Content-Encoding: gzip
  15199. Client cli(HOST, PORT);
  15200. Headers headers = {{"Content-Encoding", "gzip"}};
  15201. auto res =
  15202. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15203. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15204. ASSERT_TRUE(res);
  15205. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15206. }
  15207. #endif
  15208. // ============================================================================
  15209. // OpenSSL-Specific Tests
  15210. // ============================================================================
  15211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15212. X509 *readCertificate(const std::string &strFileName) {
  15213. std::ifstream inStream(strFileName);
  15214. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15215. std::istreambuf_iterator<char>());
  15216. if (strCertPEM.empty()) return (nullptr);
  15217. BIO *pbCert = BIO_new(BIO_s_mem());
  15218. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15219. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15220. BIO_free(pbCert);
  15221. return (pCert);
  15222. }
  15223. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15224. std::ifstream inStream(strFileName);
  15225. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15226. std::istreambuf_iterator<char>());
  15227. if (strPrivateKeyPEM.empty()) return (nullptr);
  15228. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15229. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15230. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15231. BIO_free(pbPrivKey);
  15232. return (pPrivateKey);
  15233. }
  15234. TEST(BindServerTest, UpdateCerts) {
  15235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15236. int port = svr.bind_to_any_port("0.0.0.0");
  15237. ASSERT_TRUE(svr.is_valid());
  15238. ASSERT_TRUE(port > 0);
  15239. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15240. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15241. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15242. ASSERT_TRUE(cert != nullptr);
  15243. ASSERT_TRUE(ca_cert != nullptr);
  15244. ASSERT_TRUE(key != nullptr);
  15245. X509_STORE *cert_store = X509_STORE_new();
  15246. X509_STORE_add_cert(cert_store, ca_cert);
  15247. // svr.update_certs(cert, key, cert_store); // deprecated
  15248. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15249. CLIENT_CA_CERT_FILE);
  15250. ASSERT_TRUE(svr.is_valid());
  15251. svr.stop();
  15252. X509_STORE_free(cert_store);
  15253. X509_free(cert);
  15254. X509_free(ca_cert);
  15255. EVP_PKEY_free(key);
  15256. }
  15257. // Test that update_certs() updates client CA list correctly
  15258. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15259. // Start with file-based constructor
  15260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15261. ASSERT_TRUE(svr.is_valid());
  15262. // Initially no client CA list should be set
  15263. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15264. ASSERT_TRUE(ssl_ctx != nullptr);
  15265. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15266. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15267. EXPECT_EQ(0, count_before);
  15268. // Now update with client CA (PEM string)
  15269. std::string cert_pem, key_pem, ca_pem;
  15270. read_file(SERVER_CERT_FILE, cert_pem);
  15271. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15272. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15273. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15274. ASSERT_TRUE(svr.is_valid());
  15275. // Now client CA list should be set
  15276. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15277. ASSERT_TRUE(ca_list_after != nullptr);
  15278. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15279. }
  15280. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15281. // Test that the file-path SSLServer constructor properly sets the client CA
  15282. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15284. ASSERT_TRUE(svr.is_valid());
  15285. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15286. ASSERT_TRUE(ssl_ctx != nullptr);
  15287. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15288. ASSERT_TRUE(ca_list != nullptr);
  15289. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15290. }
  15291. #endif
  15292. // ============================================================================
  15293. // MbedTLS-Specific Tests
  15294. // ============================================================================
  15295. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15296. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15297. using namespace httplib::tls;
  15298. // Track if callback was invoked
  15299. bool callback_invoked = false;
  15300. // The callback receives void* ctx which is actually MbedTlsContext*
  15301. // We can access the mbedtls_ssl_config via the context
  15302. auto setup_callback = [&callback_invoked](void *ctx) {
  15303. callback_invoked = true;
  15304. // Cast to MbedTlsContext* to access the ssl config
  15305. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15306. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15307. // Use static variables to hold certificate data (simplified for test)
  15308. static mbedtls_x509_crt own_cert;
  15309. static mbedtls_pk_context own_key;
  15310. static mbedtls_x509_crt ca_chain;
  15311. static bool initialized = false;
  15312. if (!initialized) {
  15313. mbedtls_x509_crt_init(&own_cert);
  15314. mbedtls_pk_init(&own_key);
  15315. mbedtls_x509_crt_init(&ca_chain);
  15316. // Load server certificate
  15317. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15318. return false;
  15319. }
  15320. // Load server private key
  15321. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15322. #if MBEDTLS_VERSION_MAJOR >= 3
  15323. ,
  15324. mbedtls_ctr_drbg_random, nullptr
  15325. #endif
  15326. ) != 0) {
  15327. return false;
  15328. }
  15329. // Load CA chain for client verification
  15330. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15331. return false;
  15332. }
  15333. initialized = true;
  15334. }
  15335. // Configure the SSL config
  15336. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15337. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15338. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15339. // Set minimum TLS version using mbedTLS native API
  15340. #if MBEDTLS_VERSION_MAJOR >= 3
  15341. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15342. #else
  15343. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15344. MBEDTLS_SSL_MINOR_VERSION_3);
  15345. #endif
  15346. return true;
  15347. };
  15348. SSLServer svr(setup_callback);
  15349. ASSERT_TRUE(svr.is_valid());
  15350. ASSERT_TRUE(callback_invoked);
  15351. svr.Get("/test", [&](const Request &req, Response &res) {
  15352. res.set_content("test", "text/plain");
  15353. auto cert = req.peer_cert();
  15354. ASSERT_TRUE(static_cast<bool>(cert));
  15355. auto common_name = cert.subject_cn();
  15356. EXPECT_EQ("Common Name", common_name);
  15357. });
  15358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15359. auto se = detail::scope_exit([&] {
  15360. svr.stop();
  15361. t.join();
  15362. ASSERT_FALSE(svr.is_running());
  15363. });
  15364. svr.wait_until_ready();
  15365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15366. cli.enable_server_certificate_verification(false);
  15367. cli.set_connection_timeout(30);
  15368. auto res = cli.Get("/test");
  15369. ASSERT_TRUE(res);
  15370. ASSERT_EQ(StatusCode::OK_200, res->status);
  15371. }
  15372. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15373. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15374. // keep-alive SSL session, which reads through that config in
  15375. // mbedtls_ssl_close_notify.
  15376. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15378. ASSERT_TRUE(svr.is_valid());
  15379. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15380. res.set_content("test", "text/plain");
  15381. });
  15382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15383. auto se = detail::scope_exit([&] {
  15384. svr.stop();
  15385. t.join();
  15386. ASSERT_FALSE(svr.is_running());
  15387. });
  15388. svr.wait_until_ready();
  15389. {
  15390. SSLClient cli(HOST, PORT);
  15391. cli.enable_server_certificate_verification(false);
  15392. cli.set_keep_alive(true);
  15393. auto res = cli.Get("/test");
  15394. ASSERT_TRUE(res);
  15395. ASSERT_EQ(StatusCode::OK_200, res->status);
  15396. // cli is destructed here with the keep-alive SSL session still open.
  15397. }
  15398. }
  15399. #endif
  15400. // WebSocket Tests
  15401. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15402. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15403. // defining the meaning of these bits has been negotiated.
  15404. auto make_frame = [](uint8_t first_byte) {
  15405. std::string frame;
  15406. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15407. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15408. frame += "Hello";
  15409. return frame;
  15410. };
  15411. // RSV1 set (0x40)
  15412. {
  15413. detail::BufferStream strm;
  15414. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15415. ws::Opcode opcode;
  15416. std::string payload;
  15417. bool fin;
  15418. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15419. false, 1024));
  15420. }
  15421. // RSV2 set (0x20)
  15422. {
  15423. detail::BufferStream strm;
  15424. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15425. ws::Opcode opcode;
  15426. std::string payload;
  15427. bool fin;
  15428. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15429. false, 1024));
  15430. }
  15431. // RSV3 set (0x10)
  15432. {
  15433. detail::BufferStream strm;
  15434. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15435. ws::Opcode opcode;
  15436. std::string payload;
  15437. bool fin;
  15438. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15439. false, 1024));
  15440. }
  15441. // No RSV bits set - should succeed
  15442. {
  15443. detail::BufferStream strm;
  15444. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15445. ws::Opcode opcode;
  15446. std::string payload;
  15447. bool fin;
  15448. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15449. false, 1024));
  15450. EXPECT_EQ(ws::Opcode::Text, opcode);
  15451. EXPECT_EQ("Hello", payload);
  15452. EXPECT_TRUE(fin);
  15453. }
  15454. }
  15455. TEST(WebSocketTest, ControlFrameValidation) {
  15456. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15457. // payload length <= 125.
  15458. // Ping with FIN=0 - must be rejected
  15459. {
  15460. detail::BufferStream strm;
  15461. std::string frame;
  15462. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15463. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15464. strm.write(frame.data(), frame.size());
  15465. ws::Opcode opcode;
  15466. std::string payload;
  15467. bool fin;
  15468. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15469. false, 1024));
  15470. }
  15471. // Close with FIN=0 - must be rejected
  15472. {
  15473. detail::BufferStream strm;
  15474. std::string frame;
  15475. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15476. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15477. strm.write(frame.data(), frame.size());
  15478. ws::Opcode opcode;
  15479. std::string payload;
  15480. bool fin;
  15481. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15482. false, 1024));
  15483. }
  15484. // Ping with payload_len=126 (extended length) - must be rejected
  15485. {
  15486. detail::BufferStream strm;
  15487. std::string frame;
  15488. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15489. frame += static_cast<char>(126); // payload_len=126 (>125)
  15490. frame += static_cast<char>(0x00); // extended length high byte
  15491. frame += static_cast<char>(126); // extended length low byte
  15492. frame += std::string(126, 'x');
  15493. strm.write(frame.data(), frame.size());
  15494. ws::Opcode opcode;
  15495. std::string payload;
  15496. bool fin;
  15497. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15498. false, 1024));
  15499. }
  15500. // Ping with FIN=1 and payload_len=125 - should succeed
  15501. {
  15502. detail::BufferStream strm;
  15503. std::string frame;
  15504. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15505. frame += static_cast<char>(125); // payload_len=125
  15506. frame += std::string(125, 'x');
  15507. strm.write(frame.data(), frame.size());
  15508. ws::Opcode opcode;
  15509. std::string payload;
  15510. bool fin;
  15511. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15512. false, 1024));
  15513. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15514. EXPECT_EQ(125u, payload.size());
  15515. EXPECT_TRUE(fin);
  15516. }
  15517. }
  15518. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15519. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15520. // length MUST be 0.
  15521. // MSB set - must be rejected
  15522. {
  15523. detail::BufferStream strm;
  15524. std::string frame;
  15525. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15526. frame += static_cast<char>(127); // 64-bit extended length
  15527. frame += static_cast<char>(0x80); // MSB set (invalid)
  15528. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15529. strm.write(frame.data(), frame.size());
  15530. ws::Opcode opcode;
  15531. std::string payload;
  15532. bool fin;
  15533. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15534. false, 1024));
  15535. }
  15536. // MSB clear - should pass length parsing (will be rejected by max_len,
  15537. // but that's a different check; use a small length to verify)
  15538. {
  15539. detail::BufferStream strm;
  15540. std::string frame;
  15541. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15542. frame += static_cast<char>(127); // 64-bit extended length
  15543. frame += std::string(7, '\0'); // high bytes = 0
  15544. frame += static_cast<char>(0x03); // length = 3
  15545. frame += "abc";
  15546. strm.write(frame.data(), frame.size());
  15547. ws::Opcode opcode;
  15548. std::string payload;
  15549. bool fin;
  15550. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15551. false, 1024));
  15552. EXPECT_EQ(ws::Opcode::Text, opcode);
  15553. EXPECT_EQ("abc", payload);
  15554. }
  15555. }
  15556. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15557. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15558. // Valid UTF-8
  15559. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15560. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15561. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15562. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15563. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15564. // Invalid UTF-8
  15565. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15566. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15567. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15568. EXPECT_FALSE(
  15569. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15570. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15571. }
  15572. TEST(WebSocketTest, ConnectAndDisconnect) {
  15573. Server svr;
  15574. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15575. std::string msg;
  15576. while (ws.read(msg)) {}
  15577. });
  15578. auto port = svr.bind_to_any_port(HOST);
  15579. std::thread t([&]() { svr.listen_after_bind(); });
  15580. svr.wait_until_ready();
  15581. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15582. ASSERT_TRUE(client.connect());
  15583. EXPECT_TRUE(client.is_open());
  15584. client.close();
  15585. EXPECT_FALSE(client.is_open());
  15586. svr.stop();
  15587. t.join();
  15588. }
  15589. TEST(WebSocketTest, ValidURL) {
  15590. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15591. EXPECT_TRUE(ws1.is_valid());
  15592. ws::WebSocketClient ws2("ws://example.com/path");
  15593. EXPECT_TRUE(ws2.is_valid());
  15594. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15595. EXPECT_TRUE(ws3.is_valid());
  15596. #ifdef CPPHTTPLIB_SSL_ENABLED
  15597. ws::WebSocketClient wss1("wss://example.com/path");
  15598. EXPECT_TRUE(wss1.is_valid());
  15599. ws::WebSocketClient wss2("wss://example.com:443/path");
  15600. EXPECT_TRUE(wss2.is_valid());
  15601. #endif
  15602. }
  15603. TEST(WebSocketTest, InvalidURL) {
  15604. // No scheme
  15605. ws::WebSocketClient ws1("localhost:8080/path");
  15606. EXPECT_FALSE(ws1.is_valid());
  15607. // No path
  15608. ws::WebSocketClient ws2("ws://localhost:8080");
  15609. EXPECT_FALSE(ws2.is_valid());
  15610. // Empty string
  15611. ws::WebSocketClient ws3("");
  15612. EXPECT_FALSE(ws3.is_valid());
  15613. // Missing host
  15614. ws::WebSocketClient ws4("ws://:8080/path");
  15615. EXPECT_FALSE(ws4.is_valid());
  15616. // Port number overflow — should not crash
  15617. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15618. EXPECT_FALSE(ws5.is_valid());
  15619. // Port out of range
  15620. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15621. EXPECT_FALSE(ws6.is_valid());
  15622. }
  15623. TEST(WebSocketTest, UnsupportedScheme) {
  15624. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15625. ws::WebSocketClient ws1("http://localhost:8080/path");
  15626. EXPECT_FALSE(ws1.is_valid());
  15627. ws::WebSocketClient ws2("https://localhost:8080/path");
  15628. EXPECT_FALSE(ws2.is_valid());
  15629. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15630. EXPECT_FALSE(ws3.is_valid());
  15631. #else
  15632. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15633. std::invalid_argument);
  15634. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15635. std::invalid_argument);
  15636. #endif
  15637. }
  15638. TEST(WebSocketTest, ConnectWhenInvalid) {
  15639. ws::WebSocketClient ws("not a valid url");
  15640. EXPECT_FALSE(ws.is_valid());
  15641. EXPECT_FALSE(ws.connect());
  15642. }
  15643. TEST(WebSocketTest, DefaultPort) {
  15644. ws::WebSocketClient ws1("ws://example.com/path");
  15645. EXPECT_TRUE(ws1.is_valid());
  15646. // ws:// defaults to port 80 (verified by successful parse)
  15647. #ifdef CPPHTTPLIB_SSL_ENABLED
  15648. ws::WebSocketClient ws2("wss://example.com/path");
  15649. EXPECT_TRUE(ws2.is_valid());
  15650. // wss:// defaults to port 443 (verified by successful parse)
  15651. #endif
  15652. }
  15653. TEST(WebSocketTest, IPv6LiteralAddress) {
  15654. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15655. EXPECT_TRUE(ws1.is_valid());
  15656. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15657. EXPECT_TRUE(ws2.is_valid());
  15658. }
  15659. TEST(WebSocketTest, ComplexPath) {
  15660. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15661. EXPECT_TRUE(ws1.is_valid());
  15662. ws::WebSocketClient ws2("ws://localhost:8080/");
  15663. EXPECT_TRUE(ws2.is_valid());
  15664. }
  15665. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15666. Server svr;
  15667. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15668. std::string msg;
  15669. while (ws.read(msg)) {}
  15670. });
  15671. auto port = svr.bind_to_any_port(HOST);
  15672. std::thread t([&]() { svr.listen_after_bind(); });
  15673. svr.wait_until_ready();
  15674. auto another_host = "example.com";
  15675. auto wrong_ip = "192.0.2.1";
  15676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15677. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15678. ASSERT_TRUE(client.connect());
  15679. EXPECT_TRUE(client.is_open());
  15680. client.close();
  15681. svr.stop();
  15682. t.join();
  15683. }
  15684. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15685. Server svr;
  15686. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15687. std::string msg;
  15688. while (ws.read(msg)) {}
  15689. });
  15690. auto port = svr.bind_to_any_port(HOST);
  15691. std::thread t([&]() { svr.listen_after_bind(); });
  15692. svr.wait_until_ready();
  15693. auto wrong_ip = "192.0.2.1";
  15694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15695. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15696. client.set_connection_timeout(1);
  15697. client.set_read_timeout(1);
  15698. client.set_write_timeout(1);
  15699. EXPECT_FALSE(client.connect());
  15700. EXPECT_FALSE(client.is_open());
  15701. svr.stop();
  15702. t.join();
  15703. }
  15704. class WebSocketIntegrationTest : public ::testing::Test {
  15705. protected:
  15706. void SetUp() override {
  15707. server_ = httplib::detail::make_unique<Server>();
  15708. setup_server();
  15709. start_server();
  15710. }
  15711. void TearDown() override {
  15712. server_->stop();
  15713. if (server_thread_.joinable()) { server_thread_.join(); }
  15714. }
  15715. void setup_server() {
  15716. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15717. std::string msg;
  15718. ws::ReadResult ret;
  15719. while ((ret = ws.read(msg))) {
  15720. if (ret == ws::Binary) {
  15721. ws.send(msg.data(), msg.size());
  15722. } else {
  15723. ws.send(msg);
  15724. }
  15725. }
  15726. });
  15727. server_->WebSocket("/ws-echo-string",
  15728. [](const Request &, ws::WebSocket &ws) {
  15729. std::string msg;
  15730. while (ws.read(msg)) {
  15731. ws.send("echo: " + msg);
  15732. }
  15733. });
  15734. server_->WebSocket(
  15735. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15736. // Echo back request metadata
  15737. ws.send("path:" + req.path);
  15738. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15739. std::string msg;
  15740. while (ws.read(msg)) {}
  15741. });
  15742. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15743. std::string msg;
  15744. ws.read(msg); // wait for a message
  15745. ws.close();
  15746. });
  15747. server_->WebSocket("/ws-close-status",
  15748. [](const Request &, ws::WebSocket &ws) {
  15749. std::string msg;
  15750. ws.read(msg); // wait for a message
  15751. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15752. });
  15753. server_->WebSocket(
  15754. "/ws-subprotocol",
  15755. [](const Request &, ws::WebSocket &ws) {
  15756. std::string msg;
  15757. while (ws.read(msg)) {
  15758. ws.send(msg);
  15759. }
  15760. },
  15761. [](const std::vector<std::string> &protocols) -> std::string {
  15762. for (const auto &p : protocols) {
  15763. if (p == "graphql-ws") { return p; }
  15764. }
  15765. return "";
  15766. });
  15767. }
  15768. void start_server() {
  15769. port_ = server_->bind_to_any_port(HOST);
  15770. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15771. server_->wait_until_ready();
  15772. }
  15773. std::unique_ptr<Server> server_;
  15774. std::thread server_thread_;
  15775. int port_ = 0;
  15776. };
  15777. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15778. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15779. "/ws-echo");
  15780. ASSERT_TRUE(client.connect());
  15781. ASSERT_TRUE(client.is_open());
  15782. ASSERT_TRUE(client.send("Hello WebSocket"));
  15783. std::string msg;
  15784. EXPECT_EQ(ws::Text, client.read(msg));
  15785. EXPECT_EQ("Hello WebSocket", msg);
  15786. client.close();
  15787. }
  15788. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15790. "/ws-echo");
  15791. ASSERT_TRUE(client.connect());
  15792. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15793. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15794. std::string msg;
  15795. EXPECT_EQ(ws::Binary, client.read(msg));
  15796. EXPECT_EQ(binary_data, msg);
  15797. client.close();
  15798. }
  15799. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15800. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15801. "/ws-echo");
  15802. ASSERT_TRUE(client.connect());
  15803. for (int i = 0; i < 10; i++) {
  15804. auto text = "message " + std::to_string(i);
  15805. ASSERT_TRUE(client.send(text));
  15806. std::string msg;
  15807. ASSERT_TRUE(client.read(msg));
  15808. EXPECT_EQ(text, msg);
  15809. }
  15810. client.close();
  15811. }
  15812. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15814. "/ws-close");
  15815. ASSERT_TRUE(client.connect());
  15816. // Send a message to trigger the server to close
  15817. ASSERT_TRUE(client.send("trigger close"));
  15818. // The server will close, so read should return false
  15819. std::string msg;
  15820. EXPECT_FALSE(client.read(msg));
  15821. EXPECT_FALSE(client.is_open());
  15822. }
  15823. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15825. "/ws-echo");
  15826. ASSERT_TRUE(client.connect());
  15827. // 128KB message
  15828. std::string large_data(128 * 1024, 'X');
  15829. ASSERT_TRUE(client.send(large_data));
  15830. std::string msg;
  15831. ASSERT_TRUE(client.read(msg));
  15832. EXPECT_EQ(large_data, msg);
  15833. client.close();
  15834. }
  15835. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15837. "/ws-echo");
  15838. ASSERT_TRUE(client.connect());
  15839. const int num_threads = 4;
  15840. std::vector<std::thread> threads;
  15841. std::atomic<int> send_count{0};
  15842. for (int t = 0; t < num_threads; t++) {
  15843. threads.emplace_back([&client, &send_count, t]() {
  15844. for (int i = 0; i < 5; i++) {
  15845. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15846. if (client.send(text)) { send_count++; }
  15847. }
  15848. });
  15849. }
  15850. for (auto &th : threads) {
  15851. th.join();
  15852. }
  15853. int received = 0;
  15854. std::string msg;
  15855. while (received < send_count.load()) {
  15856. if (!client.read(msg)) { break; }
  15857. received++;
  15858. }
  15859. EXPECT_EQ(send_count.load(), received);
  15860. client.close();
  15861. }
  15862. TEST_F(WebSocketIntegrationTest, ReadString) {
  15863. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15864. "/ws-echo-string");
  15865. ASSERT_TRUE(client.connect());
  15866. ASSERT_TRUE(client.send("hello"));
  15867. std::string msg;
  15868. ASSERT_TRUE(client.read(msg));
  15869. EXPECT_EQ("echo: hello", msg);
  15870. ASSERT_TRUE(client.send("world"));
  15871. ASSERT_TRUE(client.read(msg));
  15872. EXPECT_EQ("echo: world", msg);
  15873. client.close();
  15874. }
  15875. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15876. Headers headers = {{"X-Test-Header", "test-value"}};
  15877. ws::WebSocketClient client(
  15878. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15879. ASSERT_TRUE(client.connect());
  15880. std::string msg;
  15881. ASSERT_TRUE(client.read(msg));
  15882. EXPECT_EQ("path:/ws-request-info", msg);
  15883. ASSERT_TRUE(client.read(msg));
  15884. EXPECT_EQ("header:test-value", msg);
  15885. client.close();
  15886. }
  15887. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15889. "/ws-echo");
  15890. client.set_read_timeout(1, 0); // 1 second
  15891. ASSERT_TRUE(client.connect());
  15892. // Don't send anything — server echo handler waits for a message,
  15893. // so read() should time out and return false.
  15894. std::string msg;
  15895. EXPECT_FALSE(client.read(msg));
  15896. }
  15897. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15899. "/ws-echo");
  15900. client.set_read_timeout(5, 0);
  15901. ASSERT_TRUE(client.connect());
  15902. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15903. // The server should reject it and close the connection.
  15904. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15905. client.send(oversized);
  15906. // The server's read() should have failed due to payload limit,
  15907. // so our read() should return false (connection closed).
  15908. std::string msg;
  15909. EXPECT_FALSE(client.read(msg));
  15910. }
  15911. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15913. "/ws-echo");
  15914. client.set_read_timeout(10, 0);
  15915. ASSERT_TRUE(client.connect());
  15916. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15917. // This should succeed.
  15918. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15919. ASSERT_TRUE(client.send(at_limit));
  15920. std::string msg;
  15921. ASSERT_TRUE(client.read(msg));
  15922. EXPECT_EQ(at_limit.size(), msg.size());
  15923. client.close();
  15924. }
  15925. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15927. "/nonexistent");
  15928. EXPECT_FALSE(client.connect());
  15929. EXPECT_FALSE(client.is_open());
  15930. }
  15931. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15933. "/ws-echo");
  15934. ASSERT_TRUE(client.connect());
  15935. ASSERT_TRUE(client.send(""));
  15936. std::string msg;
  15937. EXPECT_EQ(ws::Text, client.read(msg));
  15938. EXPECT_EQ("", msg);
  15939. client.close();
  15940. }
  15941. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15943. "/ws-echo");
  15944. // First connection
  15945. ASSERT_TRUE(client.connect());
  15946. ASSERT_TRUE(client.send("first"));
  15947. std::string msg;
  15948. ASSERT_TRUE(client.read(msg));
  15949. EXPECT_EQ("first", msg);
  15950. client.close();
  15951. EXPECT_FALSE(client.is_open());
  15952. // Reconnect using the same client object
  15953. ASSERT_TRUE(client.connect());
  15954. ASSERT_TRUE(client.is_open());
  15955. ASSERT_TRUE(client.send("second"));
  15956. ASSERT_TRUE(client.read(msg));
  15957. EXPECT_EQ("second", msg);
  15958. client.close();
  15959. }
  15960. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15962. "/ws-close-status");
  15963. ASSERT_TRUE(client.connect());
  15964. // Trigger the server to close with GoingAway status
  15965. ASSERT_TRUE(client.send("trigger"));
  15966. // read() should return false after receiving the close frame
  15967. std::string msg;
  15968. EXPECT_FALSE(client.read(msg));
  15969. EXPECT_FALSE(client.is_open());
  15970. }
  15971. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15972. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15973. "/ws-echo");
  15974. ASSERT_TRUE(client.connect());
  15975. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15976. EXPECT_FALSE(client.is_open());
  15977. }
  15978. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15979. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15980. ws::WebSocketClient client(
  15981. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15982. ASSERT_TRUE(client.connect());
  15983. // Server should have selected graphql-ws
  15984. EXPECT_EQ("graphql-ws", client.subprotocol());
  15985. client.close();
  15986. }
  15987. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15988. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15989. ws::WebSocketClient client(
  15990. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15991. ASSERT_TRUE(client.connect());
  15992. // Server should not have selected any subprotocol
  15993. EXPECT_TRUE(client.subprotocol().empty());
  15994. client.close();
  15995. }
  15996. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15997. // Connect without requesting any subprotocol
  15998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15999. "/ws-subprotocol");
  16000. ASSERT_TRUE(client.connect());
  16001. EXPECT_TRUE(client.subprotocol().empty());
  16002. client.close();
  16003. }
  16004. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16005. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16006. "/ws-echo");
  16007. client.set_tcp_nodelay(true);
  16008. client.set_connection_timeout(3, 0);
  16009. bool socket_options_called = false;
  16010. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16011. ASSERT_TRUE(client.connect());
  16012. ASSERT_TRUE(client.is_open());
  16013. EXPECT_TRUE(socket_options_called);
  16014. ASSERT_TRUE(client.send("hello"));
  16015. std::string msg;
  16016. auto result = client.read(msg);
  16017. EXPECT_EQ(result, ws::ReadResult::Text);
  16018. EXPECT_EQ(msg, "hello");
  16019. client.close();
  16020. }
  16021. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16022. Server svr;
  16023. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16024. if (!req.has_header("Authorization")) {
  16025. res.status = StatusCode::Unauthorized_401;
  16026. res.set_content("Unauthorized", "text/plain");
  16027. return Server::HandlerResponse::Handled;
  16028. }
  16029. return Server::HandlerResponse::Unhandled;
  16030. });
  16031. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16032. std::string msg;
  16033. while (ws.read(msg)) {
  16034. ws.send(msg);
  16035. }
  16036. });
  16037. auto port = svr.bind_to_any_port("localhost");
  16038. std::thread t([&]() { svr.listen_after_bind(); });
  16039. svr.wait_until_ready();
  16040. // Without Authorization header - should be rejected before upgrade
  16041. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16042. EXPECT_FALSE(client1.connect());
  16043. // With Authorization header - should succeed
  16044. Headers headers = {{"Authorization", "Bearer token123"}};
  16045. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16046. headers);
  16047. ASSERT_TRUE(client2.connect());
  16048. ASSERT_TRUE(client2.send("hello"));
  16049. std::string msg;
  16050. ASSERT_TRUE(client2.read(msg));
  16051. EXPECT_EQ("hello", msg);
  16052. client2.close();
  16053. svr.stop();
  16054. t.join();
  16055. }
  16056. TEST(WebSocketTest, QueryStringInHandshake) {
  16057. Server svr;
  16058. std::mutex mtx;
  16059. std::string received_target;
  16060. std::string received_token;
  16061. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16062. {
  16063. std::lock_guard<std::mutex> lock(mtx);
  16064. received_target = req.target;
  16065. if (req.has_param("token")) {
  16066. received_token = req.get_param_value("token");
  16067. }
  16068. }
  16069. std::string msg;
  16070. while (ws.read(msg)) {
  16071. ws.send(msg);
  16072. }
  16073. });
  16074. auto port = svr.bind_to_any_port("localhost");
  16075. std::thread t([&]() { svr.listen_after_bind(); });
  16076. svr.wait_until_ready();
  16077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16078. "/ws?token=ABC&session=123");
  16079. ASSERT_TRUE(client.connect());
  16080. // Round-trip ensures the handler has run and captured the request.
  16081. ASSERT_TRUE(client.send("hello"));
  16082. std::string msg;
  16083. ASSERT_TRUE(client.read(msg));
  16084. EXPECT_EQ("hello", msg);
  16085. client.close();
  16086. {
  16087. std::lock_guard<std::mutex> lock(mtx);
  16088. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16089. EXPECT_EQ("ABC", received_token);
  16090. }
  16091. svr.stop();
  16092. t.join();
  16093. }
  16094. TEST(WebSocketTest, HostHeaderInHandshake) {
  16095. Server svr;
  16096. std::mutex mtx;
  16097. std::string received_host;
  16098. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16099. {
  16100. std::lock_guard<std::mutex> lock(mtx);
  16101. received_host = req.get_header_value("Host");
  16102. }
  16103. std::string msg;
  16104. while (ws.read(msg)) {
  16105. ws.send(msg);
  16106. }
  16107. });
  16108. auto port = svr.bind_to_any_port("localhost");
  16109. std::thread t([&]() { svr.listen_after_bind(); });
  16110. svr.wait_until_ready();
  16111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16112. ASSERT_TRUE(client.connect());
  16113. // Round-trip ensures the handler has run and captured the request.
  16114. ASSERT_TRUE(client.send("hello"));
  16115. std::string msg;
  16116. ASSERT_TRUE(client.read(msg));
  16117. client.close();
  16118. {
  16119. std::lock_guard<std::mutex> lock(mtx);
  16120. // Non-default port must be present in the Host header. Default ports
  16121. // (80/443) are omitted; that logic is covered by
  16122. // MakeHostAndPortStringTest.
  16123. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16124. }
  16125. svr.stop();
  16126. t.join();
  16127. }
  16128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16129. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16130. protected:
  16131. void SetUp() override {
  16132. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16133. SERVER_PRIVATE_KEY_FILE);
  16134. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16135. std::string msg;
  16136. ws::ReadResult ret;
  16137. while ((ret = ws.read(msg))) {
  16138. if (ret == ws::Binary) {
  16139. ws.send(msg.data(), msg.size());
  16140. } else {
  16141. ws.send(msg);
  16142. }
  16143. }
  16144. });
  16145. port_ = server_->bind_to_any_port(HOST);
  16146. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16147. server_->wait_until_ready();
  16148. }
  16149. void TearDown() override {
  16150. server_->stop();
  16151. if (server_thread_.joinable()) { server_thread_.join(); }
  16152. }
  16153. std::unique_ptr<SSLServer> server_;
  16154. std::thread server_thread_;
  16155. int port_ = 0;
  16156. };
  16157. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16158. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16159. "/ws-echo");
  16160. client.enable_server_certificate_verification(false);
  16161. ASSERT_TRUE(client.connect());
  16162. ASSERT_TRUE(client.is_open());
  16163. ASSERT_TRUE(client.send("Hello WSS"));
  16164. std::string msg;
  16165. EXPECT_EQ(ws::Text, client.read(msg));
  16166. EXPECT_EQ("Hello WSS", msg);
  16167. client.close();
  16168. }
  16169. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16170. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16171. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16172. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16173. // client (without calling close() first) is the only path that runs
  16174. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16175. // bug exactly.
  16176. //
  16177. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16178. // when linked against an instrumented libssl; run under Valgrind to catch it
  16179. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16180. // suite (the freed session otherwise stalls on the close handshake) — this test
  16181. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16182. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16183. {
  16184. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16185. "/ws-echo");
  16186. client.enable_server_certificate_verification(false);
  16187. client.set_read_timeout(2, 0);
  16188. client.set_write_timeout(2, 0);
  16189. ASSERT_TRUE(client.connect());
  16190. ASSERT_TRUE(client.is_open());
  16191. ASSERT_TRUE(client.send("still open"));
  16192. // Intentionally do NOT call client.close(): leaving scope runs
  16193. // shutdown_and_close() with the WebSocket still open, which must send the
  16194. // close frame while the TLS session is still alive.
  16195. }
  16196. }
  16197. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16198. // shutdown_and_close() at the start of connect(), reproducing the same
  16199. // use-after-free within the test body rather than at scope exit. The second
  16200. // connect must succeed and echo, proving the close handshake ran over a live
  16201. // session. See the note above about memory-tool requirements.
  16202. TEST_F(WebSocketSSLIntegrationTest,
  16203. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16204. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16205. "/ws-echo");
  16206. client.enable_server_certificate_verification(false);
  16207. client.set_read_timeout(2, 0);
  16208. client.set_write_timeout(2, 0);
  16209. ASSERT_TRUE(client.connect());
  16210. ASSERT_TRUE(client.is_open());
  16211. ASSERT_TRUE(client.send("still open"));
  16212. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16213. // the still-open connection, which must not touch a freed TLS session.
  16214. ASSERT_TRUE(client.connect());
  16215. ASSERT_TRUE(client.is_open());
  16216. ASSERT_TRUE(client.send("after reconnect"));
  16217. std::string msg;
  16218. EXPECT_EQ(ws::Text, client.read(msg));
  16219. EXPECT_EQ("after reconnect", msg);
  16220. client.close();
  16221. }
  16222. #endif
  16223. #ifdef CPPHTTPLIB_SSL_ENABLED
  16224. class WebSocketSSLCATest : public ::testing::Test {
  16225. protected:
  16226. void SetUp() override {
  16227. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16228. SERVER_PRIVATE_KEY_FILE);
  16229. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16230. std::string msg;
  16231. while (ws.read(msg)) {
  16232. ws.send(msg);
  16233. }
  16234. });
  16235. port_ = server_->bind_to_any_port("127.0.0.1");
  16236. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16237. server_->wait_until_ready();
  16238. }
  16239. void TearDown() override {
  16240. server_->stop();
  16241. if (server_thread_.joinable()) { server_thread_.join(); }
  16242. }
  16243. std::string url() const {
  16244. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16245. }
  16246. std::unique_ptr<SSLServer> server_;
  16247. std::thread server_thread_;
  16248. int port_ = 0;
  16249. };
  16250. // A custom CA loaded as PEM verifies the server with full certificate
  16251. // verification enabled
  16252. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16253. ws::WebSocketClient client(url());
  16254. std::string cert;
  16255. read_file(SERVER_CERT2_FILE, cert);
  16256. client.load_ca_cert_store(cert.c_str(), cert.size());
  16257. ASSERT_TRUE(client.connect());
  16258. ASSERT_TRUE(client.send("hello"));
  16259. std::string msg;
  16260. EXPECT_EQ(ws::Text, client.read(msg));
  16261. EXPECT_EQ("hello", msg);
  16262. client.close();
  16263. }
  16264. // A custom CA that does not cover the server must fail verification (the
  16265. // custom CA is exclusive; system certs are not loaded alongside it)
  16266. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16267. ws::WebSocketClient client(url());
  16268. std::string cert;
  16269. read_file(CLIENT_CA_CERT_FILE, cert);
  16270. client.load_ca_cert_store(cert.c_str(), cert.size());
  16271. ASSERT_FALSE(client.connect());
  16272. }
  16273. // Regression test: reconnecting with a native custom CA store used to reuse
  16274. // a store handle the previous TLS context had already freed (use-after-free
  16275. // under the OpenSSL backend). The context now lives as long as the client.
  16276. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16277. ws::WebSocketClient client(url());
  16278. std::string cert;
  16279. read_file(SERVER_CERT2_FILE, cert);
  16280. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16281. ASSERT_TRUE(client.connect());
  16282. client.close();
  16283. ASSERT_TRUE(client.connect());
  16284. ASSERT_TRUE(client.send("again"));
  16285. std::string msg;
  16286. EXPECT_EQ(ws::Text, client.read(msg));
  16287. EXPECT_EQ("again", msg);
  16288. client.close();
  16289. }
  16290. // Regression test: a certificate with a trusted chain but no identity match
  16291. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16292. // verification entirely for IP hosts, so this connection succeeded there.
  16293. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16294. // chain verification while the identity check must still fail.
  16295. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16297. ASSERT_TRUE(svr.is_valid());
  16298. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16299. std::string msg;
  16300. while (ws.read(msg)) {
  16301. ws.send(msg);
  16302. }
  16303. });
  16304. auto port = svr.bind_to_any_port("127.0.0.1");
  16305. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16306. auto se = detail::scope_exit([&] {
  16307. svr.stop();
  16308. t.join();
  16309. });
  16310. svr.wait_until_ready();
  16311. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16312. "/echo");
  16313. std::string cert;
  16314. read_file(SERVER_CERT_FILE, cert);
  16315. client.load_ca_cert_store(cert.c_str(), cert.size());
  16316. ASSERT_FALSE(client.connect());
  16317. }
  16318. #endif
  16319. #if !defined(_WIN32)
  16320. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16321. auto secret_dir = std::string("./symlink_test_secret");
  16322. auto served_dir = std::string("./symlink_test_served");
  16323. auto secret_file = secret_dir + "/secret.txt";
  16324. auto symlink_path = served_dir + "/escape";
  16325. // Setup: create directories and files
  16326. mkdir(secret_dir.c_str(), 0755);
  16327. mkdir(served_dir.c_str(), 0755);
  16328. {
  16329. std::ofstream ofs(secret_file);
  16330. ofs << "SECRET_DATA";
  16331. }
  16332. // Create symlink using absolute path so it resolves correctly
  16333. #ifdef PATH_MAX
  16334. char abs_secret[PATH_MAX];
  16335. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16336. #else
  16337. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16338. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16339. ASSERT_NE(nullptr, abs_secret);
  16340. #endif
  16341. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16342. auto se = detail::scope_exit([&] {
  16343. unlink(symlink_path.c_str());
  16344. unlink(secret_file.c_str());
  16345. rmdir(served_dir.c_str());
  16346. rmdir(secret_dir.c_str());
  16347. });
  16348. Server svr;
  16349. svr.set_mount_point("/", served_dir);
  16350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16351. auto se2 = detail::scope_exit([&] {
  16352. svr.stop();
  16353. listen_thread.join();
  16354. });
  16355. svr.wait_until_ready();
  16356. Client cli("localhost", PORT);
  16357. // Symlink pointing outside base dir should be blocked
  16358. auto res = cli.Get("/escape/secret.txt");
  16359. ASSERT_TRUE(res);
  16360. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16361. }
  16362. #endif
  16363. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16364. // A GET request with Content-Length to a static file handler must have its
  16365. // body drained before the keep-alive connection is reused. Otherwise the
  16366. // unread body bytes are interpreted as the next HTTP request.
  16367. //
  16368. // The body is sent AFTER receiving the first response (as in the original
  16369. // PoC) so that the stream_line_reader cannot buffer it together with the
  16370. // headers of the first request.
  16371. Server svr;
  16372. svr.set_mount_point("/", "./www");
  16373. std::atomic<int> smuggled_count(0);
  16374. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16375. smuggled_count++;
  16376. res.set_content("oops", "text/plain");
  16377. });
  16378. auto port = svr.bind_to_any_port("localhost");
  16379. thread t = thread([&] { svr.listen_after_bind(); });
  16380. auto se = detail::scope_exit([&] {
  16381. svr.stop();
  16382. t.join();
  16383. });
  16384. svr.wait_until_ready();
  16385. auto error = Error::Success;
  16386. auto sock = detail::create_client_socket(
  16387. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16388. /*connection_timeout_sec=*/2, 0,
  16389. /*read_timeout_sec=*/2, 0,
  16390. /*write_timeout_sec=*/2, 0, std::string(), error);
  16391. ASSERT_NE(INVALID_SOCKET, sock);
  16392. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16393. // The "smuggled" request will be sent as the body of the outer GET
  16394. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16395. "Host: localhost\r\n"
  16396. "Connection: close\r\n"
  16397. "\r\n";
  16398. // Step 1: Send only the outer request headers (no body yet)
  16399. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16400. "Host: localhost\r\n"
  16401. "Content-Length: " +
  16402. std::to_string(smuggled.size()) +
  16403. "\r\n"
  16404. "\r\n";
  16405. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16406. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16407. // Step 2: Read the first response (server serves file without reading body)
  16408. std::string first_response;
  16409. char buf[4096];
  16410. for (;;) {
  16411. auto n = recv(sock, buf, sizeof(buf), 0);
  16412. if (n <= 0) break;
  16413. first_response.append(buf, static_cast<size_t>(n));
  16414. // Stop once we have a complete response (headers + body)
  16415. auto hdr_end = first_response.find("\r\n\r\n");
  16416. if (hdr_end != std::string::npos) {
  16417. // Check for Content-Length to know when the body is complete
  16418. auto cl_pos = first_response.find("Content-Length:");
  16419. if (cl_pos != std::string::npos) {
  16420. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16421. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16422. auto cl = std::stoul(
  16423. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16424. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16425. } else {
  16426. break; // No Content-Length, assume headers-only response
  16427. }
  16428. }
  16429. }
  16430. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16431. // Step 3: Now send the body, which looks like a new HTTP request.
  16432. // On a vulnerable server the keep-alive loop reads this as a second request.
  16433. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16434. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16435. // Step 4: Try to read a second response (should NOT exist after fix)
  16436. std::string second_response;
  16437. for (;;) {
  16438. auto n = recv(sock, buf, sizeof(buf), 0);
  16439. if (n <= 0) break;
  16440. second_response.append(buf, static_cast<size_t>(n));
  16441. }
  16442. // The smuggled request must NOT have been processed
  16443. EXPECT_EQ(0, smuggled_count.load());
  16444. }
  16445. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16446. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16447. // must be rejected with 400 Bad Request.
  16448. Server svr;
  16449. svr.Post("/test", [&](const Request &, Response &res) {
  16450. res.set_content("ok", "text/plain");
  16451. });
  16452. thread t = thread([&] { svr.listen(HOST, PORT); });
  16453. auto se = detail::scope_exit([&] {
  16454. svr.stop();
  16455. t.join();
  16456. ASSERT_FALSE(svr.is_running());
  16457. });
  16458. svr.wait_until_ready();
  16459. // Exact "chunked"
  16460. {
  16461. auto req = "POST /test HTTP/1.1\r\n"
  16462. "Host: localhost\r\n"
  16463. "Content-Length: 5\r\n"
  16464. "Transfer-Encoding: chunked\r\n"
  16465. "Connection: close\r\n"
  16466. "\r\n"
  16467. "hello";
  16468. std::string response;
  16469. ASSERT_TRUE(send_request(1, req, &response));
  16470. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16471. response.substr(0, response.find("\r\n")));
  16472. }
  16473. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16474. {
  16475. auto req = "POST /test HTTP/1.1\r\n"
  16476. "Host: localhost\r\n"
  16477. "Content-Length: 5\r\n"
  16478. "Transfer-Encoding: gzip, chunked\r\n"
  16479. "Connection: close\r\n"
  16480. "\r\n"
  16481. "hello";
  16482. std::string response;
  16483. ASSERT_TRUE(send_request(1, req, &response));
  16484. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16485. response.substr(0, response.find("\r\n")));
  16486. }
  16487. }
  16488. // Regression for issue #2450: a DELETE without Content-Length on a
  16489. // keep-alive connection must not let the post-response drain consume the
  16490. // next request's bytes.
  16491. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16492. Server svr;
  16493. std::atomic<int> delete_count(0);
  16494. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16495. delete_count++;
  16496. res.status = StatusCode::NoContent_204;
  16497. });
  16498. auto port = svr.bind_to_any_port(HOST);
  16499. thread t = thread([&] { svr.listen_after_bind(); });
  16500. auto se = detail::scope_exit([&] {
  16501. svr.stop();
  16502. t.join();
  16503. });
  16504. svr.wait_until_ready();
  16505. auto error = Error::Success;
  16506. auto sock = detail::create_client_socket(
  16507. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16508. /*connection_timeout_sec=*/2, 0,
  16509. /*read_timeout_sec=*/2, 0,
  16510. /*write_timeout_sec=*/2, 0, std::string(), error);
  16511. ASSERT_NE(INVALID_SOCKET, sock);
  16512. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16513. auto send_request_and_read_response = [&](const std::string &req,
  16514. std::string &out) -> bool {
  16515. auto sent = send(sock, req.data(), req.size(), 0);
  16516. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16517. char buf[4096];
  16518. for (;;) {
  16519. auto n = recv(sock, buf, sizeof(buf), 0);
  16520. if (n <= 0) { return !out.empty(); }
  16521. out.append(buf, static_cast<size_t>(n));
  16522. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16523. }
  16524. };
  16525. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16526. "Host: localhost\r\n"
  16527. "\r\n";
  16528. std::string resp1;
  16529. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16530. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16531. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16532. "Host: localhost\r\n"
  16533. "Connection: close\r\n"
  16534. "\r\n";
  16535. std::string resp2;
  16536. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16537. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16538. EXPECT_EQ(2, delete_count.load());
  16539. }
  16540. namespace no_proxy_test {
  16541. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16542. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16543. // calling listen().
  16544. class ScopedServer {
  16545. public:
  16546. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16547. ~ScopedServer() {
  16548. svr_.stop();
  16549. if (th_.joinable()) { th_.join(); }
  16550. }
  16551. Server &svr() { return svr_; }
  16552. int port() const { return port_; }
  16553. void listen() {
  16554. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16555. svr_.wait_until_ready();
  16556. }
  16557. private:
  16558. Server svr_;
  16559. std::thread th_;
  16560. int port_ = 0;
  16561. };
  16562. class ProxyAndTargetServers {
  16563. public:
  16564. ProxyAndTargetServers() {
  16565. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16566. proxy_hits_++;
  16567. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16568. res.set_content("via-proxy", "text/plain");
  16569. });
  16570. target_.Get(".*", [this](const Request &req, Response &res) {
  16571. target_hits_++;
  16572. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16573. res.set_content("direct", "text/plain");
  16574. });
  16575. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16576. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16577. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16578. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16579. proxy_mock_.wait_until_ready();
  16580. target_.wait_until_ready();
  16581. }
  16582. ~ProxyAndTargetServers() {
  16583. proxy_mock_.stop();
  16584. target_.stop();
  16585. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16586. if (target_thread_.joinable()) { target_thread_.join(); }
  16587. }
  16588. Server &proxy_mock() { return proxy_mock_; }
  16589. Server &target() { return target_; }
  16590. int proxy_port() const { return proxy_port_; }
  16591. int target_port() const { return target_port_; }
  16592. int proxy_hits() const { return proxy_hits_.load(); }
  16593. int target_hits() const { return target_hits_.load(); }
  16594. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16595. void reset_counters() {
  16596. proxy_hits_ = 0;
  16597. target_hits_ = 0;
  16598. last_had_proxy_authz_ = false;
  16599. }
  16600. private:
  16601. Server proxy_mock_;
  16602. Server target_;
  16603. std::thread proxy_thread_;
  16604. std::thread target_thread_;
  16605. int proxy_port_ = 0;
  16606. int target_port_ = 0;
  16607. std::atomic<int> proxy_hits_{0};
  16608. std::atomic<int> target_hits_{0};
  16609. std::atomic<bool> last_had_proxy_authz_{false};
  16610. };
  16611. inline std::unique_ptr<Client> make_client(const std::string &host,
  16612. ProxyAndTargetServers &s) {
  16613. auto cli = detail::make_unique<Client>(host, s.target_port());
  16614. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16615. cli->set_proxy("127.0.0.1", s.proxy_port());
  16616. return cli;
  16617. }
  16618. } // namespace no_proxy_test
  16619. using no_proxy_test::make_client;
  16620. using no_proxy_test::ProxyAndTargetServers;
  16621. TEST(NoProxyTest, ExactHostnameBypasses) {
  16622. ProxyAndTargetServers s;
  16623. auto cli = make_client("example.com", s);
  16624. cli->set_no_proxy({"example.com"});
  16625. auto res = cli->Get("/");
  16626. ASSERT_TRUE(res);
  16627. EXPECT_EQ(0, s.proxy_hits());
  16628. EXPECT_EQ(1, s.target_hits());
  16629. }
  16630. TEST(NoProxyTest, SubdomainBypasses) {
  16631. ProxyAndTargetServers s;
  16632. auto cli = make_client("foo.example.com", s);
  16633. cli->set_no_proxy({"example.com"});
  16634. auto res = cli->Get("/");
  16635. ASSERT_TRUE(res);
  16636. EXPECT_EQ(0, s.proxy_hits());
  16637. EXPECT_EQ(1, s.target_hits());
  16638. }
  16639. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16640. // Regression guard: "evilexample.com" must not be considered a subdomain
  16641. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16642. // check would let traffic bypass the proxy and leak credentials direct
  16643. // to the attacker host.
  16644. ProxyAndTargetServers s;
  16645. auto cli = make_client("evilexample.com", s);
  16646. cli->set_no_proxy({"example.com"});
  16647. auto res = cli->Get("/");
  16648. ASSERT_TRUE(res);
  16649. EXPECT_GE(s.proxy_hits(), 1);
  16650. EXPECT_EQ(0, s.target_hits());
  16651. }
  16652. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16653. ProxyAndTargetServers s;
  16654. auto cli = make_client("example.com.evil.com", s);
  16655. cli->set_no_proxy({"example.com"});
  16656. auto res = cli->Get("/");
  16657. ASSERT_TRUE(res);
  16658. EXPECT_GE(s.proxy_hits(), 1);
  16659. EXPECT_EQ(0, s.target_hits());
  16660. }
  16661. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16662. ProxyAndTargetServers s;
  16663. auto cli = make_client("example.com", s);
  16664. cli->set_no_proxy({".example.com"});
  16665. auto res = cli->Get("/");
  16666. ASSERT_TRUE(res);
  16667. EXPECT_EQ(0, s.proxy_hits());
  16668. EXPECT_EQ(1, s.target_hits());
  16669. }
  16670. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16671. ProxyAndTargetServers s;
  16672. auto cli = make_client("Example.COM", s);
  16673. cli->set_no_proxy({"EXAMPLE.com"});
  16674. auto res = cli->Get("/");
  16675. ASSERT_TRUE(res);
  16676. EXPECT_EQ(0, s.proxy_hits());
  16677. EXPECT_EQ(1, s.target_hits());
  16678. }
  16679. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16680. ProxyAndTargetServers s;
  16681. auto cli = make_client("example.com.", s);
  16682. cli->set_no_proxy({"example.com"});
  16683. auto res = cli->Get("/");
  16684. ASSERT_TRUE(res);
  16685. EXPECT_EQ(0, s.proxy_hits());
  16686. EXPECT_EQ(1, s.target_hits());
  16687. }
  16688. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16689. // Trailing dots must be normalized on BOTH sides — host and entry.
  16690. // An implementation that only strips the host-side trailing dot would
  16691. // fail to match host "example.com" against entry "example.com." because
  16692. // a literal substring search would compare 11 chars against 12.
  16693. ProxyAndTargetServers s;
  16694. auto cli = make_client("example.com", s);
  16695. cli->set_no_proxy({"example.com."});
  16696. auto res = cli->Get("/");
  16697. ASSERT_TRUE(res);
  16698. EXPECT_EQ(0, s.proxy_hits());
  16699. EXPECT_EQ(1, s.target_hits());
  16700. }
  16701. TEST(NoProxyTest, WildcardBypassesEverything) {
  16702. ProxyAndTargetServers s;
  16703. auto cli = make_client("anything.invalid.test", s);
  16704. cli->set_no_proxy({"*"});
  16705. auto res = cli->Get("/");
  16706. ASSERT_TRUE(res);
  16707. EXPECT_EQ(0, s.proxy_hits());
  16708. EXPECT_EQ(1, s.target_hits());
  16709. }
  16710. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16711. ProxyAndTargetServers s;
  16712. Client cli("127.0.0.1", s.target_port());
  16713. cli.set_proxy("127.0.0.1", s.proxy_port());
  16714. cli.set_no_proxy({"127.0.0.1"});
  16715. auto res = cli.Get("/");
  16716. ASSERT_TRUE(res);
  16717. EXPECT_EQ(0, s.proxy_hits());
  16718. EXPECT_EQ(1, s.target_hits());
  16719. }
  16720. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16721. ProxyAndTargetServers s;
  16722. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16723. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16724. cli.set_proxy("127.0.0.1", s.proxy_port());
  16725. cli.set_no_proxy({"::1"});
  16726. auto res = cli.Get("/");
  16727. ASSERT_TRUE(res);
  16728. EXPECT_EQ(0, s.proxy_hits());
  16729. EXPECT_EQ(1, s.target_hits());
  16730. }
  16731. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16732. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16733. // must still be recognized as IPv6 for CIDR matching. Implementations
  16734. // that detect IPv6 only when the host begins with '[' would parse the
  16735. // host as a hostname and miss the match.
  16736. ProxyAndTargetServers s;
  16737. Client cli("fe80::1", s.target_port());
  16738. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16739. cli.set_proxy("127.0.0.1", s.proxy_port());
  16740. cli.set_no_proxy({"fe80::/10"});
  16741. auto res = cli.Get("/");
  16742. ASSERT_TRUE(res);
  16743. EXPECT_EQ(0, s.proxy_hits());
  16744. EXPECT_EQ(1, s.target_hits());
  16745. }
  16746. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16747. ProxyAndTargetServers s;
  16748. Client cli("::1", s.target_port());
  16749. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16750. cli.set_proxy("127.0.0.1", s.proxy_port());
  16751. cli.set_no_proxy({"[::1]"});
  16752. auto res = cli.Get("/");
  16753. ASSERT_TRUE(res);
  16754. EXPECT_EQ(0, s.proxy_hits());
  16755. EXPECT_EQ(1, s.target_hits());
  16756. }
  16757. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16758. ProxyAndTargetServers s;
  16759. Client cli("fe80::1", s.target_port());
  16760. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16761. cli.set_proxy("127.0.0.1", s.proxy_port());
  16762. cli.set_no_proxy({"[fe80::]/10"});
  16763. auto res = cli.Get("/");
  16764. ASSERT_TRUE(res);
  16765. EXPECT_EQ(0, s.proxy_hits());
  16766. EXPECT_EQ(1, s.target_hits());
  16767. }
  16768. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16769. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16770. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16771. // tricks via address-family conversion.
  16772. ProxyAndTargetServers s;
  16773. Client cli("::ffff:127.0.0.1", s.target_port());
  16774. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16775. cli.set_proxy("127.0.0.1", s.proxy_port());
  16776. cli.set_no_proxy({"127.0.0.1"});
  16777. auto res = cli.Get("/");
  16778. ASSERT_TRUE(res);
  16779. EXPECT_GE(s.proxy_hits(), 1);
  16780. EXPECT_EQ(0, s.target_hits());
  16781. }
  16782. TEST(NoProxyTest, IPv4CidrMatch) {
  16783. ProxyAndTargetServers s;
  16784. Client cli("127.0.0.1", s.target_port());
  16785. cli.set_proxy("127.0.0.1", s.proxy_port());
  16786. cli.set_no_proxy({"127.0.0.0/8"});
  16787. auto res = cli.Get("/");
  16788. ASSERT_TRUE(res);
  16789. EXPECT_EQ(0, s.proxy_hits());
  16790. EXPECT_EQ(1, s.target_hits());
  16791. }
  16792. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16793. ProxyAndTargetServers s;
  16794. Client cli("127.0.0.1", s.target_port());
  16795. cli.set_proxy("127.0.0.1", s.proxy_port());
  16796. cli.set_no_proxy({"10.0.0.0/8"});
  16797. auto res = cli.Get("/");
  16798. ASSERT_TRUE(res);
  16799. EXPECT_GE(s.proxy_hits(), 1);
  16800. EXPECT_EQ(0, s.target_hits());
  16801. }
  16802. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16803. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16804. // IPv4 target matches.
  16805. ProxyAndTargetServers s;
  16806. Client cli("127.0.0.1", s.target_port());
  16807. cli.set_proxy("127.0.0.1", s.proxy_port());
  16808. cli.set_no_proxy({"0.0.0.0/0"});
  16809. auto res = cli.Get("/");
  16810. ASSERT_TRUE(res);
  16811. EXPECT_EQ(0, s.proxy_hits());
  16812. EXPECT_EQ(1, s.target_hits());
  16813. }
  16814. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16815. ProxyAndTargetServers s;
  16816. Client cli("127.0.0.1", s.target_port());
  16817. cli.set_proxy("127.0.0.1", s.proxy_port());
  16818. cli.set_no_proxy({"127.0.0.1"});
  16819. auto res = cli.Get("/");
  16820. ASSERT_TRUE(res);
  16821. EXPECT_EQ(0, s.proxy_hits());
  16822. EXPECT_EQ(1, s.target_hits());
  16823. }
  16824. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16825. ProxyAndTargetServers s;
  16826. Client cli("127.0.0.1", s.target_port());
  16827. cli.set_proxy("127.0.0.1", s.proxy_port());
  16828. cli.set_no_proxy({"127.0.0.0/33"});
  16829. auto res = cli.Get("/");
  16830. ASSERT_TRUE(res);
  16831. EXPECT_GE(s.proxy_hits(), 1);
  16832. EXPECT_EQ(0, s.target_hits());
  16833. }
  16834. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16835. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16836. ProxyAndTargetServers s;
  16837. Client cli("127.0.0.1", s.target_port());
  16838. cli.set_proxy("127.0.0.1", s.proxy_port());
  16839. cli.set_no_proxy({"127.0.0.1/"});
  16840. auto res = cli.Get("/");
  16841. ASSERT_TRUE(res);
  16842. EXPECT_GE(s.proxy_hits(), 1);
  16843. EXPECT_EQ(0, s.target_hits());
  16844. }
  16845. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16846. ProxyAndTargetServers s;
  16847. auto cli = make_client("internal.corp", s);
  16848. cli->set_proxy_basic_auth("u", "p");
  16849. cli->set_no_proxy({"internal.corp"});
  16850. auto res = cli->Get("/");
  16851. ASSERT_TRUE(res);
  16852. EXPECT_EQ(1, s.target_hits());
  16853. EXPECT_EQ(0, s.proxy_hits());
  16854. EXPECT_FALSE(s.last_had_proxy_authz())
  16855. << "Proxy-Authorization must not be sent direct to the target";
  16856. }
  16857. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16858. ProxyAndTargetServers s;
  16859. auto cli = make_client("public.example", s);
  16860. cli->set_proxy_basic_auth("u", "p");
  16861. cli->set_no_proxy({"internal.corp"}); // does not match
  16862. auto res = cli->Get("/");
  16863. ASSERT_TRUE(res);
  16864. EXPECT_GE(s.proxy_hits(), 1);
  16865. EXPECT_TRUE(s.last_had_proxy_authz());
  16866. }
  16867. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16868. ProxyAndTargetServers s;
  16869. auto cli = make_client("anything.test", s);
  16870. auto res = cli->Get("/");
  16871. ASSERT_TRUE(res);
  16872. EXPECT_GE(s.proxy_hits(), 1);
  16873. EXPECT_EQ(0, s.target_hits());
  16874. }
  16875. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16876. ProxyAndTargetServers s;
  16877. auto cli = make_client("example.com", s);
  16878. cli->set_no_proxy({"example.com:8080"});
  16879. auto res = cli->Get("/");
  16880. ASSERT_TRUE(res);
  16881. EXPECT_GE(s.proxy_hits(), 1);
  16882. EXPECT_EQ(0, s.target_hits());
  16883. }
  16884. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16885. ProxyAndTargetServers s;
  16886. auto cli = make_client("anything.test", s);
  16887. cli->set_no_proxy({"", " ", "\t"});
  16888. auto res = cli->Get("/");
  16889. ASSERT_TRUE(res);
  16890. EXPECT_GE(s.proxy_hits(), 1);
  16891. EXPECT_EQ(0, s.target_hits());
  16892. }
  16893. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16894. // An entry with leading/trailing whitespace must still match — env-style
  16895. // values are commonly pasted with stray spaces and an implementation
  16896. // that feeds the raw token directly to inet_pton would fail to match
  16897. // valid CIDRs because of the spaces.
  16898. ProxyAndTargetServers s;
  16899. Client cli("127.0.0.1", s.target_port());
  16900. cli.set_proxy("127.0.0.1", s.proxy_port());
  16901. cli.set_no_proxy({" 127.0.0.0/8 "});
  16902. auto res = cli.Get("/");
  16903. ASSERT_TRUE(res);
  16904. EXPECT_EQ(0, s.proxy_hits());
  16905. EXPECT_EQ(1, s.target_hits());
  16906. }
  16907. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16908. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16909. // go direct and must NOT carry Proxy-Authorization.
  16910. std::atomic<int> proxy_hits{0};
  16911. std::atomic<int> target_hits{0};
  16912. std::atomic<bool> target_saw_authz{false};
  16913. no_proxy_test::ScopedServer proxy_mock, target;
  16914. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16915. proxy_hits++;
  16916. res.status = 302;
  16917. res.set_header("Location", "http://127.0.0.1:" +
  16918. std::to_string(target.port()) + "/landed");
  16919. });
  16920. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16921. target_hits++;
  16922. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16923. res.set_content("direct", "text/plain");
  16924. });
  16925. proxy_mock.listen();
  16926. target.listen();
  16927. Client cli("public.example", target.port());
  16928. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16929. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16930. cli.set_proxy_basic_auth("u", "p");
  16931. cli.set_no_proxy({"127.0.0.1"});
  16932. cli.set_follow_location(true);
  16933. auto res = cli.Get("/redir");
  16934. ASSERT_TRUE(res);
  16935. EXPECT_GE(proxy_hits.load(), 1);
  16936. EXPECT_GE(target_hits.load(), 1);
  16937. EXPECT_FALSE(target_saw_authz.load());
  16938. }
  16939. #ifdef CPPHTTPLIB_SSL_ENABLED
  16940. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16941. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16942. // proxy creds would be sent to the (possibly hostile) origin.
  16943. std::atomic<int> target_hits{0};
  16944. std::atomic<bool> target_saw_proxy_authz{false};
  16945. no_proxy_test::ScopedServer target;
  16946. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16947. target_hits++;
  16948. if (req.has_header("Proxy-Authorization")) {
  16949. target_saw_proxy_authz = true;
  16950. }
  16951. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16952. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16953. "nonce=\"abc\", algorithm=MD5");
  16954. });
  16955. target.listen();
  16956. // The proxy address is set to the target's port: the bypass MUST kick in;
  16957. // if it doesn't, the test still routes "via proxy" to the same server and
  16958. // the Proxy-Authorization assertion below catches the leak.
  16959. Client cli("evil.example", target.port());
  16960. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16961. cli.set_proxy("127.0.0.1", target.port());
  16962. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16963. cli.set_no_proxy({"evil.example"});
  16964. auto res = cli.Get("/x");
  16965. ASSERT_TRUE(res);
  16966. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16967. EXPECT_EQ(1, target_hits.load());
  16968. EXPECT_FALSE(target_saw_proxy_authz.load());
  16969. }
  16970. #endif
  16971. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16972. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16973. std::atomic<int> proxy_hits{0};
  16974. std::atomic<int> bypass_hits{0};
  16975. std::atomic<bool> proxy_saw_c_url{false};
  16976. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16977. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16978. proxy_hits++;
  16979. if (req.path.find("/start") != std::string::npos) {
  16980. res.status = 302;
  16981. res.set_header("Location", "http://127.0.0.1:" +
  16982. std::to_string(bypass_server.port()) +
  16983. "/middle");
  16984. return;
  16985. }
  16986. if (req.path.find("/end") != std::string::npos) {
  16987. proxy_saw_c_url = true;
  16988. res.set_content("c-via-proxy", "text/plain");
  16989. return;
  16990. }
  16991. res.set_content("unexpected", "text/plain");
  16992. });
  16993. // public.example's "advertised" port is arbitrary (the request never lands
  16994. // there — it goes through the proxy), but use a dynamic value to stay
  16995. // friendly with sharded parallel runs.
  16996. int public_port = bypass_server.port();
  16997. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16998. bypass_hits++;
  16999. res.status = 302;
  17000. res.set_header("Location", "http://public.example:" +
  17001. std::to_string(public_port) + "/end");
  17002. });
  17003. proxy_mock.listen();
  17004. bypass_server.listen();
  17005. Client cli("public.example", public_port);
  17006. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17007. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17008. cli.set_no_proxy({"127.0.0.1"});
  17009. cli.set_follow_location(true);
  17010. auto res = cli.Get("/start");
  17011. ASSERT_TRUE(res);
  17012. EXPECT_EQ(StatusCode::OK_200, res->status);
  17013. EXPECT_EQ("c-via-proxy", res->body);
  17014. EXPECT_GE(proxy_hits.load(), 2);
  17015. EXPECT_GE(bypass_hits.load(), 1);
  17016. EXPECT_TRUE(proxy_saw_c_url.load());
  17017. }
  17018. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17019. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17020. // request reconnects to the correct endpoint.
  17021. std::atomic<int> proxy_hits{0};
  17022. std::atomic<int> target_hits{0};
  17023. no_proxy_test::ScopedServer proxy_mock, target;
  17024. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17025. proxy_hits++;
  17026. res.set_content("via-proxy", "text/plain");
  17027. });
  17028. target.svr().Get(".*", [&](const Request &, Response &res) {
  17029. target_hits++;
  17030. res.set_content("direct", "text/plain");
  17031. });
  17032. proxy_mock.listen();
  17033. target.listen();
  17034. Client cli("public.example", target.port());
  17035. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17036. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17037. cli.set_keep_alive(true);
  17038. auto res1 = cli.Get("/a");
  17039. ASSERT_TRUE(res1);
  17040. EXPECT_EQ("via-proxy", res1->body);
  17041. EXPECT_EQ(1, proxy_hits.load());
  17042. EXPECT_EQ(0, target_hits.load());
  17043. cli.set_no_proxy({"public.example"});
  17044. auto res2 = cli.Get("/b");
  17045. ASSERT_TRUE(res2);
  17046. EXPECT_EQ("direct", res2->body);
  17047. EXPECT_EQ(1, proxy_hits.load());
  17048. EXPECT_EQ(1, target_hits.load());
  17049. }
  17050. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17051. namespace proxy_tunnel_test {
  17052. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17053. class ScopedSSLServer {
  17054. public:
  17055. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17056. port_ = svr_.bind_to_any_port("127.0.0.1");
  17057. }
  17058. ~ScopedSSLServer() {
  17059. svr_.stop();
  17060. if (th_.joinable()) { th_.join(); }
  17061. }
  17062. SSLServer &svr() { return svr_; }
  17063. int port() const { return port_; }
  17064. void listen() {
  17065. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17066. svr_.wait_until_ready();
  17067. }
  17068. private:
  17069. SSLServer svr_;
  17070. std::thread th_;
  17071. int port_ = 0;
  17072. };
  17073. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17074. class ScopedConnectProxy {
  17075. public:
  17076. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17077. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17078. if (listen_fd_ < 0) { return; }
  17079. int yes = 1;
  17080. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17081. sockaddr_in a{};
  17082. a.sin_family = AF_INET;
  17083. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17084. a.sin_port = 0;
  17085. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17086. return;
  17087. }
  17088. socklen_t alen = sizeof(a);
  17089. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17090. 0) {
  17091. return;
  17092. }
  17093. port_ = ntohs(a.sin_port);
  17094. if (::listen(listen_fd_, 1) != 0) { return; }
  17095. th_ = std::thread([this] { run(); });
  17096. }
  17097. ~ScopedConnectProxy() {
  17098. stop_ = true;
  17099. if (listen_fd_ >= 0) {
  17100. ::shutdown(listen_fd_, SHUT_RDWR);
  17101. ::close(listen_fd_);
  17102. }
  17103. if (th_.joinable()) { th_.join(); }
  17104. }
  17105. int port() const { return port_; }
  17106. int connect_hits() const { return connect_hits_.load(); }
  17107. private:
  17108. void run() {
  17109. while (!stop_.load()) {
  17110. fd_set rfds;
  17111. FD_ZERO(&rfds);
  17112. FD_SET(listen_fd_, &rfds);
  17113. timeval tv{0, 100 * 1000};
  17114. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17115. if (sel <= 0) { continue; }
  17116. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17117. if (client_fd < 0) { continue; }
  17118. std::string req;
  17119. char buf[2048];
  17120. while (req.find("\r\n\r\n") == std::string::npos) {
  17121. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17122. if (n <= 0) { break; }
  17123. req.append(buf, static_cast<size_t>(n));
  17124. }
  17125. if (req.compare(0, 7, "CONNECT") != 0) {
  17126. ::close(client_fd);
  17127. continue;
  17128. }
  17129. connect_hits_++;
  17130. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17131. ::send(client_fd, ok, std::strlen(ok), 0);
  17132. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17133. sockaddr_in o{};
  17134. o.sin_family = AF_INET;
  17135. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17136. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17137. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17138. 0) {
  17139. ::close(client_fd);
  17140. ::close(origin_fd);
  17141. continue;
  17142. }
  17143. auto forward = [](int from, int to) {
  17144. char b[8192];
  17145. for (;;) {
  17146. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17147. if (n <= 0) { break; }
  17148. ssize_t off = 0;
  17149. while (off < n) {
  17150. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17151. if (s <= 0) {
  17152. off = n;
  17153. break;
  17154. }
  17155. off += s;
  17156. }
  17157. }
  17158. ::shutdown(to, SHUT_WR);
  17159. };
  17160. std::thread t1([&] { forward(client_fd, origin_fd); });
  17161. std::thread t2([&] { forward(origin_fd, client_fd); });
  17162. t1.join();
  17163. t2.join();
  17164. ::close(client_fd);
  17165. ::close(origin_fd);
  17166. }
  17167. }
  17168. int forward_port_ = -1;
  17169. int listen_fd_ = -1;
  17170. int port_ = 0;
  17171. std::thread th_;
  17172. std::atomic<bool> stop_{false};
  17173. std::atomic<int> connect_hits_{0};
  17174. };
  17175. } // namespace proxy_tunnel_test
  17176. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17177. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17178. // retry; otherwise proxy creds would be sent to the origin.
  17179. std::atomic<int> origin_hits{0};
  17180. std::atomic<bool> origin_saw_proxy_authz{false};
  17181. proxy_tunnel_test::ScopedSSLServer origin;
  17182. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17183. origin_hits++;
  17184. if (req.has_header("Proxy-Authorization")) {
  17185. origin_saw_proxy_authz = true;
  17186. }
  17187. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17188. res.set_header("Proxy-Authenticate",
  17189. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17190. "algorithm=MD5");
  17191. });
  17192. origin.listen();
  17193. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17194. ASSERT_NE(0, proxy.port());
  17195. SSLClient cli(HOST, origin.port());
  17196. cli.enable_server_certificate_verification(false);
  17197. cli.set_proxy(HOST, proxy.port());
  17198. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17199. auto res = cli.Get("/x");
  17200. ASSERT_TRUE(res);
  17201. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17202. EXPECT_EQ(1, origin_hits.load());
  17203. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17204. EXPECT_EQ(1, proxy.connect_hits());
  17205. }
  17206. #endif