test.cc 592 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  666. Server svr;
  667. svr.Get("/", [](const Request & /*req*/, Response &res) {
  668. res.set_content("ok", "text/plain");
  669. });
  670. std::atomic<int> start_count{0};
  671. std::atomic<bool> running_when_called{false};
  672. svr.set_start_handler([&]() {
  673. running_when_called = svr.is_running();
  674. start_count++;
  675. });
  676. auto port = svr.bind_to_any_port(HOST);
  677. std::thread t([&]() { svr.listen_after_bind(); });
  678. auto se = detail::scope_exit([&] {
  679. svr.stop();
  680. t.join();
  681. ASSERT_FALSE(svr.is_running());
  682. });
  683. svr.wait_until_ready();
  684. // A successful request proves the accept loop is running, which the start
  685. // handler precedes; so by now the handler must have run exactly once.
  686. Client cli(HOST, port);
  687. cli.set_connection_timeout(std::chrono::seconds(5));
  688. auto res = cli.Get("/");
  689. ASSERT_TRUE(res);
  690. EXPECT_EQ(StatusCode::OK_200, res->status);
  691. EXPECT_EQ(1, start_count.load());
  692. EXPECT_TRUE(running_when_called.load());
  693. }
  694. TEST(DivideTest, DivideStringTests) {
  695. auto divide = [](const std::string &str, char d) {
  696. std::string lhs;
  697. std::string rhs;
  698. detail::divide(str, d,
  699. [&](const char *lhs_data, std::size_t lhs_size,
  700. const char *rhs_data, std::size_t rhs_size) {
  701. lhs.assign(lhs_data, lhs_size);
  702. rhs.assign(rhs_data, rhs_size);
  703. });
  704. return std::make_pair(std::move(lhs), std::move(rhs));
  705. };
  706. {
  707. const auto res = divide("", '=');
  708. EXPECT_EQ(res.first, "");
  709. EXPECT_EQ(res.second, "");
  710. }
  711. {
  712. const auto res = divide("=", '=');
  713. EXPECT_EQ(res.first, "");
  714. EXPECT_EQ(res.second, "");
  715. }
  716. {
  717. const auto res = divide(" ", '=');
  718. EXPECT_EQ(res.first, " ");
  719. EXPECT_EQ(res.second, "");
  720. }
  721. {
  722. const auto res = divide("a", '=');
  723. EXPECT_EQ(res.first, "a");
  724. EXPECT_EQ(res.second, "");
  725. }
  726. {
  727. const auto res = divide("a=", '=');
  728. EXPECT_EQ(res.first, "a");
  729. EXPECT_EQ(res.second, "");
  730. }
  731. {
  732. const auto res = divide("=b", '=');
  733. EXPECT_EQ(res.first, "");
  734. EXPECT_EQ(res.second, "b");
  735. }
  736. {
  737. const auto res = divide("a=b", '=');
  738. EXPECT_EQ(res.first, "a");
  739. EXPECT_EQ(res.second, "b");
  740. }
  741. {
  742. const auto res = divide("a=b=", '=');
  743. EXPECT_EQ(res.first, "a");
  744. EXPECT_EQ(res.second, "b=");
  745. }
  746. {
  747. const auto res = divide("a=b=c", '=');
  748. EXPECT_EQ(res.first, "a");
  749. EXPECT_EQ(res.second, "b=c");
  750. }
  751. }
  752. TEST(SplitTest, ParseQueryString) {
  753. string s = "key1=val1&key2=val2&key3=val3";
  754. Params dic;
  755. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  756. [&](const char *b, const char *e) {
  757. string key, val;
  758. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  759. if (key.empty()) {
  760. key.assign(b2, e2);
  761. } else {
  762. val.assign(b2, e2);
  763. }
  764. });
  765. dic.emplace(key, val);
  766. });
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. TEST(SplitTest, ParseInvalidQueryTests) {
  772. {
  773. string s = " ";
  774. Params dict;
  775. detail::parse_query_text(s, dict);
  776. EXPECT_TRUE(dict.empty());
  777. }
  778. {
  779. string s = " = =";
  780. Params dict;
  781. detail::parse_query_text(s, dict);
  782. EXPECT_TRUE(dict.empty());
  783. }
  784. }
  785. TEST(ParseQueryTest, ParseQueryString) {
  786. {
  787. std::string s = "key1=val1&key2=val2&key3=val3";
  788. Params dic;
  789. detail::parse_query_text(s, dic);
  790. EXPECT_EQ("val1", dic.find("key1")->second);
  791. EXPECT_EQ("val2", dic.find("key2")->second);
  792. EXPECT_EQ("val3", dic.find("key3")->second);
  793. }
  794. {
  795. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  796. Params dic;
  797. detail::parse_query_text(s, dic);
  798. EXPECT_EQ("", dic.find("key1")->second);
  799. EXPECT_EQ("val1", dic.find("key2")->second);
  800. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  801. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  802. }
  803. }
  804. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  805. Params dic;
  806. EXPECT_EQ(detail::params_to_query_str(dic), "");
  807. dic.emplace("key1", "val1");
  808. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  809. dic.emplace("key2", "val2");
  810. dic.emplace("key3", "val3");
  811. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  812. }
  813. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  814. string content_type = "multipart/form-data; boundary=something";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "something");
  819. }
  820. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  821. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  828. string content_type =
  829. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  830. string boundary;
  831. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  834. }
  835. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  836. string content_type =
  837. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  838. string boundary;
  839. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  840. EXPECT_TRUE(ret);
  841. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  842. }
  843. TEST(GetHeaderValueTest, DefaultValue) {
  844. Headers headers = {{"Dummy", "Dummy"}};
  845. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  846. EXPECT_STREQ("text/plain", val);
  847. }
  848. TEST(GetHeaderValueTest, DefaultValueInt) {
  849. Headers headers = {{"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularValue) {
  854. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  855. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  856. EXPECT_STREQ("text/html", val);
  857. }
  858. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  859. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  860. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  861. EXPECT_STREQ("text/html", val);
  862. }
  863. TEST(GetHeaderValueTest, SetContent) {
  864. Response res;
  865. res.set_content("html", "text/html");
  866. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  867. res.set_content("text", "text/plain");
  868. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  869. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  870. }
  871. TEST(GetHeaderValueTest, RegularValueInt) {
  872. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  873. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  874. EXPECT_EQ(100ull, val);
  875. }
  876. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  877. Headers headers = {{"Content-Length", "x"}};
  878. auto is_invalid_value = false;
  879. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  880. is_invalid_value);
  881. EXPECT_EQ(0ull, val);
  882. EXPECT_TRUE(is_invalid_value);
  883. }
  884. TEST(GetHeaderValueTest, Range) {
  885. {
  886. Headers headers = {make_range_header({{1, -1}})};
  887. auto val = detail::get_header_value(headers, "Range", 0, 0);
  888. EXPECT_STREQ("bytes=1-", val);
  889. }
  890. {
  891. Headers headers = {make_range_header({{-1, 1}})};
  892. auto val = detail::get_header_value(headers, "Range", 0, 0);
  893. EXPECT_STREQ("bytes=-1", val);
  894. }
  895. {
  896. Headers headers = {make_range_header({{1, 10}})};
  897. auto val = detail::get_header_value(headers, "Range", 0, 0);
  898. EXPECT_STREQ("bytes=1-10", val);
  899. }
  900. {
  901. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  902. auto val = detail::get_header_value(headers, "Range", 0, 0);
  903. EXPECT_STREQ("bytes=1-10, 100-", val);
  904. }
  905. {
  906. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  907. auto val = detail::get_header_value(headers, "Range", 0, 0);
  908. EXPECT_STREQ("bytes=1-10, 100-200", val);
  909. }
  910. {
  911. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  912. auto val = detail::get_header_value(headers, "Range", 0, 0);
  913. EXPECT_STREQ("bytes=0-0, -1", val);
  914. }
  915. }
  916. TEST(ParseHeaderValueTest, Range) {
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(1u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(-1, ranges[0].second);
  924. }
  925. {
  926. Ranges ranges;
  927. auto ret = detail::parse_range_header("bytes=-1", ranges);
  928. EXPECT_TRUE(ret);
  929. EXPECT_EQ(1u, ranges.size());
  930. EXPECT_EQ(-1, ranges[0].first);
  931. EXPECT_EQ(1u, ranges[0].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  936. EXPECT_TRUE(ret);
  937. EXPECT_EQ(1u, ranges.size());
  938. EXPECT_EQ(1u, ranges[0].first);
  939. EXPECT_EQ(10u, ranges[0].second);
  940. }
  941. {
  942. Ranges ranges;
  943. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  944. EXPECT_FALSE(ret);
  945. }
  946. {
  947. Ranges ranges;
  948. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  949. EXPECT_TRUE(ret);
  950. EXPECT_EQ(2u, ranges.size());
  951. EXPECT_EQ(1u, ranges[0].first);
  952. EXPECT_EQ(10u, ranges[0].second);
  953. EXPECT_EQ(100u, ranges[1].first);
  954. EXPECT_EQ(-1, ranges[1].second);
  955. }
  956. {
  957. Ranges ranges;
  958. auto ret =
  959. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  960. EXPECT_TRUE(ret);
  961. EXPECT_EQ(3u, ranges.size());
  962. EXPECT_EQ(1u, ranges[0].first);
  963. EXPECT_EQ(10u, ranges[0].second);
  964. EXPECT_EQ(100u, ranges[1].first);
  965. EXPECT_EQ(200u, ranges[1].second);
  966. EXPECT_EQ(300u, ranges[2].first);
  967. EXPECT_EQ(400u, ranges[2].second);
  968. }
  969. {
  970. Ranges ranges;
  971. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  972. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  973. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  974. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  975. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  976. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  977. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  978. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  984. EXPECT_TRUE(ranges.empty());
  985. }
  986. }
  987. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  988. Request req;
  989. req.set_header("Accept-Encoding", "gzip");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  995. #else
  996. EXPECT_TRUE(ret == detail::EncodingType::None);
  997. #endif
  998. }
  999. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1000. Request req;
  1001. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1002. Response res;
  1003. res.set_header("Content-Type", "text/plain");
  1004. auto ret = detail::encoding_type(req, res);
  1005. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1006. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1007. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1008. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1009. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1010. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1011. #else
  1012. EXPECT_TRUE(ret == detail::EncodingType::None);
  1013. #endif
  1014. }
  1015. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1016. Request req;
  1017. req.set_header("Accept-Encoding",
  1018. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1019. Response res;
  1020. res.set_header("Content-Type", "text/plain");
  1021. auto ret = detail::encoding_type(req, res);
  1022. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1023. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1024. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1025. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1026. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1028. #else
  1029. EXPECT_TRUE(ret == detail::EncodingType::None);
  1030. #endif
  1031. }
  1032. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1033. // All supported encodings rejected with q=0 should return None
  1034. Request req;
  1035. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1036. Response res;
  1037. res.set_header("Content-Type", "text/plain");
  1038. auto ret = detail::encoding_type(req, res);
  1039. EXPECT_TRUE(ret == detail::EncodingType::None);
  1040. }
  1041. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1042. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1043. Request req;
  1044. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1045. Response res;
  1046. res.set_header("Content-Type", "text/plain");
  1047. auto ret = detail::encoding_type(req, res);
  1048. EXPECT_TRUE(ret == detail::EncodingType::None);
  1049. }
  1050. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1051. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1052. Request req;
  1053. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1054. Response res;
  1055. res.set_header("Content-Type", "text/plain");
  1056. auto ret = detail::encoding_type(req, res);
  1057. EXPECT_TRUE(ret == detail::EncodingType::None);
  1058. }
  1059. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1060. // RFC 7231: Accept-Encoding values are case-insensitive
  1061. Request req;
  1062. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1063. Response res;
  1064. res.set_header("Content-Type", "text/plain");
  1065. auto ret = detail::encoding_type(req, res);
  1066. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1067. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1068. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1069. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1070. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1071. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1072. #else
  1073. EXPECT_TRUE(ret == detail::EncodingType::None);
  1074. #endif
  1075. }
  1076. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1077. // q value should determine priority, not hardcoded order
  1078. Request req;
  1079. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1080. Response res;
  1081. res.set_header("Content-Type", "text/plain");
  1082. auto ret = detail::encoding_type(req, res);
  1083. // gzip has highest q=1.0, so it should be selected even though
  1084. // br and zstd are also supported
  1085. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1086. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1087. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1088. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1089. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1090. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1091. #else
  1092. EXPECT_TRUE(ret == detail::EncodingType::None);
  1093. #endif
  1094. }
  1095. TEST(BufferStreamTest, read) {
  1096. detail::BufferStream strm1;
  1097. Stream &strm = strm1;
  1098. EXPECT_EQ(5, strm.write("hello"));
  1099. char buf[512];
  1100. EXPECT_EQ(2, strm.read(buf, 2));
  1101. EXPECT_EQ('h', buf[0]);
  1102. EXPECT_EQ('e', buf[1]);
  1103. EXPECT_EQ(2, strm.read(buf, 2));
  1104. EXPECT_EQ('l', buf[0]);
  1105. EXPECT_EQ('l', buf[1]);
  1106. EXPECT_EQ(1, strm.read(buf, 1));
  1107. EXPECT_EQ('o', buf[0]);
  1108. EXPECT_EQ(0, strm.read(buf, 1));
  1109. }
  1110. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1111. auto host = "www.httpwatch.com";
  1112. auto ip = hosted_at(host);
  1113. EXPECT_EQ("23.96.13.243", ip);
  1114. std::vector<std::string> addrs;
  1115. hosted_at(host, addrs);
  1116. EXPECT_EQ(1u, addrs.size());
  1117. }
  1118. #if 0 // It depends on each test environment...
  1119. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1120. auto host = "www.youtube.com";
  1121. std::vector<std::string> addrs;
  1122. hosted_at(host, addrs);
  1123. EXPECT_EQ(20u, addrs.size());
  1124. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1125. EXPECT_TRUE(it != addrs.end());
  1126. }
  1127. #endif
  1128. class ChunkedEncodingTest : public ::testing::Test {
  1129. protected:
  1130. ChunkedEncodingTest()
  1131. : cli_(HOST, PORT)
  1132. #ifdef CPPHTTPLIB_SSL_ENABLED
  1133. ,
  1134. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1135. #endif
  1136. {
  1137. cli_.set_connection_timeout(2);
  1138. #ifdef CPPHTTPLIB_SSL_ENABLED
  1139. cli_.enable_server_certificate_verification(false);
  1140. #endif
  1141. }
  1142. virtual void SetUp() {
  1143. read_file("./image.jpg", image_data_);
  1144. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1145. res.set_content("Hello World!", "text/plain");
  1146. });
  1147. svr_.Get(
  1148. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1149. res.set_chunked_content_provider(
  1150. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1151. size_t remaining = image_data_.size() - offset;
  1152. if (remaining == 0) {
  1153. sink.done();
  1154. } else {
  1155. constexpr size_t CHUNK_SIZE = 1024;
  1156. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1157. sink.write(&image_data_[offset], send_size);
  1158. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1159. }
  1160. return true;
  1161. });
  1162. });
  1163. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1164. svr_.wait_until_ready();
  1165. }
  1166. virtual void TearDown() {
  1167. svr_.stop();
  1168. if (!request_threads_.empty()) {
  1169. std::this_thread::sleep_for(std::chrono::seconds(1));
  1170. for (auto &t : request_threads_) {
  1171. t.join();
  1172. }
  1173. }
  1174. t_.join();
  1175. }
  1176. #ifdef CPPHTTPLIB_SSL_ENABLED
  1177. SSLClient cli_;
  1178. SSLServer svr_;
  1179. #else
  1180. Client cli_;
  1181. Server svr_;
  1182. #endif
  1183. thread t_;
  1184. std::vector<thread> request_threads_;
  1185. std::string image_data_;
  1186. };
  1187. TEST_F(ChunkedEncodingTest, NormalGet) {
  1188. auto res = cli_.Get("/chunked");
  1189. ASSERT_TRUE(res);
  1190. std::string out;
  1191. read_file("./image.jpg", out);
  1192. EXPECT_EQ(StatusCode::OK_200, res->status);
  1193. EXPECT_EQ(out, res->body);
  1194. }
  1195. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1196. std::string body;
  1197. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1198. body.append(data, data_length);
  1199. return true;
  1200. });
  1201. ASSERT_TRUE(res);
  1202. std::string out;
  1203. read_file("./image.jpg", out);
  1204. EXPECT_EQ(StatusCode::OK_200, res->status);
  1205. EXPECT_EQ(out, body);
  1206. }
  1207. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1208. std::string body;
  1209. auto res = cli_.Get(
  1210. "/chunked",
  1211. [&](const Response &response) {
  1212. EXPECT_EQ(StatusCode::OK_200, response.status);
  1213. return true;
  1214. },
  1215. [&](const char *data, size_t data_length) {
  1216. body.append(data, data_length);
  1217. return true;
  1218. });
  1219. ASSERT_TRUE(res);
  1220. std::string out;
  1221. read_file("./image.jpg", out);
  1222. EXPECT_EQ(StatusCode::OK_200, res->status);
  1223. EXPECT_EQ(out, body);
  1224. }
  1225. TEST(RangeTest, FromHTTPBin_Online) {
  1226. auto host = "httpbingo.org";
  1227. auto path = std::string{"/range/32"};
  1228. #ifdef CPPHTTPLIB_SSL_ENABLED
  1229. auto port = 443;
  1230. SSLClient cli(host, port);
  1231. #else
  1232. auto port = 80;
  1233. Client cli(host, port);
  1234. #endif
  1235. cli.set_connection_timeout(5);
  1236. {
  1237. auto res = cli.Get(path);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1240. EXPECT_EQ(StatusCode::OK_200, res->status);
  1241. }
  1242. {
  1243. Headers headers = {make_range_header({{1, -1}})};
  1244. auto res = cli.Get(path, headers);
  1245. ASSERT_TRUE(res);
  1246. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1248. }
  1249. {
  1250. Headers headers = {make_range_header({{1, 10}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ("bcdefghijk", res->body);
  1254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1255. }
  1256. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1257. // entire resource, while the original httpbin returned 200. Both are
  1258. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1259. {
  1260. Headers headers = {make_range_header({{0, 31}})};
  1261. auto res = cli.Get(path, headers);
  1262. ASSERT_TRUE(res);
  1263. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1264. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1265. res->status == StatusCode::PartialContent_206);
  1266. }
  1267. {
  1268. Headers headers = {make_range_header({{0, -1}})};
  1269. auto res = cli.Get(path, headers);
  1270. ASSERT_TRUE(res);
  1271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1272. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1273. res->status == StatusCode::PartialContent_206);
  1274. }
  1275. // go-httpbin returns 206 with clamped range for over-range requests,
  1276. // while the original httpbin returned 416. Both behaviors are observed
  1277. // in real servers, so we only verify the request succeeds.
  1278. {
  1279. Headers headers = {make_range_header({{0, 32}})};
  1280. auto res = cli.Get(path, headers);
  1281. ASSERT_TRUE(res);
  1282. }
  1283. }
  1284. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1285. auto host = "unresolvableaddress.local";
  1286. auto path = std::string{"/"};
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. auto port = 443;
  1289. SSLClient cli(host, port);
  1290. #else
  1291. auto port = 80;
  1292. Client cli(host, port);
  1293. #endif
  1294. cli.set_connection_timeout(1);
  1295. {
  1296. auto res = cli.Get(path);
  1297. ASSERT_FALSE(res);
  1298. }
  1299. std::this_thread::sleep_for(std::chrono::seconds(8));
  1300. }
  1301. #if defined(__linux__) && defined(__GLIBC__) && \
  1302. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1303. // Forward declaration: in split builds split.py strips `inline` and moves the
  1304. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1305. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1306. // against the symbol in both header-only and split builds.
  1307. namespace httplib {
  1308. namespace detail {
  1309. int getaddrinfo_with_timeout(const char *node, const char *service,
  1310. const struct addrinfo *hints,
  1311. struct addrinfo **res, time_t timeout_sec);
  1312. } // namespace detail
  1313. } // namespace httplib
  1314. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1315. //
  1316. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1317. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1318. // gai_suspend() call hits the connection timeout the function calls
  1319. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1320. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1321. // still alive and still references the now-destroyed stack frame.
  1322. //
  1323. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1324. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1325. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1326. // and runs them in a container.
  1327. namespace {
  1328. bool should_run_issue_2431_tests() {
  1329. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1330. return v && *v && std::string(v) != "0";
  1331. }
  1332. std::string unique_unresolvable_host(int n) {
  1333. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1334. // glibc still asks the configured nameserver — which is exactly the path
  1335. // we want to exercise. A unique label per call avoids the resolver cache.
  1336. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1337. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1338. std::to_string(n) + ".invalid";
  1339. }
  1340. } // namespace
  1341. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1342. if (!should_run_issue_2431_tests()) {
  1343. GTEST_SKIP()
  1344. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1345. }
  1346. for (int i = 0; i < 8; ++i) {
  1347. struct addrinfo hints;
  1348. memset(&hints, 0, sizeof(hints));
  1349. hints.ai_family = AF_UNSPEC;
  1350. hints.ai_socktype = SOCK_STREAM;
  1351. auto host = unique_unresolvable_host(i);
  1352. struct addrinfo *result = nullptr;
  1353. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1354. &result, /*timeout_sec=*/1);
  1355. if (rc == 0 && result) { freeaddrinfo(result); }
  1356. }
  1357. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1358. // stack region they still believe holds their gaicb.
  1359. std::this_thread::sleep_for(std::chrono::seconds(3));
  1360. }
  1361. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1362. if (!should_run_issue_2431_tests()) {
  1363. GTEST_SKIP()
  1364. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1365. }
  1366. std::atomic<bool> stop{false};
  1367. std::vector<std::thread> threads;
  1368. for (int t = 0; t < 8; ++t) {
  1369. threads.emplace_back([t, &stop] {
  1370. int i = 0;
  1371. while (!stop.load(std::memory_order_relaxed)) {
  1372. struct addrinfo hints;
  1373. memset(&hints, 0, sizeof(hints));
  1374. hints.ai_family = AF_UNSPEC;
  1375. hints.ai_socktype = SOCK_STREAM;
  1376. auto host = unique_unresolvable_host(t * 100000 + i++);
  1377. struct addrinfo *result = nullptr;
  1378. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1379. &result, /*timeout_sec=*/1);
  1380. if (rc == 0 && result) { freeaddrinfo(result); }
  1381. }
  1382. });
  1383. }
  1384. std::this_thread::sleep_for(std::chrono::seconds(8));
  1385. stop.store(true, std::memory_order_relaxed);
  1386. for (auto &th : threads) {
  1387. th.join();
  1388. }
  1389. std::this_thread::sleep_for(std::chrono::seconds(3));
  1390. }
  1391. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1392. if (!should_run_issue_2431_tests()) {
  1393. GTEST_SKIP()
  1394. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1395. }
  1396. std::atomic<bool> stop{false};
  1397. std::vector<std::thread> threads;
  1398. for (int t = 0; t < 8; ++t) {
  1399. threads.emplace_back([t, &stop] {
  1400. int i = 0;
  1401. while (!stop.load(std::memory_order_relaxed)) {
  1402. auto host = unique_unresolvable_host(t * 100000 + i++);
  1403. Client cli(host, 80);
  1404. cli.set_connection_timeout(1, 0);
  1405. cli.set_read_timeout(1, 0);
  1406. cli.set_write_timeout(1, 0);
  1407. (void)cli.Get("/");
  1408. }
  1409. });
  1410. }
  1411. std::this_thread::sleep_for(std::chrono::seconds(8));
  1412. stop.store(true, std::memory_order_relaxed);
  1413. for (auto &th : threads) {
  1414. th.join();
  1415. }
  1416. std::this_thread::sleep_for(std::chrono::seconds(3));
  1417. }
  1418. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1419. TEST(ConnectionErrorTest, InvalidHost) {
  1420. auto host = "-abcde.com";
  1421. #ifdef CPPHTTPLIB_SSL_ENABLED
  1422. auto port = 443;
  1423. SSLClient cli(host, port);
  1424. #else
  1425. auto port = 80;
  1426. Client cli(host, port);
  1427. #endif
  1428. cli.set_connection_timeout(std::chrono::seconds(2));
  1429. auto res = cli.Get("/");
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Connection, res.error());
  1432. }
  1433. TEST(ConnectionErrorTest, InvalidHost2) {
  1434. auto host = "httpcan.org/";
  1435. #ifdef CPPHTTPLIB_SSL_ENABLED
  1436. SSLClient cli(host);
  1437. #else
  1438. Client cli(host);
  1439. #endif
  1440. cli.set_connection_timeout(std::chrono::seconds(2));
  1441. auto res = cli.Get("/");
  1442. ASSERT_TRUE(!res);
  1443. EXPECT_EQ(Error::Connection, res.error());
  1444. }
  1445. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1446. auto host = "httpcan.org/";
  1447. #ifdef CPPHTTPLIB_SSL_ENABLED
  1448. SSLClient cli(host);
  1449. #else
  1450. Client cli(host);
  1451. #endif
  1452. cli.set_connection_timeout(std::chrono::seconds(2));
  1453. auto res = cli.Get("/");
  1454. ASSERT_TRUE(!res);
  1455. stringstream s;
  1456. s << "error code: " << res.error();
  1457. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1458. }
  1459. TEST(ConnectionErrorTest, InvalidPort) {
  1460. auto host = "localhost";
  1461. auto port = 44380;
  1462. #ifdef CPPHTTPLIB_SSL_ENABLED
  1463. SSLClient cli(host, port);
  1464. #else
  1465. Client cli(host, port);
  1466. #endif
  1467. cli.set_connection_timeout(std::chrono::seconds(2));
  1468. auto res = cli.Get("/");
  1469. ASSERT_TRUE(!res);
  1470. EXPECT_TRUE(Error::Connection == res.error() ||
  1471. Error::ConnectionTimeout == res.error());
  1472. }
  1473. TEST(ConnectionErrorTest, Timeout_Online) {
  1474. auto host = "google.com";
  1475. #ifdef CPPHTTPLIB_SSL_ENABLED
  1476. auto port = 44380;
  1477. SSLClient cli(host, port);
  1478. #else
  1479. auto port = 8080;
  1480. Client cli(host, port);
  1481. #endif
  1482. cli.set_connection_timeout(std::chrono::seconds(2));
  1483. // only probe one address type so that the error reason
  1484. // correlates to the timed-out IPv4, not the unsupported
  1485. // IPv6 connection attempt
  1486. cli.set_address_family(AF_INET);
  1487. auto res = cli.Get("/");
  1488. ASSERT_TRUE(!res);
  1489. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1490. }
  1491. TEST(CancelTest, NoCancel_Online) {
  1492. auto host = "httpbingo.org";
  1493. auto path = std::string{"/range/32"};
  1494. #ifdef CPPHTTPLIB_SSL_ENABLED
  1495. auto port = 443;
  1496. SSLClient cli(host, port);
  1497. #else
  1498. auto port = 80;
  1499. Client cli(host, port);
  1500. #endif
  1501. cli.set_connection_timeout(std::chrono::seconds(5));
  1502. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1505. EXPECT_EQ(StatusCode::OK_200, res->status);
  1506. }
  1507. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1508. // Use /bytes with a large payload so that the DownloadProgress callback
  1509. // (which only fires for Content-Length responses) is invoked before the
  1510. // entire body is received, giving cancellation a chance to fire.
  1511. auto host = "httpbingo.org";
  1512. auto path = std::string{"/bytes/524288"};
  1513. #ifdef CPPHTTPLIB_SSL_ENABLED
  1514. auto port = 443;
  1515. SSLClient cli(host, port);
  1516. #else
  1517. auto port = 80;
  1518. Client cli(host, port);
  1519. #endif
  1520. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1521. cli.set_connection_timeout(std::chrono::seconds(5));
  1522. ASSERT_TRUE(!res);
  1523. EXPECT_EQ(Error::Canceled, res.error());
  1524. }
  1525. TEST(CancelTest, WithCancelLargePayload_Online) {
  1526. auto host = "httpbingo.org";
  1527. auto path = std::string{"/bytes/524288"};
  1528. #ifdef CPPHTTPLIB_SSL_ENABLED
  1529. auto port = 443;
  1530. SSLClient cli(host, port);
  1531. #else
  1532. auto port = 80;
  1533. Client cli(host, port);
  1534. #endif
  1535. cli.set_connection_timeout(std::chrono::seconds(5));
  1536. uint32_t count = 0;
  1537. auto res =
  1538. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1539. ASSERT_TRUE(!res);
  1540. EXPECT_EQ(Error::Canceled, res.error());
  1541. }
  1542. TEST(CancelTest, NoCancelPost) {
  1543. Server svr;
  1544. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return true; });
  1559. ASSERT_TRUE(res);
  1560. EXPECT_EQ("Hello World!", res->body);
  1561. EXPECT_EQ(StatusCode::OK_200, res->status);
  1562. }
  1563. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1564. Server svr;
  1565. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content("Hello World!", "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, WithCancelLargePayloadPost) {
  1584. Server svr;
  1585. svr.set_payload_max_length(200 * 1024 * 1024);
  1586. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content(LARGE_DATA, "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_payload_max_length(200 * 1024 * 1024);
  1598. cli.set_connection_timeout(std::chrono::seconds(5));
  1599. auto res =
  1600. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1601. "application/json", [](uint64_t, uint64_t) { return false; });
  1602. ASSERT_TRUE(!res);
  1603. EXPECT_EQ(Error::Canceled, res.error());
  1604. }
  1605. TEST(CancelTest, NoCancelPut) {
  1606. Server svr;
  1607. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return true; });
  1622. ASSERT_TRUE(res);
  1623. EXPECT_EQ("Hello World!", res->body);
  1624. EXPECT_EQ(StatusCode::OK_200, res->status);
  1625. }
  1626. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1627. Server svr;
  1628. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content("Hello World!", "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. TEST(CancelTest, WithCancelLargePayloadPut) {
  1647. Server svr;
  1648. svr.set_payload_max_length(200 * 1024 * 1024);
  1649. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1650. res.set_content(LARGE_DATA, "text/plain");
  1651. });
  1652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1653. auto se = detail::scope_exit([&] {
  1654. svr.stop();
  1655. thread.join();
  1656. ASSERT_FALSE(svr.is_running());
  1657. });
  1658. svr.wait_until_ready();
  1659. Client cli(HOST, PORT);
  1660. cli.set_payload_max_length(200 * 1024 * 1024);
  1661. cli.set_connection_timeout(std::chrono::seconds(5));
  1662. auto res =
  1663. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1664. "application/json", [](uint64_t, uint64_t) { return false; });
  1665. ASSERT_TRUE(!res);
  1666. EXPECT_EQ(Error::Canceled, res.error());
  1667. }
  1668. TEST(CancelTest, NoCancelPatch) {
  1669. Server svr;
  1670. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1671. res.set_content("Hello World!", "text/plain");
  1672. });
  1673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1674. auto se = detail::scope_exit([&] {
  1675. svr.stop();
  1676. thread.join();
  1677. ASSERT_FALSE(svr.is_running());
  1678. });
  1679. svr.wait_until_ready();
  1680. Client cli(HOST, PORT);
  1681. cli.set_connection_timeout(std::chrono::seconds(5));
  1682. auto res =
  1683. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1684. "application/json", [](uint64_t, uint64_t) { return true; });
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ("Hello World!", res->body);
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1690. Server svr;
  1691. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1692. res.set_content("Hello World!", "text/plain");
  1693. });
  1694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1695. auto se = detail::scope_exit([&] {
  1696. svr.stop();
  1697. thread.join();
  1698. ASSERT_FALSE(svr.is_running());
  1699. });
  1700. svr.wait_until_ready();
  1701. Client cli(HOST, PORT);
  1702. cli.set_connection_timeout(std::chrono::seconds(5));
  1703. auto res =
  1704. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1705. "application/json", [](uint64_t, uint64_t) { return false; });
  1706. ASSERT_TRUE(!res);
  1707. EXPECT_EQ(Error::Canceled, res.error());
  1708. }
  1709. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1710. Server svr;
  1711. svr.set_payload_max_length(200 * 1024 * 1024);
  1712. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1713. res.set_content(LARGE_DATA, "text/plain");
  1714. });
  1715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1716. auto se = detail::scope_exit([&] {
  1717. svr.stop();
  1718. thread.join();
  1719. ASSERT_FALSE(svr.is_running());
  1720. });
  1721. svr.wait_until_ready();
  1722. Client cli(HOST, PORT);
  1723. cli.set_payload_max_length(200 * 1024 * 1024);
  1724. cli.set_connection_timeout(std::chrono::seconds(5));
  1725. auto res =
  1726. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1727. "application/json", [](uint64_t, uint64_t) { return false; });
  1728. ASSERT_TRUE(!res);
  1729. EXPECT_EQ(Error::Canceled, res.error());
  1730. }
  1731. TEST(CancelTest, NoCancelDelete) {
  1732. Server svr;
  1733. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1734. res.set_content("Hello World!", "text/plain");
  1735. });
  1736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1737. auto se = detail::scope_exit([&] {
  1738. svr.stop();
  1739. thread.join();
  1740. ASSERT_FALSE(svr.is_running());
  1741. });
  1742. svr.wait_until_ready();
  1743. Client cli(HOST, PORT);
  1744. cli.set_connection_timeout(std::chrono::seconds(5));
  1745. auto res =
  1746. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1747. "application/json", [](uint64_t, uint64_t) { return true; });
  1748. ASSERT_TRUE(res);
  1749. EXPECT_EQ("Hello World!", res->body);
  1750. EXPECT_EQ(StatusCode::OK_200, res->status);
  1751. }
  1752. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1753. Server svr;
  1754. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1755. res.set_content("Hello World!", "text/plain");
  1756. });
  1757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1758. auto se = detail::scope_exit([&] {
  1759. svr.stop();
  1760. thread.join();
  1761. ASSERT_FALSE(svr.is_running());
  1762. });
  1763. svr.wait_until_ready();
  1764. Client cli(HOST, PORT);
  1765. cli.set_connection_timeout(std::chrono::seconds(5));
  1766. auto res =
  1767. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1768. "application/json", [](uint64_t, uint64_t) { return false; });
  1769. ASSERT_TRUE(!res);
  1770. EXPECT_EQ(Error::Canceled, res.error());
  1771. }
  1772. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1773. Server svr;
  1774. svr.set_payload_max_length(200 * 1024 * 1024);
  1775. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content(LARGE_DATA, "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. Client cli(HOST, PORT);
  1786. cli.set_payload_max_length(200 * 1024 * 1024);
  1787. cli.set_connection_timeout(std::chrono::seconds(5));
  1788. auto res =
  1789. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1790. "application/json", [](uint64_t, uint64_t) { return false; });
  1791. ASSERT_TRUE(!res);
  1792. EXPECT_EQ(Error::Canceled, res.error());
  1793. }
  1794. static std::string remove_whitespace(const std::string &input) {
  1795. std::string output;
  1796. output.reserve(input.size());
  1797. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1798. [](unsigned char c) { return !std::isspace(c); });
  1799. return output;
  1800. }
  1801. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1802. auto host = "httpbingo.org";
  1803. auto path = std::string{"/basic-auth/hello/world"};
  1804. #ifdef CPPHTTPLIB_SSL_ENABLED
  1805. auto port = 443;
  1806. SSLClient cli(host, port);
  1807. #else
  1808. auto port = 80;
  1809. Client cli(host, port);
  1810. #endif
  1811. {
  1812. auto res = cli.Get(path);
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1815. }
  1816. {
  1817. auto res =
  1818. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1819. ASSERT_TRUE(res);
  1820. auto body = remove_whitespace(res->body);
  1821. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1822. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. {
  1826. cli.set_basic_auth("hello", "world");
  1827. auto res = cli.Get(path);
  1828. ASSERT_TRUE(res);
  1829. auto body = remove_whitespace(res->body);
  1830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1832. EXPECT_EQ(StatusCode::OK_200, res->status);
  1833. }
  1834. {
  1835. cli.set_basic_auth("hello", "bad");
  1836. auto res = cli.Get(path);
  1837. ASSERT_TRUE(res);
  1838. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1839. }
  1840. {
  1841. cli.set_basic_auth("bad", "world");
  1842. auto res = cli.Get(path);
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1845. }
  1846. }
  1847. #ifdef CPPHTTPLIB_SSL_ENABLED
  1848. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1849. auto host = "httpbingo.org";
  1850. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1851. auto paths = std::vector<std::string>{
  1852. "/digest-auth/auth/hello/world/MD5",
  1853. "/digest-auth/auth/hello/world/SHA-256",
  1854. };
  1855. auto port = 443;
  1856. SSLClient cli(host, port);
  1857. {
  1858. auto res = cli.Get(unauth_path);
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1861. }
  1862. {
  1863. cli.set_digest_auth("hello", "world");
  1864. for (const auto &path : paths) {
  1865. auto res = cli.Get(path.c_str());
  1866. ASSERT_TRUE(res);
  1867. auto body = remove_whitespace(res->body);
  1868. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1869. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. }
  1872. cli.set_digest_auth("hello", "bad");
  1873. for (const auto &path : paths) {
  1874. auto res = cli.Get(path.c_str());
  1875. ASSERT_TRUE(res);
  1876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1877. }
  1878. }
  1879. }
  1880. #endif
  1881. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1882. auto host = "google.com";
  1883. auto another_host = "example.com";
  1884. auto wrong_ip = "0.0.0.0";
  1885. #ifdef CPPHTTPLIB_SSL_ENABLED
  1886. SSLClient cli(host);
  1887. #else
  1888. Client cli(host);
  1889. #endif
  1890. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1891. auto res = cli.Get("/");
  1892. ASSERT_TRUE(res);
  1893. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1894. }
  1895. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1896. auto host = "google.com";
  1897. auto wrong_ip = "0.0.0.0";
  1898. #ifdef CPPHTTPLIB_SSL_ENABLED
  1899. SSLClient cli(host);
  1900. #else
  1901. Client cli(host);
  1902. #endif
  1903. cli.set_hostname_addr_map({{host, wrong_ip}});
  1904. auto res = cli.Get("/");
  1905. ASSERT_TRUE(!res);
  1906. EXPECT_EQ(Error::Connection, res.error());
  1907. }
  1908. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1909. auto host = "httpbingo.org";
  1910. auto path = std::string{"/absolute-redirect/3"};
  1911. #ifdef CPPHTTPLIB_SSL_ENABLED
  1912. SSLClient cli(host);
  1913. #else
  1914. Client cli(host);
  1915. #endif
  1916. cli.set_follow_location(true);
  1917. auto res = cli.Get(path);
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. }
  1921. TEST(RedirectTest, Redirect_Online) {
  1922. auto host = "httpbingo.org";
  1923. auto path = std::string{"/redirect/3"};
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. SSLClient cli(host);
  1926. #else
  1927. Client cli(host);
  1928. #endif
  1929. cli.set_follow_location(true);
  1930. auto res = cli.Get(path);
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. }
  1934. TEST(RelativeRedirectTest, Redirect_Online) {
  1935. auto host = "httpbingo.org";
  1936. auto path = std::string{"/relative-redirect/3"};
  1937. #ifdef CPPHTTPLIB_SSL_ENABLED
  1938. SSLClient cli(host);
  1939. #else
  1940. Client cli(host);
  1941. #endif
  1942. cli.set_follow_location(true);
  1943. auto res = cli.Get(path);
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(StatusCode::OK_200, res->status);
  1946. }
  1947. TEST(TooManyRedirectTest, Redirect_Online) {
  1948. auto host = "httpbingo.org";
  1949. auto path = std::string{"/redirect/21"};
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_follow_location(true);
  1956. auto res = cli.Get(path);
  1957. ASSERT_TRUE(!res);
  1958. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1959. }
  1960. #ifdef CPPHTTPLIB_SSL_ENABLED
  1961. TEST(YahooRedirectTest, Redirect_Online) {
  1962. Client cli("yahoo.com");
  1963. auto res = cli.Get("/");
  1964. ASSERT_TRUE(res);
  1965. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1966. cli.set_follow_location(true);
  1967. res = cli.Get("/");
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::OK_200, res->status);
  1970. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1971. }
  1972. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1973. #define REDIR_HOST "httpbingo.org"
  1974. #define REDIR_PATH "/redirect-to"
  1975. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1976. SSLClient cli(REDIR_HOST);
  1977. cli.set_follow_location(true);
  1978. auto res =
  1979. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1984. SSLClient cli(REDIR_HOST);
  1985. cli.set_follow_location(true);
  1986. Params params;
  1987. params.emplace("url", "http://example.com");
  1988. params.emplace("status_code", "302");
  1989. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1990. ASSERT_TRUE(res);
  1991. EXPECT_EQ(StatusCode::OK_200, res->status);
  1992. }
  1993. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1994. SSLClient cli(REDIR_HOST);
  1995. cli.set_follow_location(true);
  1996. Params params;
  1997. params.emplace("url", "http://example.com");
  1998. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(StatusCode::OK_200, res->status);
  2001. }
  2002. TEST(UrlWithSpace, Redirect_Online) {
  2003. SSLClient cli("edge.forgecdn.net");
  2004. cli.set_follow_location(true);
  2005. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2006. ASSERT_TRUE(res);
  2007. EXPECT_EQ(StatusCode::OK_200, res->status);
  2008. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2009. }
  2010. #endif
  2011. #if !defined(_WIN32) && !defined(_WIN64)
  2012. TEST(ReceiveSignals, Signal) {
  2013. auto setupSignalHandlers = []() {
  2014. struct sigaction act;
  2015. sigemptyset(&act.sa_mask);
  2016. act.sa_flags = SA_SIGINFO;
  2017. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2018. switch (sig) {
  2019. case SIGINT:
  2020. default: break;
  2021. }
  2022. };
  2023. ::sigaction(SIGINT, &act, nullptr);
  2024. };
  2025. Server svr;
  2026. int port = 0;
  2027. auto thread = std::thread([&]() {
  2028. setupSignalHandlers();
  2029. port = svr.bind_to_any_port(HOST);
  2030. svr.listen_after_bind();
  2031. });
  2032. auto se = detail::scope_exit([&] {
  2033. svr.stop();
  2034. thread.join();
  2035. ASSERT_FALSE(svr.is_running());
  2036. });
  2037. svr.wait_until_ready();
  2038. ASSERT_TRUE(svr.is_running());
  2039. pthread_kill(thread.native_handle(), SIGINT);
  2040. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2041. ASSERT_TRUE(svr.is_running());
  2042. }
  2043. #endif
  2044. TEST(RedirectToDifferentPort, Redirect) {
  2045. Server svr1;
  2046. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2047. res.set_content("Hello World!", "text/plain");
  2048. });
  2049. int svr1_port = 0;
  2050. auto thread1 = std::thread([&]() {
  2051. svr1_port = svr1.bind_to_any_port(HOST);
  2052. svr1.listen_after_bind();
  2053. });
  2054. Server svr2;
  2055. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2056. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2057. });
  2058. int svr2_port = 0;
  2059. auto thread2 = std::thread([&]() {
  2060. svr2_port = svr2.bind_to_any_port(HOST);
  2061. svr2.listen_after_bind();
  2062. });
  2063. auto se = detail::scope_exit([&] {
  2064. svr2.stop();
  2065. thread2.join();
  2066. svr1.stop();
  2067. thread1.join();
  2068. ASSERT_FALSE(svr2.is_running());
  2069. ASSERT_FALSE(svr1.is_running());
  2070. });
  2071. svr1.wait_until_ready();
  2072. svr2.wait_until_ready();
  2073. Client cli("localhost", svr2_port);
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get("/2");
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. EXPECT_EQ("Hello World!", res->body);
  2079. }
  2080. static void
  2081. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2082. Server svr1;
  2083. std::string captured_authorization;
  2084. svr1.Get("/target", [&](const Request &req, Response &res) {
  2085. captured_authorization = req.get_header_value("Authorization");
  2086. res.set_content("OK", "text/plain");
  2087. });
  2088. int svr1_port = 0;
  2089. auto thread1 = std::thread([&]() {
  2090. svr1_port = svr1.bind_to_any_port(HOST);
  2091. svr1.listen_after_bind();
  2092. });
  2093. Server svr2;
  2094. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2095. res.set_redirect(
  2096. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2097. });
  2098. int svr2_port = 0;
  2099. auto thread2 = std::thread([&]() {
  2100. svr2_port = svr2.bind_to_any_port(HOST);
  2101. svr2.listen_after_bind();
  2102. });
  2103. auto se = detail::scope_exit([&] {
  2104. svr2.stop();
  2105. thread2.join();
  2106. svr1.stop();
  2107. thread1.join();
  2108. ASSERT_FALSE(svr2.is_running());
  2109. ASSERT_FALSE(svr1.is_running());
  2110. });
  2111. svr1.wait_until_ready();
  2112. svr2.wait_until_ready();
  2113. Client cli("localhost", svr2_port);
  2114. cli.set_follow_location(true);
  2115. set_auth(cli);
  2116. auto res = cli.Get("/redir");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2120. EXPECT_TRUE(captured_authorization.empty());
  2121. }
  2122. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2123. TestDoNotForwardCredentialsOnRedirect(
  2124. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2125. }
  2126. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2127. TestDoNotForwardCredentialsOnRedirect(
  2128. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2129. }
  2130. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2131. Server svr;
  2132. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2133. // Port number that overflows int — should not crash
  2134. res.set_redirect("http://localhost:99999999999999999999/target");
  2135. });
  2136. auto port = svr.bind_to_any_port(HOST);
  2137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2138. auto se = detail::scope_exit([&] {
  2139. svr.stop();
  2140. thread.join();
  2141. ASSERT_FALSE(svr.is_running());
  2142. });
  2143. svr.wait_until_ready();
  2144. Client cli(HOST, port);
  2145. cli.set_follow_location(true);
  2146. auto res = cli.Get("/redir");
  2147. // Should fail gracefully, not crash (no valid response due to bad port)
  2148. EXPECT_FALSE(res);
  2149. }
  2150. TEST(RedirectFromPageWithContent, Redirect) {
  2151. Server svr;
  2152. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content("___", "text/plain");
  2154. res.set_redirect("/2");
  2155. });
  2156. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2157. res.set_content("Hello World!", "text/plain");
  2158. });
  2159. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2160. auto se = detail::scope_exit([&] {
  2161. svr.stop();
  2162. th.join();
  2163. ASSERT_FALSE(svr.is_running());
  2164. });
  2165. svr.wait_until_ready();
  2166. {
  2167. Client cli("localhost", PORT);
  2168. cli.set_follow_location(true);
  2169. std::string body;
  2170. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2171. body.append(data, data_length);
  2172. return true;
  2173. });
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. EXPECT_EQ("Hello World!", body);
  2177. }
  2178. {
  2179. Client cli("localhost", PORT);
  2180. std::string body;
  2181. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2182. body.append(data, data_length);
  2183. return true;
  2184. });
  2185. ASSERT_TRUE(res);
  2186. EXPECT_EQ(StatusCode::Found_302, res->status);
  2187. EXPECT_EQ("___", body);
  2188. }
  2189. }
  2190. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2191. Server svr;
  2192. auto port_str = std::to_string(PORT);
  2193. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2194. auto expected_host = "[::1]:" + port_str;
  2195. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2196. res.set_content("___", "text/plain");
  2197. // res.set_redirect("/2");
  2198. res.set_redirect(redirect_url);
  2199. });
  2200. svr.Get("/2", [&](const Request &req, Response &res) {
  2201. auto host_header = req.headers.find("Host");
  2202. ASSERT_TRUE(host_header != req.headers.end());
  2203. EXPECT_EQ(expected_host, host_header->second);
  2204. res.set_content("Hello World!", "text/plain");
  2205. });
  2206. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2207. auto se = detail::scope_exit([&] {
  2208. svr.stop();
  2209. th.join();
  2210. ASSERT_FALSE(svr.is_running());
  2211. });
  2212. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2213. // actually starts anything, so the condition !svr.is_running() will
  2214. // always remain true, and the loop never stops.
  2215. // This basically counts how many milliseconds have passed since the
  2216. // call to svr.listen(), and if after 5 seconds nothing started yet
  2217. // aborts the test.
  2218. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2219. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2220. ASSERT_LT(milliseconds, 5000U);
  2221. }
  2222. {
  2223. Client cli("::1", PORT);
  2224. cli.set_follow_location(true);
  2225. std::string body;
  2226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2227. body.append(data, data_length);
  2228. return true;
  2229. });
  2230. ASSERT_TRUE(res);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ("Hello World!", body);
  2233. }
  2234. {
  2235. Client cli("::1", PORT);
  2236. std::string body;
  2237. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2238. body.append(data, data_length);
  2239. return true;
  2240. });
  2241. ASSERT_TRUE(res);
  2242. EXPECT_EQ(StatusCode::Found_302, res->status);
  2243. EXPECT_EQ("___", body);
  2244. }
  2245. }
  2246. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2247. Server svr;
  2248. svr.Get("/foo", [](const Request &req, Response &res) {
  2249. auto a = req.params.find("a");
  2250. if (a != req.params.end()) {
  2251. res.set_content((*a).second, "text/plain");
  2252. res.status = StatusCode::OK_200;
  2253. } else {
  2254. res.status = StatusCode::BadRequest_400;
  2255. }
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. {
  2265. Client cli(HOST, PORT);
  2266. cli.set_path_encode(false);
  2267. auto res = cli.Get("/foo?a=explicitly+encoded");
  2268. ASSERT_TRUE(res);
  2269. EXPECT_EQ(StatusCode::OK_200, res->status);
  2270. // This expects it back with a space, as the `+` won't have been
  2271. // url-encoded, and server-side the params get decoded turning `+`
  2272. // into spaces.
  2273. EXPECT_EQ("explicitly encoded", res->body);
  2274. }
  2275. }
  2276. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2277. Server svr;
  2278. svr.Get("/", [](const Request &req, Response &) {
  2279. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. {
  2289. Client cli(HOST, PORT);
  2290. cli.set_path_encode(false);
  2291. auto res = cli.Get("/?something=%0A");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::OK_200, res->status);
  2294. }
  2295. }
  2296. TEST(BindServerTest, BindDualStack) {
  2297. Server svr;
  2298. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2299. res.set_content("Hello World!", "text/plain");
  2300. });
  2301. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2302. auto se = detail::scope_exit([&] {
  2303. svr.stop();
  2304. thread.join();
  2305. ASSERT_FALSE(svr.is_running());
  2306. });
  2307. svr.wait_until_ready();
  2308. {
  2309. Client cli("127.0.0.1", PORT);
  2310. auto res = cli.Get("/1");
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ(StatusCode::OK_200, res->status);
  2313. EXPECT_EQ("Hello World!", res->body);
  2314. }
  2315. {
  2316. Client cli("::1", PORT);
  2317. auto res = cli.Get("/1");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!", res->body);
  2321. }
  2322. }
  2323. TEST(BindServerTest, BindAndListenSeparately) {
  2324. Server svr;
  2325. int port = svr.bind_to_any_port("0.0.0.0");
  2326. ASSERT_TRUE(svr.is_valid());
  2327. ASSERT_TRUE(port > 0);
  2328. svr.stop();
  2329. }
  2330. #ifdef CPPHTTPLIB_SSL_ENABLED
  2331. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2333. CLIENT_CA_CERT_DIR);
  2334. int port = svr.bind_to_any_port("0.0.0.0");
  2335. ASSERT_TRUE(svr.is_valid());
  2336. ASSERT_TRUE(port > 0);
  2337. svr.stop();
  2338. }
  2339. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2340. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2341. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2342. int port = svr.bind_to_any_port("0.0.0.0");
  2343. ASSERT_TRUE(svr.is_valid());
  2344. ASSERT_TRUE(port > 0);
  2345. svr.stop();
  2346. }
  2347. TEST(BindServerTest, UpdateCertsPem) {
  2348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2349. int port = svr.bind_to_any_port("0.0.0.0");
  2350. ASSERT_TRUE(svr.is_valid());
  2351. ASSERT_TRUE(port > 0);
  2352. // Read PEM files
  2353. std::string cert_pem, key_pem, ca_pem;
  2354. read_file(SERVER_CERT_FILE, cert_pem);
  2355. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2356. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2357. // Update server certificates using PEM API
  2358. ASSERT_TRUE(
  2359. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2360. ASSERT_TRUE(svr.is_valid());
  2361. svr.stop();
  2362. }
  2363. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2364. // Start server with client CA (enables client auth)
  2365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2366. ASSERT_TRUE(svr.is_valid());
  2367. bool handler_called = false;
  2368. svr.Get("/test", [&](const Request &req, Response &res) {
  2369. handler_called = true;
  2370. // Verify client certificate is present
  2371. auto cert = req.peer_cert();
  2372. EXPECT_TRUE(static_cast<bool>(cert));
  2373. res.set_content("ok", "text/plain");
  2374. });
  2375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2376. auto se = detail::scope_exit([&] {
  2377. svr.stop();
  2378. t.join();
  2379. ASSERT_FALSE(svr.is_running());
  2380. });
  2381. svr.wait_until_ready();
  2382. // Read PEM files
  2383. std::string cert_pem, key_pem, ca_pem;
  2384. read_file(SERVER_CERT_FILE, cert_pem);
  2385. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2386. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2387. // Update server certificates and client CA using PEM API while server running
  2388. ASSERT_TRUE(
  2389. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2390. // Connect with client certificate
  2391. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2392. cli.enable_server_certificate_verification(false);
  2393. cli.set_connection_timeout(30);
  2394. auto res = cli.Get("/test");
  2395. ASSERT_TRUE(res);
  2396. ASSERT_EQ(StatusCode::OK_200, res->status);
  2397. ASSERT_TRUE(handler_called);
  2398. EXPECT_EQ("ok", res->body);
  2399. }
  2400. #endif
  2401. TEST(ErrorHandlerTest, ContentLength) {
  2402. Server svr;
  2403. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2404. res.status = StatusCode::OK_200;
  2405. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2406. "text/html"); // <= Content-Length still 13
  2407. });
  2408. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2409. res.set_content("Hello World!\n", "text/plain");
  2410. res.status = 524;
  2411. });
  2412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2413. auto se = detail::scope_exit([&] {
  2414. svr.stop();
  2415. thread.join();
  2416. ASSERT_FALSE(svr.is_running());
  2417. });
  2418. svr.wait_until_ready();
  2419. {
  2420. Client cli(HOST, PORT);
  2421. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2425. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2426. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2427. }
  2428. }
  2429. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2430. TEST(ExceptionTest, WithoutExceptionHandler) {
  2431. Server svr;
  2432. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2433. throw std::runtime_error("exception...");
  2434. });
  2435. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2436. throw std::runtime_error("exception\r\n...");
  2437. });
  2438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. listen_thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli("localhost", PORT);
  2446. {
  2447. auto res = cli.Get("/exception");
  2448. ASSERT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2450. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2451. }
  2452. {
  2453. auto res = cli.Get("/unknown");
  2454. ASSERT_TRUE(res);
  2455. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2456. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2457. }
  2458. }
  2459. TEST(ExceptionTest, WithExceptionHandler) {
  2460. Server svr;
  2461. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2462. std::exception_ptr ep) {
  2463. EXPECT_FALSE(ep == nullptr);
  2464. try {
  2465. std::rethrow_exception(ep);
  2466. } catch (std::exception &e) {
  2467. EXPECT_EQ("abc", std::string(e.what()));
  2468. } catch (...) {}
  2469. res.status = StatusCode::InternalServerError_500;
  2470. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2471. "text/html"); // <= Content-Length still 13 at this point
  2472. });
  2473. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!\n", "text/plain");
  2475. throw std::runtime_error("abc");
  2476. });
  2477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. thread.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. for (size_t i = 0; i < 10; i++) {
  2485. Client cli(HOST, PORT);
  2486. for (size_t j = 0; j < 100; j++) {
  2487. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2490. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2491. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2492. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2493. }
  2494. cli.set_keep_alive(true);
  2495. for (size_t j = 0; j < 100; j++) {
  2496. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2497. ASSERT_TRUE(res);
  2498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2501. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2502. }
  2503. }
  2504. }
  2505. TEST(ExceptionTest, AndErrorHandler) {
  2506. Server svr;
  2507. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2508. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2509. });
  2510. svr.set_exception_handler(
  2511. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2512. EXPECT_FALSE(ep == nullptr);
  2513. try {
  2514. std::rethrow_exception(ep);
  2515. } catch (std::exception &e) {
  2516. res.set_content(e.what(), "text/html");
  2517. } catch (...) {}
  2518. res.status = StatusCode::InternalServerError_500;
  2519. });
  2520. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2521. throw std::runtime_error("EXCEPTION");
  2522. });
  2523. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2524. res.set_content("ERROR", "text/html");
  2525. res.status = StatusCode::InternalServerError_500;
  2526. });
  2527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2528. auto se = detail::scope_exit([&] {
  2529. svr.stop();
  2530. thread.join();
  2531. ASSERT_FALSE(svr.is_running());
  2532. });
  2533. svr.wait_until_ready();
  2534. Client cli(HOST, PORT);
  2535. {
  2536. auto res = cli.Get("/exception");
  2537. ASSERT_TRUE(res);
  2538. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2539. EXPECT_EQ("EXCEPTION", res->body);
  2540. }
  2541. {
  2542. auto res = cli.Get("/error");
  2543. ASSERT_TRUE(res);
  2544. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2545. EXPECT_EQ("ERROR", res->body);
  2546. }
  2547. {
  2548. auto res = cli.Get("/invalid");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2551. EXPECT_EQ("NOT_FOUND", res->body);
  2552. }
  2553. }
  2554. #endif
  2555. TEST(NoContentTest, ContentLength) {
  2556. Server svr;
  2557. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2558. res.status = StatusCode::NoContent_204;
  2559. });
  2560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2561. auto se = detail::scope_exit([&] {
  2562. svr.stop();
  2563. thread.join();
  2564. ASSERT_FALSE(svr.is_running());
  2565. });
  2566. svr.wait_until_ready();
  2567. {
  2568. Client cli(HOST, PORT);
  2569. auto res = cli.Get("/hi");
  2570. ASSERT_TRUE(res);
  2571. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2572. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2573. }
  2574. }
  2575. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2578. ASSERT_TRUE(svr.is_valid());
  2579. #else
  2580. Server svr;
  2581. #endif
  2582. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2583. if (req.path == "/routing_handler") {
  2584. res.set_header("PRE_ROUTING", "on");
  2585. res.set_content("Routing Handler", "text/plain");
  2586. return httplib::Server::HandlerResponse::Handled;
  2587. }
  2588. return httplib::Server::HandlerResponse::Unhandled;
  2589. });
  2590. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2591. res.set_content("Error", "text/html");
  2592. });
  2593. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2594. if (req.path == "/routing_handler") {
  2595. res.set_header("POST_ROUTING", "on");
  2596. }
  2597. });
  2598. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!\n", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. {
  2609. #ifdef CPPHTTPLIB_SSL_ENABLED
  2610. SSLClient cli(HOST, PORT);
  2611. cli.enable_server_certificate_verification(false);
  2612. #else
  2613. Client cli(HOST, PORT);
  2614. #endif
  2615. auto res = cli.Get("/routing_handler");
  2616. ASSERT_TRUE(res);
  2617. EXPECT_EQ(StatusCode::OK_200, res->status);
  2618. EXPECT_EQ("Routing Handler", res->body);
  2619. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2620. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2621. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2622. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2623. }
  2624. {
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. SSLClient cli(HOST, PORT);
  2627. cli.enable_server_certificate_verification(false);
  2628. #else
  2629. Client cli(HOST, PORT);
  2630. #endif
  2631. auto res = cli.Get("/hi");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. EXPECT_EQ("Hello World!\n", res->body);
  2635. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2636. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2637. }
  2638. {
  2639. #ifdef CPPHTTPLIB_SSL_ENABLED
  2640. SSLClient cli(HOST, PORT);
  2641. cli.enable_server_certificate_verification(false);
  2642. #else
  2643. Client cli(HOST, PORT);
  2644. #endif
  2645. auto res = cli.Get("/aaa");
  2646. ASSERT_TRUE(res);
  2647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2648. EXPECT_EQ("Error", res->body);
  2649. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2650. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2651. }
  2652. }
  2653. TEST(RequestHandlerTest, PreRequestHandler) {
  2654. auto route_path = "/user/:user";
  2655. Server svr;
  2656. svr.Get("/hi", [](const Request &, Response &res) {
  2657. res.set_content("hi", "text/plain");
  2658. });
  2659. svr.Get(route_path, [](const Request &req, Response &res) {
  2660. res.set_content(req.path_params.at("user"), "text/plain");
  2661. });
  2662. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2663. if (req.matched_route == route_path) {
  2664. auto user = req.path_params.at("user");
  2665. if (user != "john") {
  2666. res.status = StatusCode::Forbidden_403;
  2667. res.set_content("error", "text/html");
  2668. return Server::HandlerResponse::Handled;
  2669. }
  2670. }
  2671. return Server::HandlerResponse::Unhandled;
  2672. });
  2673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2674. auto se = detail::scope_exit([&] {
  2675. svr.stop();
  2676. thread.join();
  2677. ASSERT_FALSE(svr.is_running());
  2678. });
  2679. svr.wait_until_ready();
  2680. Client cli(HOST, PORT);
  2681. {
  2682. auto res = cli.Get("/hi");
  2683. ASSERT_TRUE(res);
  2684. EXPECT_EQ(StatusCode::OK_200, res->status);
  2685. EXPECT_EQ("hi", res->body);
  2686. }
  2687. {
  2688. auto res = cli.Get("/user/john");
  2689. ASSERT_TRUE(res);
  2690. EXPECT_EQ(StatusCode::OK_200, res->status);
  2691. EXPECT_EQ("john", res->body);
  2692. }
  2693. {
  2694. auto res = cli.Get("/user/invalid-user");
  2695. ASSERT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2697. EXPECT_EQ("error", res->body);
  2698. }
  2699. }
  2700. TEST(UserDataTest, BasicOperations) {
  2701. httplib::UserData ud;
  2702. // Initially empty
  2703. EXPECT_FALSE(ud.has("key"));
  2704. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2705. // set and get
  2706. ud.set("key", 42);
  2707. EXPECT_TRUE(ud.has("key"));
  2708. auto *p = ud.get<int>("key");
  2709. ASSERT_NE(nullptr, p);
  2710. EXPECT_EQ(42, *p);
  2711. // Type mismatch → nullptr
  2712. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2713. // Overwrite with different type
  2714. ud.set("key", std::string("hello"));
  2715. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2716. auto *s = ud.get<std::string>("key");
  2717. ASSERT_NE(nullptr, s);
  2718. EXPECT_EQ("hello", *s);
  2719. // erase
  2720. ud.erase("key");
  2721. EXPECT_FALSE(ud.has("key"));
  2722. // clear
  2723. ud.set("a", 1);
  2724. ud.set("b", 2);
  2725. ud.clear();
  2726. EXPECT_FALSE(ud.has("a"));
  2727. EXPECT_FALSE(ud.has("b"));
  2728. }
  2729. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2730. struct AuthCtx {
  2731. std::string user_id;
  2732. };
  2733. Server svr;
  2734. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2735. res.user_data.set("auth", AuthCtx{"alice"});
  2736. return Server::HandlerResponse::Unhandled;
  2737. });
  2738. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2739. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2740. ASSERT_NE(nullptr, ctx);
  2741. res.set_content("Hello " + ctx->user_id, "text/plain");
  2742. });
  2743. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2744. auto se = detail::scope_exit([&] {
  2745. svr.stop();
  2746. thread.join();
  2747. ASSERT_FALSE(svr.is_running());
  2748. });
  2749. svr.wait_until_ready();
  2750. Client cli(HOST, PORT);
  2751. auto res = cli.Get("/me");
  2752. ASSERT_TRUE(res);
  2753. EXPECT_EQ(StatusCode::OK_200, res->status);
  2754. EXPECT_EQ("Hello alice", res->body);
  2755. }
  2756. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2757. struct RoleCtx {
  2758. std::string role;
  2759. };
  2760. Server svr;
  2761. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2762. res.user_data.set("role", RoleCtx{"admin"});
  2763. return Server::HandlerResponse::Unhandled;
  2764. });
  2765. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2766. auto *ctx = res.user_data.get<RoleCtx>("role");
  2767. ASSERT_NE(nullptr, ctx);
  2768. res.set_content(ctx->role, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. auto res = cli.Get("/role");
  2779. ASSERT_TRUE(res);
  2780. EXPECT_EQ(StatusCode::OK_200, res->status);
  2781. EXPECT_EQ("admin", res->body);
  2782. }
  2783. TEST(InvalidFormatTest, StatusCode) {
  2784. Server svr;
  2785. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2786. res.set_content("Hello World!\n", "text/plain");
  2787. res.status = 9999; // Status should be a three-digit code...
  2788. });
  2789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. thread.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. {
  2797. Client cli(HOST, PORT);
  2798. auto res = cli.Get("/hi");
  2799. ASSERT_FALSE(res);
  2800. }
  2801. }
  2802. TEST(URLFragmentTest, WithFragment) {
  2803. Server svr;
  2804. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2805. EXPECT_TRUE(req.target == "/hi");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2817. EXPECT_TRUE(res);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. res = cli.Get("/hi%23key1=val1=key2=val2");
  2820. EXPECT_TRUE(res);
  2821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2822. }
  2823. }
  2824. TEST(HeaderWriter, SetHeaderWriter) {
  2825. Server svr;
  2826. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2827. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2828. return detail::write_headers(strm, hdrs);
  2829. });
  2830. svr.Get("/hi", [](const Request &req, Response &res) {
  2831. auto it = req.headers.find("CustomClientHeader");
  2832. EXPECT_TRUE(it != req.headers.end());
  2833. EXPECT_EQ(it->second, "CustomClientValue");
  2834. res.set_content("Hello World!\n", "text/plain");
  2835. });
  2836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. thread.join();
  2840. ASSERT_FALSE(svr.is_running());
  2841. });
  2842. svr.wait_until_ready();
  2843. {
  2844. Client cli(HOST, PORT);
  2845. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2846. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2847. return detail::write_headers(strm, hdrs);
  2848. });
  2849. auto res = cli.Get("/hi");
  2850. EXPECT_TRUE(res);
  2851. EXPECT_EQ(StatusCode::OK_200, res->status);
  2852. auto it = res->headers.find("CustomServerHeader");
  2853. EXPECT_TRUE(it != res->headers.end());
  2854. EXPECT_EQ(it->second, "CustomServerValue");
  2855. }
  2856. }
  2857. class ServerTest : public ::testing::Test {
  2858. protected:
  2859. ServerTest()
  2860. : cli_(HOST, PORT)
  2861. #ifdef CPPHTTPLIB_SSL_ENABLED
  2862. ,
  2863. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2864. #endif
  2865. {
  2866. #ifdef CPPHTTPLIB_SSL_ENABLED
  2867. cli_.enable_server_certificate_verification(false);
  2868. #endif
  2869. // Allow LARGE_DATA (100MB) responses
  2870. cli_.set_payload_max_length(200 * 1024 * 1024);
  2871. }
  2872. virtual void SetUp() {
  2873. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2874. svr_.set_payload_max_length(200 * 1024 * 1024);
  2875. svr_.set_mount_point("/", "./www");
  2876. svr_.set_mount_point("/mount", "./www2");
  2877. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2878. svr_.Get("/hi",
  2879. [&](const Request & /*req*/, Response &res) {
  2880. res.set_content("Hello World!", "text/plain");
  2881. })
  2882. .Get("/file_content",
  2883. [&](const Request & /*req*/, Response &res) {
  2884. res.set_file_content("./www/dir/test.html");
  2885. })
  2886. .Get("/file_content_with_content_type",
  2887. [&](const Request & /*req*/, Response &res) {
  2888. res.set_file_content("./www/file", "text/plain");
  2889. })
  2890. .Get("/invalid_file_content",
  2891. [&](const Request & /*req*/, Response &res) {
  2892. res.set_file_content("./www/dir/invalid_file_path");
  2893. })
  2894. .Get("/http_response_splitting",
  2895. [&](const Request & /*req*/, Response &res) {
  2896. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2897. EXPECT_EQ(0U, res.headers.size());
  2898. EXPECT_FALSE(res.has_header("a"));
  2899. res.set_header("a", "1\nSet-Cookie: a=1");
  2900. EXPECT_EQ(0U, res.headers.size());
  2901. EXPECT_FALSE(res.has_header("a"));
  2902. res.set_header("a", "1\rSet-Cookie: a=1");
  2903. EXPECT_EQ(0U, res.headers.size());
  2904. EXPECT_FALSE(res.has_header("a"));
  2905. res.set_header("a\r\nb", "0");
  2906. EXPECT_EQ(0U, res.headers.size());
  2907. EXPECT_FALSE(res.has_header("a"));
  2908. res.set_header("a\rb", "0");
  2909. EXPECT_EQ(0U, res.headers.size());
  2910. EXPECT_FALSE(res.has_header("a"));
  2911. res.set_header("a\nb", "0");
  2912. EXPECT_EQ(0U, res.headers.size());
  2913. EXPECT_FALSE(res.has_header("a"));
  2914. res.set_redirect("1\r\nSet-Cookie: a=1");
  2915. EXPECT_EQ(0U, res.headers.size());
  2916. EXPECT_FALSE(res.has_header("Location"));
  2917. })
  2918. .Get("/slow",
  2919. [&](const Request & /*req*/, Response &res) {
  2920. std::this_thread::sleep_for(std::chrono::seconds(4));
  2921. res.set_content("slow", "text/plain");
  2922. })
  2923. #if 0
  2924. .Post("/slowpost",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. std::this_thread::sleep_for(std::chrono::seconds(2));
  2927. res.set_content("slow", "text/plain");
  2928. })
  2929. #endif
  2930. .Get("/remote_addr",
  2931. [&](const Request &req, Response &res) {
  2932. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2933. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2934. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2935. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2936. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2937. #endif
  2938. res.set_content(req.remote_addr, "text/plain");
  2939. })
  2940. .Get("/local_addr",
  2941. [&](const Request &req, Response &res) {
  2942. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2943. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2944. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2945. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2946. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2947. #endif
  2948. auto local_addr = req.local_addr;
  2949. auto local_port = std::to_string(req.local_port);
  2950. res.set_content(local_addr.append(":").append(local_port),
  2951. "text/plain");
  2952. })
  2953. .Get("/endwith%",
  2954. [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. })
  2957. .Get("/a\\+\\+b",
  2958. [&](const Request &req, Response &res) {
  2959. ASSERT_TRUE(req.has_param("a +b"));
  2960. auto val = req.get_param_value("a +b");
  2961. res.set_content(val, "text/plain");
  2962. })
  2963. .Get("/", [&](const Request & /*req*/,
  2964. Response &res) { res.set_redirect("/hi"); })
  2965. .Post("/1",
  2966. [](const Request & /*req*/, Response &res) {
  2967. res.set_redirect("/2", StatusCode::SeeOther_303);
  2968. })
  2969. .Get("/2",
  2970. [](const Request & /*req*/, Response &res) {
  2971. res.set_content("redirected.", "text/plain");
  2972. res.status = StatusCode::OK_200;
  2973. })
  2974. .Post("/person",
  2975. [&](const Request &req, Response &res) {
  2976. if (req.has_param("name") && req.has_param("note")) {
  2977. persons_[req.get_param_value("name")] =
  2978. req.get_param_value("note");
  2979. } else {
  2980. res.status = StatusCode::BadRequest_400;
  2981. }
  2982. })
  2983. .Put("/person",
  2984. [&](const Request &req, Response &res) {
  2985. if (req.has_param("name") && req.has_param("note")) {
  2986. persons_[req.get_param_value("name")] =
  2987. req.get_param_value("note");
  2988. } else {
  2989. res.status = StatusCode::BadRequest_400;
  2990. }
  2991. })
  2992. .Get("/person/(.*)",
  2993. [&](const Request &req, Response &res) {
  2994. string name = req.matches[1];
  2995. if (persons_.find(name) != persons_.end()) {
  2996. auto note = persons_[name];
  2997. res.set_content(note, "text/plain");
  2998. } else {
  2999. res.status = StatusCode::NotFound_404;
  3000. }
  3001. })
  3002. .Delete("/person",
  3003. [&](const Request &req, Response &res) {
  3004. if (req.has_param("name")) {
  3005. string name = req.get_param_value("name");
  3006. if (persons_.find(name) != persons_.end()) {
  3007. persons_.erase(name);
  3008. res.set_content("DELETED", "text/plain");
  3009. } else {
  3010. res.status = StatusCode::NotFound_404;
  3011. }
  3012. } else {
  3013. res.status = StatusCode::BadRequest_400;
  3014. }
  3015. })
  3016. .Post("/x-www-form-urlencoded-json",
  3017. [&](const Request &req, Response &res) {
  3018. auto json = req.get_param_value("json");
  3019. ASSERT_EQ(JSON_DATA, json);
  3020. res.set_content(json, "appliation/json");
  3021. res.status = StatusCode::OK_200;
  3022. })
  3023. .Get("/streamed-chunked",
  3024. [&](const Request & /*req*/, Response &res) {
  3025. res.set_chunked_content_provider(
  3026. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3027. sink.os << "123";
  3028. sink.os << "456";
  3029. sink.os << "789";
  3030. sink.done();
  3031. return true;
  3032. });
  3033. })
  3034. .Get("/streamed-chunked-with-prohibited-trailer",
  3035. [&](const Request & /*req*/, Response &res) {
  3036. auto i = new int(0);
  3037. // Declare both a prohibited trailer (Content-Length) and an
  3038. // allowed one
  3039. res.set_header("Trailer", "Content-Length, X-Allowed");
  3040. res.set_chunked_content_provider(
  3041. "text/plain",
  3042. [i](size_t /*offset*/, DataSink &sink) {
  3043. switch (*i) {
  3044. case 0: sink.os << "123"; break;
  3045. case 1: sink.os << "456"; break;
  3046. case 2: sink.os << "789"; break;
  3047. case 3: {
  3048. sink.done_with_trailer(
  3049. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3050. } break;
  3051. }
  3052. (*i)++;
  3053. return true;
  3054. },
  3055. [i](bool success) {
  3056. EXPECT_TRUE(success);
  3057. delete i;
  3058. });
  3059. })
  3060. .Get("/streamed-chunked2",
  3061. [&](const Request & /*req*/, Response &res) {
  3062. auto i = new int(0);
  3063. res.set_chunked_content_provider(
  3064. "text/plain",
  3065. [i](size_t /*offset*/, DataSink &sink) {
  3066. switch (*i) {
  3067. case 0: sink.os << "123"; break;
  3068. case 1: sink.os << "456"; break;
  3069. case 2: sink.os << "789"; break;
  3070. case 3: sink.done(); break;
  3071. }
  3072. (*i)++;
  3073. return true;
  3074. },
  3075. [i](bool success) {
  3076. EXPECT_TRUE(success);
  3077. delete i;
  3078. });
  3079. })
  3080. .Get("/streamed-chunked-with-trailer",
  3081. [&](const Request & /*req*/, Response &res) {
  3082. auto i = new int(0);
  3083. res.set_header("Trailer", "Dummy1, Dummy2");
  3084. res.set_chunked_content_provider(
  3085. "text/plain",
  3086. [i](size_t /*offset*/, DataSink &sink) {
  3087. switch (*i) {
  3088. case 0: sink.os << "123"; break;
  3089. case 1: sink.os << "456"; break;
  3090. case 2: sink.os << "789"; break;
  3091. case 3: {
  3092. sink.done_with_trailer(
  3093. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3094. } break;
  3095. }
  3096. (*i)++;
  3097. return true;
  3098. },
  3099. [i](bool success) {
  3100. EXPECT_TRUE(success);
  3101. delete i;
  3102. });
  3103. })
  3104. .Get("/streamed",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. 6, "text/plain",
  3108. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3109. sink.os << (offset < 3 ? "a" : "b");
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/streamed-without-length",
  3114. [&](const Request & /*req*/, Response &res) {
  3115. auto data = new std::string("abcdefg");
  3116. res.set_content_provider(
  3117. "text/plain",
  3118. [data](size_t offset, DataSink &sink) {
  3119. if (offset < data->size()) {
  3120. sink.os << data->substr(offset);
  3121. }
  3122. sink.done();
  3123. return true;
  3124. },
  3125. [data](bool success) {
  3126. EXPECT_TRUE(success);
  3127. delete data;
  3128. });
  3129. })
  3130. .Get("/streamed-with-range",
  3131. [&](const Request &req, Response &res) {
  3132. auto data = new std::string("abcdefg");
  3133. res.set_content_provider(
  3134. data->size(), "text/plain",
  3135. [data](size_t offset, size_t length, DataSink &sink) {
  3136. size_t DATA_CHUNK_SIZE = 4;
  3137. const auto &d = *data;
  3138. auto out_len =
  3139. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3140. auto ret =
  3141. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3142. EXPECT_TRUE(ret);
  3143. return true;
  3144. },
  3145. [data, &req](bool success) {
  3146. EXPECT_EQ(success, !req.has_param("error"));
  3147. delete data;
  3148. });
  3149. })
  3150. .Get("/streamed-cancel",
  3151. [&](const Request & /*req*/, Response &res) {
  3152. res.set_content_provider(
  3153. size_t(-1), "text/plain",
  3154. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3155. sink.os << "data_chunk";
  3156. return true;
  3157. });
  3158. })
  3159. .Get("/regex-with-delimiter",
  3160. [&](const Request &req, Response & /*res*/) {
  3161. ASSERT_TRUE(req.has_param("key"));
  3162. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3163. })
  3164. .Get("/with-range",
  3165. [&](const Request & /*req*/, Response &res) {
  3166. res.set_content("abcdefg", "text/plain");
  3167. })
  3168. .Get("/test-start-time",
  3169. [&](const Request &req, Response & /*res*/) {
  3170. EXPECT_NE(req.start_time_,
  3171. std::chrono::steady_clock::time_point::min());
  3172. })
  3173. .Get("/with-range-customized-response",
  3174. [&](const Request & /*req*/, Response &res) {
  3175. res.status = StatusCode::BadRequest_400;
  3176. res.set_content(JSON_DATA, "application/json");
  3177. })
  3178. .Post("/chunked",
  3179. [&](const Request &req, Response & /*res*/) {
  3180. EXPECT_EQ(req.body, "dechunked post body");
  3181. })
  3182. .Post("/large-chunked",
  3183. [&](const Request &req, Response & /*res*/) {
  3184. std::string expected(6 * 30 * 1024u, 'a');
  3185. EXPECT_EQ(req.body, expected);
  3186. })
  3187. .Post("/multipart",
  3188. [&](const Request &req, Response & /*res*/) {
  3189. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3190. req.form.get_field_count("text2") +
  3191. req.form.get_field_count("file3") +
  3192. req.form.get_field_count("file4"));
  3193. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3194. req.form.get_file_count("file2"));
  3195. ASSERT_TRUE(!req.form.has_file("???"));
  3196. ASSERT_TRUE(!req.form.has_field("???"));
  3197. ASSERT_TRUE(req.body.empty());
  3198. {
  3199. const auto &text = req.form.get_field("text1");
  3200. EXPECT_EQ("text default", text);
  3201. }
  3202. {
  3203. const auto &text = req.form.get_field("text2");
  3204. EXPECT_EQ("aωb", text);
  3205. }
  3206. {
  3207. const auto &file = req.form.get_file("file1");
  3208. EXPECT_EQ("hello.txt", file.filename);
  3209. EXPECT_EQ("text/plain", file.content_type);
  3210. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3211. }
  3212. {
  3213. const auto &file = req.form.get_file("file2");
  3214. EXPECT_EQ("world.json", file.filename);
  3215. EXPECT_EQ("application/json", file.content_type);
  3216. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3217. }
  3218. {
  3219. const auto &text = req.form.get_field("file3");
  3220. EXPECT_EQ(0u, text.size());
  3221. }
  3222. {
  3223. const auto &text = req.form.get_field("file4");
  3224. EXPECT_EQ(0u, text.size());
  3225. }
  3226. })
  3227. .Post("/multipart/multi_file_values",
  3228. [&](const Request &req, Response & /*res*/) {
  3229. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3230. req.form.get_field_count("multi_text1"));
  3231. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3232. ASSERT_TRUE(!req.form.has_file("???"));
  3233. ASSERT_TRUE(!req.form.has_field("???"));
  3234. ASSERT_TRUE(req.body.empty());
  3235. {
  3236. const auto &text = req.form.get_field("text");
  3237. EXPECT_EQ("default text", text);
  3238. }
  3239. {
  3240. const auto &text1_values = req.form.get_fields("multi_text1");
  3241. EXPECT_EQ(2u, text1_values.size());
  3242. EXPECT_EQ("aaaaa", text1_values[0]);
  3243. EXPECT_EQ("bbbbb", text1_values[1]);
  3244. }
  3245. {
  3246. const auto &file1_values = req.form.get_files("multi_file1");
  3247. EXPECT_EQ(2u, file1_values.size());
  3248. auto file1 = file1_values[0];
  3249. EXPECT_EQ(file1.filename, "hello.txt");
  3250. EXPECT_EQ(file1.content_type, "text/plain");
  3251. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3252. auto file2 = file1_values[1];
  3253. EXPECT_EQ(file2.filename, "world.json");
  3254. EXPECT_EQ(file2.content_type, "application/json");
  3255. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3256. }
  3257. })
  3258. .Post("/empty",
  3259. [&](const Request &req, Response &res) {
  3260. EXPECT_EQ(req.body, "");
  3261. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3262. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3263. res.set_content("empty", "text/plain");
  3264. })
  3265. .Post("/empty-no-content-type",
  3266. [&](const Request &req, Response &res) {
  3267. EXPECT_EQ(req.body, "");
  3268. EXPECT_FALSE(req.has_header("Content-Type"));
  3269. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3270. res.set_content("empty-no-content-type", "text/plain");
  3271. })
  3272. .Post("/path-only",
  3273. [&](const Request &req, Response &res) {
  3274. EXPECT_EQ(req.body, "");
  3275. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3276. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3277. res.set_content("path-only", "text/plain");
  3278. })
  3279. .Post("/path-headers-only",
  3280. [&](const Request &req, Response &res) {
  3281. EXPECT_EQ(req.body, "");
  3282. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3283. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3284. EXPECT_EQ("world", req.get_header_value("hello"));
  3285. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3286. res.set_content("path-headers-only", "text/plain");
  3287. })
  3288. .Post("/post-large",
  3289. [&](const Request &req, Response &res) {
  3290. EXPECT_EQ(req.body, LARGE_DATA);
  3291. res.set_content(req.body, "text/plain");
  3292. })
  3293. .Post("/post-loopback",
  3294. [&](const Request &, Response &res,
  3295. ContentReader const &content_reader) {
  3296. std::string body;
  3297. content_reader([&](const char *data, size_t data_length) {
  3298. body.append(data, data_length);
  3299. return true;
  3300. });
  3301. res.set_content(body, "text/plain");
  3302. })
  3303. .Put("/put-loopback",
  3304. [&](const Request &, Response &res,
  3305. ContentReader const &content_reader) {
  3306. std::string body;
  3307. content_reader([&](const char *data, size_t data_length) {
  3308. body.append(data, data_length);
  3309. return true;
  3310. });
  3311. res.set_content(body, "text/plain");
  3312. })
  3313. .Patch("/patch-loopback",
  3314. [&](const Request &, Response &res,
  3315. ContentReader const &content_reader) {
  3316. std::string body;
  3317. content_reader([&](const char *data, size_t data_length) {
  3318. body.append(data, data_length);
  3319. return true;
  3320. });
  3321. res.set_content(body, "text/plain");
  3322. })
  3323. .Put("/empty-no-content-type",
  3324. [&](const Request &req, Response &res) {
  3325. EXPECT_EQ(req.body, "");
  3326. EXPECT_FALSE(req.has_header("Content-Type"));
  3327. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3328. res.set_content("empty-no-content-type", "text/plain");
  3329. })
  3330. .Put("/put",
  3331. [&](const Request &req, Response &res) {
  3332. EXPECT_EQ(req.body, "PUT");
  3333. res.set_content(req.body, "text/plain");
  3334. })
  3335. .Put("/put-large",
  3336. [&](const Request &req, Response &res) {
  3337. EXPECT_EQ(req.body, LARGE_DATA);
  3338. res.set_content(req.body, "text/plain");
  3339. })
  3340. .Patch("/patch",
  3341. [&](const Request &req, Response &res) {
  3342. EXPECT_EQ(req.body, "PATCH");
  3343. res.set_content(req.body, "text/plain");
  3344. })
  3345. .Delete("/delete",
  3346. [&](const Request & /*req*/, Response &res) {
  3347. res.set_content("DELETE", "text/plain");
  3348. })
  3349. .Delete("/delete-body",
  3350. [&](const Request &req, Response &res) {
  3351. EXPECT_EQ(req.body, "content");
  3352. res.set_content(req.body, "text/plain");
  3353. })
  3354. .Options(R"(\*)",
  3355. [&](const Request & /*req*/, Response &res) {
  3356. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3357. })
  3358. .Get("/request-target",
  3359. [&](const Request &req, Response & /*res*/) {
  3360. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3361. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3362. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3363. })
  3364. .Get("/long-query-value",
  3365. [&](const Request &req, Response & /*res*/) {
  3366. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3367. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3368. })
  3369. .Get("/too-long-query-value",
  3370. [&](const Request &req, Response & /*res*/) {
  3371. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3372. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3373. })
  3374. .Get("/array-param",
  3375. [&](const Request &req, Response & /*res*/) {
  3376. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3377. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3378. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3379. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3380. })
  3381. .Get("/array-param-values",
  3382. [&](const Request &req, Response & /*res*/) {
  3383. auto values = req.get_param_values("array");
  3384. EXPECT_EQ(3u, values.size());
  3385. EXPECT_EQ("value1", values[0]);
  3386. EXPECT_EQ("value2", values[1]);
  3387. EXPECT_EQ("value3", values[2]);
  3388. auto empty = req.get_param_values("nonexistent");
  3389. EXPECT_TRUE(empty.empty());
  3390. })
  3391. .Post("/validate-no-multiple-headers",
  3392. [&](const Request &req, Response & /*res*/) {
  3393. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3394. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3395. })
  3396. .Post("/content_receiver",
  3397. [&](const Request &req, Response &res,
  3398. const ContentReader &content_reader) {
  3399. if (req.is_multipart_form_data()) {
  3400. std::vector<FormData> items;
  3401. content_reader(
  3402. [&](const FormData &file) {
  3403. items.push_back(file);
  3404. return true;
  3405. },
  3406. [&](const char *data, size_t data_length) {
  3407. items.back().content.append(data, data_length);
  3408. return true;
  3409. });
  3410. EXPECT_EQ(5u, items.size());
  3411. {
  3412. const auto &file = get_file_value(items, "text1");
  3413. EXPECT_TRUE(file.filename.empty());
  3414. EXPECT_EQ("text default", file.content);
  3415. }
  3416. {
  3417. const auto &file = get_file_value(items, "text2");
  3418. EXPECT_TRUE(file.filename.empty());
  3419. EXPECT_EQ("aωb", file.content);
  3420. }
  3421. {
  3422. const auto &file = get_file_value(items, "file1");
  3423. EXPECT_EQ("hello.txt", file.filename);
  3424. EXPECT_EQ("text/plain", file.content_type);
  3425. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3426. }
  3427. {
  3428. const auto &file = get_file_value(items, "file2");
  3429. EXPECT_EQ("world.json", file.filename);
  3430. EXPECT_EQ("application/json", file.content_type);
  3431. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3432. }
  3433. {
  3434. const auto &file = get_file_value(items, "file3");
  3435. EXPECT_TRUE(file.filename.empty());
  3436. EXPECT_EQ("application/octet-stream", file.content_type);
  3437. EXPECT_EQ(0u, file.content.size());
  3438. }
  3439. } else {
  3440. std::string body;
  3441. content_reader([&](const char *data, size_t data_length) {
  3442. EXPECT_EQ(7U, data_length);
  3443. body.append(data, data_length);
  3444. return true;
  3445. });
  3446. EXPECT_EQ(body, "content");
  3447. res.set_content(body, "text/plain");
  3448. }
  3449. })
  3450. .Put("/content_receiver",
  3451. [&](const Request & /*req*/, Response &res,
  3452. const ContentReader &content_reader) {
  3453. std::string body;
  3454. content_reader([&](const char *data, size_t data_length) {
  3455. body.append(data, data_length);
  3456. return true;
  3457. });
  3458. EXPECT_EQ(body, "content");
  3459. res.set_content(body, "text/plain");
  3460. })
  3461. .Patch("/content_receiver",
  3462. [&](const Request & /*req*/, Response &res,
  3463. const ContentReader &content_reader) {
  3464. std::string body;
  3465. content_reader([&](const char *data, size_t data_length) {
  3466. body.append(data, data_length);
  3467. return true;
  3468. });
  3469. EXPECT_EQ(body, "content");
  3470. res.set_content(body, "text/plain");
  3471. })
  3472. .Post("/query-string-and-body",
  3473. [&](const Request &req, Response & /*res*/) {
  3474. ASSERT_TRUE(req.has_param("key"));
  3475. EXPECT_EQ(req.get_param_value("key"), "value");
  3476. EXPECT_EQ(req.body, "content");
  3477. })
  3478. .Get("/last-request",
  3479. [&](const Request &req, Response & /*res*/) {
  3480. EXPECT_EQ("close", req.get_header_value("Connection"));
  3481. })
  3482. .Get(R"(/redirect/(\d+))",
  3483. [&](const Request &req, Response &res) {
  3484. auto num = std::stoi(req.matches[1]) + 1;
  3485. std::string url = "/redirect/" + std::to_string(num);
  3486. res.set_redirect(url);
  3487. })
  3488. .Post("/binary",
  3489. [&](const Request &req, Response &res) {
  3490. EXPECT_EQ(4U, req.body.size());
  3491. EXPECT_EQ("application/octet-stream",
  3492. req.get_header_value("Content-Type"));
  3493. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3494. res.set_content(req.body, "application/octet-stream");
  3495. })
  3496. .Put("/binary",
  3497. [&](const Request &req, Response &res) {
  3498. EXPECT_EQ(4U, req.body.size());
  3499. EXPECT_EQ("application/octet-stream",
  3500. req.get_header_value("Content-Type"));
  3501. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3502. res.set_content(req.body, "application/octet-stream");
  3503. })
  3504. .Patch("/binary",
  3505. [&](const Request &req, Response &res) {
  3506. EXPECT_EQ(4U, req.body.size());
  3507. EXPECT_EQ("application/octet-stream",
  3508. req.get_header_value("Content-Type"));
  3509. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3510. res.set_content(req.body, "application/octet-stream");
  3511. })
  3512. .Delete("/binary",
  3513. [&](const Request &req, Response &res) {
  3514. EXPECT_EQ(4U, req.body.size());
  3515. EXPECT_EQ("application/octet-stream",
  3516. req.get_header_value("Content-Type"));
  3517. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3518. res.set_content(req.body, "application/octet-stream");
  3519. })
  3520. .Get("/issue1772",
  3521. [&](const Request & /*req*/, Response &res) {
  3522. res.status = 401;
  3523. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3524. })
  3525. .Delete("/issue609",
  3526. [](const httplib::Request &, httplib::Response &res,
  3527. const httplib::ContentReader &) {
  3528. res.set_content("ok", "text/plain");
  3529. })
  3530. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3531. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3532. .Get("/compress",
  3533. [&](const Request & /*req*/, Response &res) {
  3534. res.set_content(
  3535. "12345678901234567890123456789012345678901234567890123456789"
  3536. "01234567890123456789012345678901234567890",
  3537. "text/plain");
  3538. })
  3539. .Get("/compress-with-charset",
  3540. [&](const Request & /*req*/, Response &res) {
  3541. res.set_content(
  3542. "12345678901234567890123456789012345678901234567890123456789"
  3543. "01234567890123456789012345678901234567890",
  3544. "application/json; charset=utf-8");
  3545. })
  3546. .Get("/nocompress",
  3547. [&](const Request & /*req*/, Response &res) {
  3548. res.set_content(
  3549. "12345678901234567890123456789012345678901234567890123456789"
  3550. "01234567890123456789012345678901234567890",
  3551. "application/octet-stream");
  3552. })
  3553. .Post("/compress-multipart",
  3554. [&](const Request &req, Response & /*res*/) {
  3555. EXPECT_EQ(2u, req.form.fields.size());
  3556. ASSERT_TRUE(!req.form.has_field("???"));
  3557. {
  3558. const auto &text = req.form.get_field("key1");
  3559. EXPECT_EQ("test", text);
  3560. }
  3561. {
  3562. const auto &text = req.form.get_field("key2");
  3563. EXPECT_EQ("--abcdefg123", text);
  3564. }
  3565. })
  3566. #endif
  3567. ;
  3568. persons_["john"] = "programmer";
  3569. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3570. svr_.wait_until_ready();
  3571. }
  3572. virtual void TearDown() {
  3573. svr_.stop();
  3574. if (!request_threads_.empty()) {
  3575. std::this_thread::sleep_for(std::chrono::seconds(1));
  3576. for (auto &t : request_threads_) {
  3577. t.join();
  3578. }
  3579. }
  3580. t_.join();
  3581. }
  3582. map<string, string> persons_;
  3583. #ifdef CPPHTTPLIB_SSL_ENABLED
  3584. SSLClient cli_;
  3585. SSLServer svr_;
  3586. #else
  3587. Client cli_;
  3588. Server svr_;
  3589. #endif
  3590. thread t_;
  3591. std::vector<thread> request_threads_;
  3592. };
  3593. TEST_F(ServerTest, GetMethod200) {
  3594. auto res = cli_.Get("/hi");
  3595. ASSERT_TRUE(res);
  3596. EXPECT_EQ("HTTP/1.1", res->version);
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("OK", res->reason);
  3599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3600. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3601. EXPECT_EQ("Hello World!", res->body);
  3602. }
  3603. TEST_F(ServerTest, GetEmptyFile) {
  3604. auto res = cli_.Get("/empty_file");
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::OK_200, res->status);
  3607. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3609. EXPECT_EQ("", res->body);
  3610. }
  3611. TEST_F(ServerTest, GetFileContent) {
  3612. auto res = cli_.Get("/file_content");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3616. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3617. EXPECT_EQ("test.html", res->body);
  3618. }
  3619. TEST_F(ServerTest, GetFileContentWithRange) {
  3620. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3623. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3624. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3625. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3626. EXPECT_EQ("est", res->body);
  3627. }
  3628. TEST_F(ServerTest, GetFileContentWithContentType) {
  3629. auto res = cli_.Get("/file_content_with_content_type");
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3633. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3634. EXPECT_EQ("file\n", res->body);
  3635. }
  3636. TEST_F(ServerTest, GetInvalidFileContent) {
  3637. auto res = cli_.Get("/invalid_file_content");
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3640. }
  3641. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3642. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ("HTTP/1.1", res->version);
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3647. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3648. EXPECT_EQ("Hello World!", res->body);
  3649. }
  3650. TEST_F(ServerTest, GetMethod302) {
  3651. auto res = cli_.Get("/");
  3652. ASSERT_TRUE(res);
  3653. EXPECT_EQ(StatusCode::Found_302, res->status);
  3654. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3655. }
  3656. TEST_F(ServerTest, GetMethod302Redirect) {
  3657. cli_.set_follow_location(true);
  3658. auto res = cli_.Get("/");
  3659. ASSERT_TRUE(res);
  3660. EXPECT_EQ(StatusCode::OK_200, res->status);
  3661. EXPECT_EQ("Hello World!", res->body);
  3662. EXPECT_EQ("/hi", res->location);
  3663. }
  3664. TEST_F(ServerTest, GetMethod404) {
  3665. auto res = cli_.Get("/invalid");
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3668. }
  3669. TEST_F(ServerTest, HeadMethod200) {
  3670. auto res = cli_.Head("/hi");
  3671. ASSERT_TRUE(res);
  3672. EXPECT_EQ(StatusCode::OK_200, res->status);
  3673. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3674. EXPECT_TRUE(res->body.empty());
  3675. }
  3676. TEST_F(ServerTest, HeadMethod200Static) {
  3677. auto res = cli_.Head("/mount/dir/index.html");
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3681. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3682. EXPECT_TRUE(res->body.empty());
  3683. }
  3684. TEST_F(ServerTest, HeadMethod404) {
  3685. auto res = cli_.Head("/invalid");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3688. EXPECT_TRUE(res->body.empty());
  3689. }
  3690. TEST_F(ServerTest, GetMethodPersonJohn) {
  3691. auto res = cli_.Get("/person/john");
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ("programmer", res->body);
  3696. }
  3697. TEST_F(ServerTest, PostMethod1) {
  3698. auto res = cli_.Get("/person/john1");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. res = cli_.Post("/person", "name=john1&note=coder",
  3702. "application/x-www-form-urlencoded");
  3703. ASSERT_TRUE(res);
  3704. ASSERT_EQ(StatusCode::OK_200, res->status);
  3705. res = cli_.Get("/person/john1");
  3706. ASSERT_TRUE(res);
  3707. ASSERT_EQ(StatusCode::OK_200, res->status);
  3708. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3709. ASSERT_EQ("coder", res->body);
  3710. }
  3711. TEST_F(ServerTest, PostMethod2) {
  3712. auto res = cli_.Get("/person/john2");
  3713. ASSERT_TRUE(res);
  3714. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3715. Params params;
  3716. params.emplace("name", "john2");
  3717. params.emplace("note", "coder");
  3718. res = cli_.Post("/person", params);
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::OK_200, res->status);
  3721. res = cli_.Get("/person/john2");
  3722. ASSERT_TRUE(res);
  3723. ASSERT_EQ(StatusCode::OK_200, res->status);
  3724. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3725. ASSERT_EQ("coder", res->body);
  3726. }
  3727. TEST_F(ServerTest, PutMethod3) {
  3728. auto res = cli_.Get("/person/john3");
  3729. ASSERT_TRUE(res);
  3730. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3731. Params params;
  3732. params.emplace("name", "john3");
  3733. params.emplace("note", "coder");
  3734. res = cli_.Put("/person", params);
  3735. ASSERT_TRUE(res);
  3736. ASSERT_EQ(StatusCode::OK_200, res->status);
  3737. res = cli_.Get("/person/john3");
  3738. ASSERT_TRUE(res);
  3739. ASSERT_EQ(StatusCode::OK_200, res->status);
  3740. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3741. ASSERT_EQ("coder", res->body);
  3742. }
  3743. TEST_F(ServerTest, DeleteMethod1) {
  3744. auto res = cli_.Get("/person/john4");
  3745. ASSERT_TRUE(res);
  3746. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3747. Params params;
  3748. params.emplace("name", "john4");
  3749. params.emplace("note", "coder");
  3750. res = cli_.Post("/person", params);
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::OK_200, res->status);
  3753. res = cli_.Get("/person/john4");
  3754. ASSERT_TRUE(res);
  3755. ASSERT_EQ(StatusCode::OK_200, res->status);
  3756. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3757. ASSERT_EQ("coder", res->body);
  3758. Params delete_params;
  3759. delete_params.emplace("name", "john4");
  3760. res = cli_.Delete("/person", delete_params);
  3761. ASSERT_TRUE(res);
  3762. ASSERT_EQ(StatusCode::OK_200, res->status);
  3763. ASSERT_EQ("DELETED", res->body);
  3764. res = cli_.Get("/person/john4");
  3765. ASSERT_TRUE(res);
  3766. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3767. }
  3768. TEST_F(ServerTest, DeleteMethod2) {
  3769. auto res = cli_.Get("/person/john5");
  3770. ASSERT_TRUE(res);
  3771. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3772. Params params;
  3773. params.emplace("name", "john5");
  3774. params.emplace("note", "developer");
  3775. res = cli_.Post("/person", params);
  3776. ASSERT_TRUE(res);
  3777. ASSERT_EQ(StatusCode::OK_200, res->status);
  3778. res = cli_.Get("/person/john5");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(StatusCode::OK_200, res->status);
  3781. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3782. ASSERT_EQ("developer", res->body);
  3783. Params delete_params;
  3784. delete_params.emplace("name", "john5");
  3785. Headers headers;
  3786. headers.emplace("Custom-Header", "test-value");
  3787. res = cli_.Delete("/person", headers, delete_params);
  3788. ASSERT_TRUE(res);
  3789. ASSERT_EQ(StatusCode::OK_200, res->status);
  3790. ASSERT_EQ("DELETED", res->body);
  3791. res = cli_.Get("/person/john5");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3794. }
  3795. TEST_F(ServerTest, DeleteMethod3) {
  3796. auto res = cli_.Get("/person/john6");
  3797. ASSERT_TRUE(res);
  3798. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3799. Params params;
  3800. params.emplace("name", "john6");
  3801. params.emplace("note", "tester");
  3802. res = cli_.Post("/person", params);
  3803. ASSERT_TRUE(res);
  3804. ASSERT_EQ(StatusCode::OK_200, res->status);
  3805. res = cli_.Get("/person/john6");
  3806. ASSERT_TRUE(res);
  3807. ASSERT_EQ(StatusCode::OK_200, res->status);
  3808. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3809. ASSERT_EQ("tester", res->body);
  3810. Params delete_params;
  3811. delete_params.emplace("name", "john6");
  3812. Headers headers;
  3813. headers.emplace("Custom-Header", "test-value");
  3814. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3815. ASSERT_TRUE(res);
  3816. ASSERT_EQ(StatusCode::OK_200, res->status);
  3817. ASSERT_EQ("DELETED", res->body);
  3818. res = cli_.Get("/person/john6");
  3819. ASSERT_TRUE(res);
  3820. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3823. Params params;
  3824. params.emplace("json", JSON_DATA);
  3825. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3826. ASSERT_TRUE(res);
  3827. ASSERT_EQ(StatusCode::OK_200, res->status);
  3828. ASSERT_EQ(JSON_DATA, res->body);
  3829. }
  3830. TEST_F(ServerTest, PostEmptyContent) {
  3831. auto res = cli_.Post("/empty", "", "text/plain");
  3832. ASSERT_TRUE(res);
  3833. ASSERT_EQ(StatusCode::OK_200, res->status);
  3834. ASSERT_EQ("empty", res->body);
  3835. }
  3836. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3837. auto res = cli_.Post("/empty-no-content-type");
  3838. ASSERT_TRUE(res);
  3839. ASSERT_EQ(StatusCode::OK_200, res->status);
  3840. ASSERT_EQ("empty-no-content-type", res->body);
  3841. }
  3842. TEST_F(ServerTest, PostPathOnly) {
  3843. auto res = cli_.Post("/path-only");
  3844. ASSERT_TRUE(res);
  3845. ASSERT_EQ(StatusCode::OK_200, res->status);
  3846. ASSERT_EQ("path-only", res->body);
  3847. }
  3848. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3849. auto res = cli_.Post("/path-headers-only",
  3850. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3851. ASSERT_TRUE(res);
  3852. ASSERT_EQ(StatusCode::OK_200, res->status);
  3853. ASSERT_EQ("path-headers-only", res->body);
  3854. }
  3855. TEST_F(ServerTest, PostLarge) {
  3856. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3857. ASSERT_TRUE(res);
  3858. ASSERT_EQ(StatusCode::OK_200, res->status);
  3859. EXPECT_EQ(LARGE_DATA, res->body);
  3860. }
  3861. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3862. auto res = cli_.Put("/empty-no-content-type");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. ASSERT_EQ("empty-no-content-type", res->body);
  3866. }
  3867. TEST_F(ServerTest, GetMethodDir) {
  3868. auto res = cli_.Get("/dir/");
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::OK_200, res->status);
  3871. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3872. auto body = R"(<html>
  3873. <head>
  3874. </head>
  3875. <body>
  3876. <a href="/dir/test.html">Test</a>
  3877. <a href="/hi">hi</a>
  3878. </body>
  3879. </html>
  3880. )";
  3881. EXPECT_EQ(body, res->body);
  3882. }
  3883. TEST_F(ServerTest, GetMethodDirTest) {
  3884. auto res = cli_.Get("/dir/test.html");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::OK_200, res->status);
  3887. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3888. EXPECT_EQ("test.html", res->body);
  3889. }
  3890. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3891. auto res = cli_.Get("/dir/../dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3895. EXPECT_EQ("test.html", res->body);
  3896. }
  3897. TEST_F(ServerTest, GetMethodInvalidPath) {
  3898. auto res = cli_.Get("/dir/../test.html");
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3901. }
  3902. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3903. auto res = cli_.Get("/../www/dir/test.html");
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3906. }
  3907. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3908. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3909. ASSERT_TRUE(res);
  3910. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3911. }
  3912. TEST_F(ServerTest, GetMethodDirMountTest) {
  3913. auto res = cli_.Get("/mount/dir/test.html");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3917. EXPECT_EQ("test.html", res->body);
  3918. }
  3919. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3920. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("test.html", res->body);
  3925. }
  3926. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3927. auto res = cli_.Get("/mount/dir/../test.html");
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3930. }
  3931. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3932. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3933. ASSERT_TRUE(res);
  3934. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3935. }
  3936. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3937. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3938. ASSERT_TRUE(res);
  3939. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3940. }
  3941. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3942. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3943. ASSERT_TRUE(res);
  3944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3945. }
  3946. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3947. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3950. }
  3951. TEST_F(ServerTest, PostMethod303) {
  3952. auto res = cli_.Post("/1", "body", "text/plain");
  3953. ASSERT_TRUE(res);
  3954. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3955. EXPECT_EQ("/2", res->get_header_value("Location"));
  3956. }
  3957. TEST_F(ServerTest, PostMethod303Redirect) {
  3958. cli_.set_follow_location(true);
  3959. auto res = cli_.Post("/1", "body", "text/plain");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("redirected.", res->body);
  3963. EXPECT_EQ("/2", res->location);
  3964. }
  3965. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3966. auto res = cli_.Get("/dir/test.abcde");
  3967. ASSERT_TRUE(res);
  3968. EXPECT_EQ(StatusCode::OK_200, res->status);
  3969. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3970. EXPECT_EQ("abcde", res->body);
  3971. }
  3972. TEST_F(ServerTest, StaticFileRange) {
  3973. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3974. ASSERT_TRUE(res);
  3975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3976. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(true, res->has_header("Content-Range"));
  3979. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3980. EXPECT_EQ(std::string("cd"), res->body);
  3981. }
  3982. TEST_F(ServerTest, StaticFileRanges) {
  3983. auto res =
  3984. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3987. EXPECT_TRUE(
  3988. res->get_header_value("Content-Type")
  3989. .find(
  3990. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3991. 0);
  3992. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3993. }
  3994. TEST_F(ServerTest, StaticFileRangeHead) {
  3995. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3998. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3999. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4000. EXPECT_EQ(true, res->has_header("Content-Range"));
  4001. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4002. }
  4003. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4004. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4008. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4009. EXPECT_EQ(true, res->has_header("Content-Range"));
  4010. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4011. res->get_header_value("Content-Range"));
  4012. EXPECT_EQ("LAST\n", res->body);
  4013. }
  4014. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4015. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4019. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4020. EXPECT_EQ(true, res->has_header("Content-Range"));
  4021. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4022. }
  4023. TEST_F(ServerTest, StaticFileBigFile) {
  4024. auto res = cli_.Get("/dir/1MB.txt");
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::OK_200, res->status);
  4027. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4028. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4029. }
  4030. TEST_F(ServerTest, InvalidBaseDirMount) {
  4031. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4032. }
  4033. TEST_F(ServerTest, Binary) {
  4034. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4035. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4036. "application/octet-stream");
  4037. ASSERT_TRUE(res);
  4038. ASSERT_EQ(StatusCode::OK_200, res->status);
  4039. ASSERT_EQ(4U, res->body.size());
  4040. res = cli_.Put("/binary", binary.data(), binary.size(),
  4041. "application/octet-stream");
  4042. ASSERT_TRUE(res);
  4043. ASSERT_EQ(StatusCode::OK_200, res->status);
  4044. ASSERT_EQ(4U, res->body.size());
  4045. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4046. "application/octet-stream");
  4047. ASSERT_TRUE(res);
  4048. ASSERT_EQ(StatusCode::OK_200, res->status);
  4049. ASSERT_EQ(4U, res->body.size());
  4050. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4051. "application/octet-stream");
  4052. ASSERT_TRUE(res);
  4053. ASSERT_EQ(StatusCode::OK_200, res->status);
  4054. ASSERT_EQ(4U, res->body.size());
  4055. }
  4056. TEST_F(ServerTest, BinaryString) {
  4057. auto binary = std::string("\x00\x01\x02\x03", 4);
  4058. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ(4U, res->body.size());
  4062. res = cli_.Put("/binary", binary, "application/octet-stream");
  4063. ASSERT_TRUE(res);
  4064. ASSERT_EQ(StatusCode::OK_200, res->status);
  4065. ASSERT_EQ(4U, res->body.size());
  4066. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4067. ASSERT_TRUE(res);
  4068. ASSERT_EQ(StatusCode::OK_200, res->status);
  4069. ASSERT_EQ(4U, res->body.size());
  4070. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ(4U, res->body.size());
  4074. }
  4075. TEST_F(ServerTest, EmptyRequest) {
  4076. auto res = cli_.Get("");
  4077. ASSERT_TRUE(!res);
  4078. EXPECT_EQ(Error::Connection, res.error());
  4079. }
  4080. TEST_F(ServerTest, LongRequest) {
  4081. std::string request;
  4082. for (size_t i = 0; i < 545; i++) {
  4083. request += "/TooLongRequest";
  4084. }
  4085. request += "OK";
  4086. auto res = cli_.Get(request.c_str());
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4089. }
  4090. TEST_F(ServerTest, TooLongRequest) {
  4091. std::string request;
  4092. for (size_t i = 0; i < 546; i++) {
  4093. request += "/TooLongRequest";
  4094. }
  4095. request += "_NG";
  4096. auto start = std::chrono::high_resolution_clock::now();
  4097. cli_.set_keep_alive(true);
  4098. auto res = cli_.Get(request.c_str());
  4099. auto end = std::chrono::high_resolution_clock::now();
  4100. auto elapsed =
  4101. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4102. .count();
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4105. EXPECT_LE(elapsed, 1000);
  4106. EXPECT_EQ("close", res->get_header_value("Connection"));
  4107. EXPECT_FALSE(cli_.is_socket_open());
  4108. }
  4109. TEST_F(ServerTest, AlmostTooLongRequest) {
  4110. // test for #2046 - URI length check shouldn't include other content on req
  4111. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4112. // leading /, space, HTTP/1.1)
  4113. std::string request =
  4114. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4115. auto res = cli_.Get(request.c_str());
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. }
  4119. TEST_F(ServerTest, LongHeader) {
  4120. Request req;
  4121. req.method = "GET";
  4122. req.path = "/hi";
  4123. std::string host_and_port;
  4124. host_and_port += HOST;
  4125. host_and_port += ":";
  4126. host_and_port += std::to_string(PORT);
  4127. req.headers.emplace("Host", host_and_port.c_str());
  4128. req.headers.emplace("Accept", "*/*");
  4129. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4130. req.headers.emplace(
  4131. "Header-Name",
  4132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@");
  4161. auto res = std::make_shared<Response>();
  4162. auto error = Error::Success;
  4163. auto ret = cli_.send(req, *res, error);
  4164. ASSERT_TRUE(ret);
  4165. EXPECT_EQ(StatusCode::OK_200, res->status);
  4166. }
  4167. TEST_F(ServerTest, LongQueryValue) {
  4168. auto start = std::chrono::high_resolution_clock::now();
  4169. cli_.set_keep_alive(true);
  4170. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4171. auto end = std::chrono::high_resolution_clock::now();
  4172. auto elapsed =
  4173. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4174. .count();
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4177. EXPECT_LE(elapsed, 1000);
  4178. EXPECT_EQ("close", res->get_header_value("Connection"));
  4179. EXPECT_FALSE(cli_.is_socket_open());
  4180. }
  4181. TEST_F(ServerTest, TooLongQueryValue) {
  4182. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4183. ASSERT_FALSE(res);
  4184. EXPECT_EQ(Error::Read, res.error());
  4185. }
  4186. TEST_F(ServerTest, TooLongHeader) {
  4187. Request req;
  4188. req.method = "GET";
  4189. req.path = "/hi";
  4190. std::string host_and_port;
  4191. host_and_port += HOST;
  4192. host_and_port += ":";
  4193. host_and_port += std::to_string(PORT);
  4194. req.headers.emplace("Host", host_and_port.c_str());
  4195. req.headers.emplace("Accept", "*/*");
  4196. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4197. req.headers.emplace(
  4198. "Header-Name",
  4199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4227. "@@@@@@@@@@@@@@@@@");
  4228. auto res = std::make_shared<Response>();
  4229. auto error = Error::Success;
  4230. auto ret = cli_.send(req, *res, error);
  4231. ASSERT_TRUE(ret);
  4232. EXPECT_EQ(StatusCode::OK_200, res->status);
  4233. }
  4234. TEST_F(ServerTest, HeaderCountAtLimit) {
  4235. // Test with headers just under the 100 limit
  4236. httplib::Headers headers;
  4237. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4238. // This should keep us just under the 100 header limit
  4239. for (int i = 0; i < 95; i++) {
  4240. std::string name = "X-Test-Header-" + std::to_string(i);
  4241. std::string value = "value" + std::to_string(i);
  4242. headers.emplace(name, value);
  4243. }
  4244. // This should work fine as we're under the limit
  4245. auto res = cli_.Get("/hi", headers);
  4246. EXPECT_TRUE(res);
  4247. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4248. }
  4249. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4250. // Test with many headers to exceed the 100 limit
  4251. httplib::Headers headers;
  4252. // Add 150 headers to definitely exceed the 100 limit
  4253. for (int i = 0; i < 150; i++) {
  4254. std::string name = "X-Test-Header-" + std::to_string(i);
  4255. std::string value = "value" + std::to_string(i);
  4256. headers.emplace(name, value);
  4257. }
  4258. // This should fail due to exceeding header count limit
  4259. cli_.set_keep_alive(true);
  4260. auto res = cli_.Get("/hi", headers);
  4261. // The server should respond with 400 Bad Request
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4264. EXPECT_EQ("close", res->get_header_value("Connection"));
  4265. EXPECT_FALSE(cli_.is_socket_open());
  4266. }
  4267. TEST_F(ServerTest, PercentEncoding) {
  4268. auto res = cli_.Get("/e%6edwith%");
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::OK_200, res->status);
  4271. }
  4272. TEST_F(ServerTest, PercentEncodingUnicode) {
  4273. auto res = cli_.Get("/e%u006edwith%");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::OK_200, res->status);
  4276. }
  4277. TEST_F(ServerTest, InvalidPercentEncoding) {
  4278. auto res = cli_.Get("/%endwith%");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4281. }
  4282. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4283. auto res = cli_.Get("/%uendwith%");
  4284. ASSERT_TRUE(res);
  4285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4286. }
  4287. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4288. auto res = cli_.Get("/hello?aaa=bbb%");
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. TEST_F(ServerTest, PlusSignEncoding) {
  4293. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ("a +b", res->body);
  4297. }
  4298. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4299. // This test simulates a potential DoS attack using many headers
  4300. // to verify our security fix prevents memory exhaustion
  4301. httplib::Headers attack_headers;
  4302. // Attempt to add many headers like an attacker would (200 headers to far
  4303. // exceed limit)
  4304. for (int i = 0; i < 200; i++) {
  4305. std::string name = "X-Attack-Header-" + std::to_string(i);
  4306. std::string value = "attack_payload_" + std::to_string(i);
  4307. attack_headers.emplace(name, value);
  4308. }
  4309. // Try to POST with excessive headers
  4310. cli_.set_keep_alive(true);
  4311. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4312. // Should either fail or return 400 Bad Request due to security limit
  4313. if (res) {
  4314. // If we get a response, it should be 400 Bad Request
  4315. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4316. EXPECT_EQ("close", res->get_header_value("Connection"));
  4317. }
  4318. EXPECT_FALSE(cli_.is_socket_open());
  4319. }
  4320. TEST_F(ServerTest, MultipartFormData) {
  4321. UploadFormDataItems items = {
  4322. {"text1", "text default", "", ""},
  4323. {"text2", "aωb", "", ""},
  4324. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4325. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4326. {"file3", "", "", "application/octet-stream"},
  4327. {"file4", "", "", " application/json tmp-string "}};
  4328. auto res = cli_.Post("/multipart", items);
  4329. ASSERT_TRUE(res);
  4330. EXPECT_EQ(StatusCode::OK_200, res->status);
  4331. }
  4332. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4333. UploadFormDataItems items = {
  4334. {"text", "default text", "", ""},
  4335. {"multi_text1", "aaaaa", "", ""},
  4336. {"multi_text1", "bbbbb", "", ""},
  4337. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4338. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4339. "application/json"},
  4340. };
  4341. auto res = cli_.Post("/multipart/multi_file_values", items);
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. }
  4345. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4346. auto res = cli_.Get("/hi");
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4350. EXPECT_EQ("Hello World!", res->body);
  4351. }
  4352. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4353. Request req;
  4354. req.method = "POST";
  4355. req.path = "/chunked";
  4356. std::string host_and_port;
  4357. host_and_port += HOST;
  4358. host_and_port += ":";
  4359. host_and_port += std::to_string(PORT);
  4360. req.headers.emplace("Host", host_and_port.c_str());
  4361. req.headers.emplace("Accept", "*/*");
  4362. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4363. req.headers.emplace("Content-Type", "text/plain");
  4364. req.headers.emplace("Content-Length", "0");
  4365. req.headers.emplace(
  4366. "Transfer-Encoding",
  4367. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4368. // Client does not chunk, so make a chunked body manually.
  4369. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4370. auto res = std::make_shared<Response>();
  4371. auto error = Error::Success;
  4372. auto ret = cli_.send(req, *res, error);
  4373. ASSERT_TRUE(ret);
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4377. // rather than treat them as valid lengths.
  4378. template <typename ClientT>
  4379. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4380. Request req;
  4381. req.method = "POST";
  4382. req.path = "/chunked";
  4383. std::string host_and_port;
  4384. host_and_port += HOST;
  4385. host_and_port += ":";
  4386. host_and_port += std::to_string(PORT);
  4387. req.headers.emplace("Host", host_and_port.c_str());
  4388. req.headers.emplace("Content-Length", "0");
  4389. req.headers.emplace("Transfer-Encoding", "chunked");
  4390. req.body = body;
  4391. auto res = std::make_shared<Response>();
  4392. auto error = Error::Success;
  4393. ASSERT_TRUE(cli.send(req, *res, error));
  4394. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4395. }
  4396. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4397. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4398. }
  4399. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4400. expect_chunked_body_rejected(
  4401. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4402. }
  4403. TEST_F(ServerTest, GetStreamed2) {
  4404. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4405. ASSERT_TRUE(res);
  4406. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4407. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4408. EXPECT_EQ(true, res->has_header("Content-Range"));
  4409. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4410. EXPECT_EQ(std::string("ab"), res->body);
  4411. }
  4412. TEST_F(ServerTest, GetStreamed) {
  4413. auto res = cli_.Get("/streamed");
  4414. ASSERT_TRUE(res);
  4415. EXPECT_EQ(StatusCode::OK_200, res->status);
  4416. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4417. EXPECT_EQ(std::string("aaabbb"), res->body);
  4418. }
  4419. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4420. auto res =
  4421. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ(false, res->has_header("Content-Length"));
  4425. EXPECT_EQ(false, res->has_header("Content-Range"));
  4426. EXPECT_EQ(std::string("abcdefg"), res->body);
  4427. }
  4428. TEST_F(ServerTest, GetStreamedWithRange1) {
  4429. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4432. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4433. EXPECT_EQ(true, res->has_header("Content-Range"));
  4434. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4435. EXPECT_EQ(std::string("def"), res->body);
  4436. }
  4437. TEST_F(ServerTest, GetStreamedWithRange2) {
  4438. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4441. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4442. EXPECT_EQ(true, res->has_header("Content-Range"));
  4443. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4444. EXPECT_EQ(std::string("bcdefg"), res->body);
  4445. }
  4446. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4447. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4450. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4451. EXPECT_EQ(true, res->has_header("Content-Range"));
  4452. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4453. EXPECT_EQ(std::string("efg"), res->body);
  4454. }
  4455. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4456. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4457. ASSERT_TRUE(res);
  4458. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4459. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4460. EXPECT_EQ(false, res->has_header("Content-Range"));
  4461. EXPECT_EQ(0U, res->body.size());
  4462. }
  4463. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4464. auto res = cli_.Get("/streamed-with-range",
  4465. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4466. "92233720368547758079223372036854775807"}});
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4469. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4470. EXPECT_EQ(false, res->has_header("Content-Range"));
  4471. EXPECT_EQ(0U, res->body.size());
  4472. }
  4473. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4474. auto res = cli_.Get(
  4475. "/with-range",
  4476. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4477. {"Accept-Encoding", ""}});
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4480. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4481. EXPECT_EQ(true, res->has_header("Content-Range"));
  4482. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4483. EXPECT_EQ(std::string("abcdefg"), res->body);
  4484. }
  4485. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4486. auto res = cli_.Get("/with-range", {
  4487. {"Range", "bytes=0-"},
  4488. {"Accept-Encoding", ""},
  4489. });
  4490. ASSERT_TRUE(res);
  4491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4492. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4493. EXPECT_EQ(true, res->has_header("Content-Range"));
  4494. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4495. EXPECT_EQ(std::string("abcdefg"), res->body);
  4496. }
  4497. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4498. auto res =
  4499. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4500. ASSERT_TRUE(res);
  4501. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4502. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4503. EXPECT_EQ(false, res->has_header("Content-Range"));
  4504. EXPECT_EQ(267U, res->body.size());
  4505. // Check that both range contents are present
  4506. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4507. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4508. // Check that Content-Range headers are present for both ranges
  4509. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4510. std::string::npos);
  4511. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4512. std::string::npos);
  4513. }
  4514. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4515. Ranges ranges;
  4516. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4517. ranges.emplace_back(0, -1);
  4518. }
  4519. auto res =
  4520. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4523. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4524. EXPECT_EQ(false, res->has_header("Content-Range"));
  4525. EXPECT_EQ(0U, res->body.size());
  4526. }
  4527. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4528. auto res =
  4529. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4530. ASSERT_TRUE(res);
  4531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4532. EXPECT_EQ(5U, res->body.size());
  4533. // Check that overlapping ranges are coalesced into a single range
  4534. EXPECT_EQ("bcdef", res->body);
  4535. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4536. // Should be single range, not multipart
  4537. EXPECT_TRUE(res->has_header("Content-Range"));
  4538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4539. }
  4540. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4541. auto res =
  4542. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4545. EXPECT_EQ(268U, res->body.size());
  4546. // Check that both range contents are present
  4547. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4548. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4549. // Check that Content-Range headers are present for both ranges
  4550. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4551. std::string::npos);
  4552. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4553. std::string::npos);
  4554. }
  4555. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4556. auto res =
  4557. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4558. ASSERT_TRUE(res);
  4559. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4560. EXPECT_EQ(269U, res->body.size());
  4561. // Check that both duplicate range contents are present
  4562. size_t first_abc = res->body.find("abc\r\n");
  4563. EXPECT_TRUE(first_abc != std::string::npos);
  4564. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4565. EXPECT_TRUE(second_abc != std::string::npos);
  4566. // Check that Content-Range headers are present for both ranges
  4567. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4568. EXPECT_TRUE(first_range != std::string::npos);
  4569. size_t second_range =
  4570. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4571. EXPECT_TRUE(second_range != std::string::npos);
  4572. }
  4573. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4574. auto res = cli_.Get("/streamed-with-range?error",
  4575. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4578. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4579. EXPECT_EQ(false, res->has_header("Content-Range"));
  4580. EXPECT_EQ(0U, res->body.size());
  4581. }
  4582. TEST_F(ServerTest, GetStreamedEndless) {
  4583. uint64_t offset = 0;
  4584. auto res = cli_.Get("/streamed-cancel",
  4585. [&](const char * /*data*/, uint64_t data_length) {
  4586. if (offset < 100) {
  4587. offset += data_length;
  4588. return true;
  4589. }
  4590. return false;
  4591. });
  4592. ASSERT_TRUE(!res);
  4593. EXPECT_EQ(Error::Canceled, res.error());
  4594. }
  4595. TEST_F(ServerTest, ClientStop) {
  4596. std::atomic_size_t count{4};
  4597. std::vector<std::thread> threads;
  4598. for (auto i = count.load(); i != 0; --i) {
  4599. threads.emplace_back([&]() {
  4600. auto res = cli_.Get("/streamed-cancel",
  4601. [&](const char *, uint64_t) { return true; });
  4602. --count;
  4603. ASSERT_TRUE(!res);
  4604. EXPECT_TRUE(res.error() == Error::Canceled ||
  4605. res.error() == Error::Read || res.error() == Error::Write);
  4606. });
  4607. }
  4608. std::this_thread::sleep_for(std::chrono::seconds(2));
  4609. while (count != 0) {
  4610. cli_.stop();
  4611. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4612. }
  4613. for (auto &t : threads) {
  4614. t.join();
  4615. }
  4616. }
  4617. TEST_F(ServerTest, GetWithRange1) {
  4618. auto res = cli_.Get("/with-range", {
  4619. make_range_header({{3, 5}}),
  4620. {"Accept-Encoding", ""},
  4621. });
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4624. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4625. EXPECT_EQ(true, res->has_header("Content-Range"));
  4626. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4627. EXPECT_EQ(std::string("def"), res->body);
  4628. }
  4629. TEST_F(ServerTest, GetWithRange2) {
  4630. auto res = cli_.Get("/with-range", {
  4631. make_range_header({{1, -1}}),
  4632. {"Accept-Encoding", ""},
  4633. });
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4636. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4637. EXPECT_EQ(true, res->has_header("Content-Range"));
  4638. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4639. EXPECT_EQ(std::string("bcdefg"), res->body);
  4640. }
  4641. TEST_F(ServerTest, GetWithRange3) {
  4642. auto res = cli_.Get("/with-range", {
  4643. make_range_header({{0, 0}}),
  4644. {"Accept-Encoding", ""},
  4645. });
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4648. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4649. EXPECT_EQ(true, res->has_header("Content-Range"));
  4650. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4651. EXPECT_EQ(std::string("a"), res->body);
  4652. }
  4653. TEST_F(ServerTest, GetWithRange4) {
  4654. auto res = cli_.Get("/with-range", {
  4655. make_range_header({{-1, 2}}),
  4656. {"Accept-Encoding", ""},
  4657. });
  4658. ASSERT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4660. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4661. EXPECT_EQ(true, res->has_header("Content-Range"));
  4662. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4663. EXPECT_EQ(std::string("fg"), res->body);
  4664. }
  4665. TEST_F(ServerTest, GetWithRange5) {
  4666. auto res = cli_.Get("/with-range", {
  4667. make_range_header({{0, 5}}),
  4668. {"Accept-Encoding", ""},
  4669. });
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4672. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4673. EXPECT_EQ(true, res->has_header("Content-Range"));
  4674. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4675. EXPECT_EQ(std::string("abcdef"), res->body);
  4676. }
  4677. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4678. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4681. }
  4682. TEST_F(ServerTest, GetWithRangeMultipart) {
  4683. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4684. ASSERT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4686. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4687. EXPECT_EQ(false, res->has_header("Content-Range"));
  4688. EXPECT_EQ(267U, res->body.size());
  4689. }
  4690. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4691. auto res =
  4692. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4693. ASSERT_TRUE(res);
  4694. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4695. }
  4696. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4697. auto res = cli_.Get("/with-range-customized-response",
  4698. {{make_range_header({{1, 2}})}});
  4699. ASSERT_TRUE(res);
  4700. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4701. EXPECT_EQ(true, res->has_header("Content-Length"));
  4702. EXPECT_EQ(false, res->has_header("Content-Range"));
  4703. EXPECT_EQ(JSON_DATA, res->body);
  4704. }
  4705. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4706. auto res = cli_.Get("/with-range-customized-response",
  4707. {{make_range_header({{1, 2}, {4, 5}})}});
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4710. EXPECT_EQ(true, res->has_header("Content-Length"));
  4711. EXPECT_EQ(false, res->has_header("Content-Range"));
  4712. EXPECT_EQ(JSON_DATA, res->body);
  4713. }
  4714. TEST_F(ServerTest, Issue1772) {
  4715. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4716. ASSERT_TRUE(res);
  4717. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4718. }
  4719. TEST_F(ServerTest, Issue609) {
  4720. auto res = cli_.Delete("/issue609");
  4721. ASSERT_TRUE(res);
  4722. EXPECT_EQ(StatusCode::OK_200, res->status);
  4723. EXPECT_EQ(std::string("ok"), res->body);
  4724. }
  4725. TEST_F(ServerTest, GetStreamedChunked) {
  4726. auto res = cli_.Get("/streamed-chunked");
  4727. ASSERT_TRUE(res);
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ(std::string("123456789"), res->body);
  4730. }
  4731. TEST_F(ServerTest, GetStreamedChunked2) {
  4732. auto res = cli_.Get("/streamed-chunked2");
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ(std::string("123456789"), res->body);
  4736. }
  4737. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4738. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4739. ASSERT_TRUE(res);
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. EXPECT_EQ(std::string("123456789"), res->body);
  4742. EXPECT_TRUE(res->has_header("Trailer"));
  4743. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4744. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4745. // Trailers are now stored separately from headers (security fix)
  4746. EXPECT_EQ(2U, res->trailers.size());
  4747. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4748. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4749. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4750. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4751. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4752. // Verify trailers are NOT in headers (security verification)
  4753. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4754. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4755. }
  4756. TEST_F(ServerTest, LargeChunkedPost) {
  4757. Request req;
  4758. req.method = "POST";
  4759. req.path = "/large-chunked";
  4760. std::string host_and_port;
  4761. host_and_port += HOST;
  4762. host_and_port += ":";
  4763. host_and_port += std::to_string(PORT);
  4764. req.headers.emplace("Host", host_and_port.c_str());
  4765. req.headers.emplace("Accept", "*/*");
  4766. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4767. req.headers.emplace("Content-Type", "text/plain");
  4768. req.headers.emplace("Content-Length", "0");
  4769. req.headers.emplace("Transfer-Encoding", "chunked");
  4770. std::string long_string(30 * 1024u, 'a');
  4771. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4772. // Attempt to make a large enough post to exceed OS buffers, to test that
  4773. // the server handles short reads if the full chunk data isn't available.
  4774. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4775. auto res = std::make_shared<Response>();
  4776. auto error = Error::Success;
  4777. auto ret = cli_.send(req, *res, error);
  4778. ASSERT_TRUE(ret);
  4779. EXPECT_EQ(StatusCode::OK_200, res->status);
  4780. }
  4781. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4782. auto res = cli_.Get("/remote_addr");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4786. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4787. }
  4788. TEST_F(ServerTest, GetMethodLocalAddr) {
  4789. auto res = cli_.Get("/local_addr");
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::OK_200, res->status);
  4792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4793. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4794. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4795. }
  4796. TEST_F(ServerTest, HTTPResponseSplitting) {
  4797. auto res = cli_.Get("/http_response_splitting");
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::OK_200, res->status);
  4800. }
  4801. TEST_F(ServerTest, SlowRequest) {
  4802. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4803. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4804. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4805. }
  4806. #if 0
  4807. TEST_F(ServerTest, SlowPost) {
  4808. char buffer[64 * 1024];
  4809. memset(buffer, 0x42, sizeof(buffer));
  4810. auto res = cli_.Post(
  4811. "/slowpost", 64 * 1024 * 1024,
  4812. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4813. auto ret = sink.write(buffer, sizeof(buffer));
  4814. EXPECT_TRUE(ret);
  4815. return true;
  4816. },
  4817. "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. }
  4821. TEST_F(ServerTest, SlowPostFail) {
  4822. char buffer[64 * 1024];
  4823. memset(buffer, 0x42, sizeof(buffer));
  4824. cli_.set_write_timeout(std::chrono::seconds(0));
  4825. auto res = cli_.Post(
  4826. "/slowpost", 64 * 1024 * 1024,
  4827. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4828. sink.write(buffer, sizeof(buffer));
  4829. return true;
  4830. },
  4831. "text/plain");
  4832. ASSERT_TRUE(!res);
  4833. EXPECT_EQ(Error::Write, res.error());
  4834. }
  4835. #endif
  4836. TEST_F(ServerTest, Put) {
  4837. auto res = cli_.Put("/put", "PUT", "text/plain");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("PUT", res->body);
  4841. }
  4842. TEST_F(ServerTest, PutWithContentProvider) {
  4843. auto res = cli_.Put(
  4844. "/put", 3,
  4845. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4846. sink.os << "PUT";
  4847. return true;
  4848. },
  4849. "text/plain");
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::OK_200, res->status);
  4852. EXPECT_EQ("PUT", res->body);
  4853. }
  4854. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4855. auto res = cli_.Post(
  4856. "/post", 42,
  4857. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4858. return false;
  4859. },
  4860. "text/plain");
  4861. ASSERT_TRUE(!res);
  4862. EXPECT_EQ(Error::Canceled, res.error());
  4863. }
  4864. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4865. auto res = cli_.Put(
  4866. "/put",
  4867. [](size_t /*offset*/, DataSink &sink) {
  4868. sink.os << "PUT";
  4869. sink.done();
  4870. return true;
  4871. },
  4872. "text/plain");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. EXPECT_EQ("PUT", res->body);
  4876. }
  4877. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4878. auto res = cli_.Post(
  4879. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4880. "text/plain");
  4881. ASSERT_TRUE(!res);
  4882. EXPECT_EQ(Error::Canceled, res.error());
  4883. }
  4884. TEST_F(ServerTest, PostLoopBack) {
  4885. std::string body;
  4886. auto res = cli_.Post(
  4887. "/post-loopback", 9,
  4888. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4889. EXPECT_EQ(9u, length);
  4890. sink.write("123", 3);
  4891. sink.write("456", 3);
  4892. sink.write("789", 3);
  4893. return true;
  4894. },
  4895. "text/plain",
  4896. [&body](const char *data, size_t data_length) {
  4897. body.append(data, data_length);
  4898. return true;
  4899. });
  4900. ASSERT_TRUE(res);
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("123456789", body);
  4903. }
  4904. TEST_F(ServerTest, PutLoopBack) {
  4905. std::string body;
  4906. auto res = cli_.Put(
  4907. "/put-loopback", 9,
  4908. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4909. EXPECT_EQ(9u, length);
  4910. sink.write("123", 3);
  4911. sink.write("456", 3);
  4912. sink.write("789", 3);
  4913. return true;
  4914. },
  4915. "text/plain",
  4916. [&body](const char *data, size_t data_length) {
  4917. body.append(data, data_length);
  4918. return true;
  4919. });
  4920. ASSERT_TRUE(res);
  4921. EXPECT_EQ(StatusCode::OK_200, res->status);
  4922. EXPECT_EQ("123456789", body);
  4923. }
  4924. TEST_F(ServerTest, PatchLoopBack) {
  4925. std::string body;
  4926. auto res = cli_.Patch(
  4927. "/patch-loopback", 9,
  4928. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4929. EXPECT_EQ(9u, length);
  4930. sink.write("123", 3);
  4931. sink.write("456", 3);
  4932. sink.write("789", 3);
  4933. return true;
  4934. },
  4935. "text/plain",
  4936. [&body](const char *data, size_t data_length) {
  4937. body.append(data, data_length);
  4938. return true;
  4939. });
  4940. ASSERT_TRUE(res);
  4941. EXPECT_EQ(StatusCode::OK_200, res->status);
  4942. EXPECT_EQ("123456789", body);
  4943. }
  4944. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4945. std::string body;
  4946. auto res = cli_.Post(
  4947. "/post-loopback",
  4948. [](size_t /*offset*/, DataSink &sink) {
  4949. sink.write("123", 3);
  4950. sink.write("456", 3);
  4951. sink.write("789", 3);
  4952. sink.done();
  4953. return true;
  4954. },
  4955. "text/plain",
  4956. [&body](const char *data, size_t data_length) {
  4957. body.append(data, data_length);
  4958. return true;
  4959. });
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ(StatusCode::OK_200, res->status);
  4962. EXPECT_EQ("123456789", body);
  4963. }
  4964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4965. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4966. cli_.set_compress(true);
  4967. auto res = cli_.Put(
  4968. "/put", 3,
  4969. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4970. sink.os << "PUT";
  4971. return true;
  4972. },
  4973. "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("PUT", res->body);
  4977. }
  4978. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4979. cli_.set_compress(true);
  4980. auto res = cli_.Post(
  4981. "/post", 42,
  4982. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4983. return false;
  4984. },
  4985. "text/plain");
  4986. ASSERT_TRUE(!res);
  4987. EXPECT_EQ(Error::Canceled, res.error());
  4988. }
  4989. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4990. cli_.set_compress(true);
  4991. auto res = cli_.Put(
  4992. "/put",
  4993. [](size_t /*offset*/, DataSink &sink) {
  4994. sink.os << "PUT";
  4995. sink.done();
  4996. return true;
  4997. },
  4998. "text/plain");
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::OK_200, res->status);
  5001. EXPECT_EQ("PUT", res->body);
  5002. }
  5003. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5004. cli_.set_compress(true);
  5005. auto res = cli_.Post(
  5006. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5007. "text/plain");
  5008. ASSERT_TRUE(!res);
  5009. EXPECT_EQ(Error::Canceled, res.error());
  5010. }
  5011. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5012. cli_.set_compress(true);
  5013. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::OK_200, res->status);
  5016. EXPECT_EQ(LARGE_DATA, res->body);
  5017. }
  5018. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5019. #ifdef CPPHTTPLIB_SSL_ENABLED
  5020. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5021. Client cli(s.c_str());
  5022. cli.enable_server_certificate_verification(false);
  5023. #else
  5024. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5025. Client cli(s.c_str());
  5026. #endif
  5027. cli.set_compress(true);
  5028. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5029. ASSERT_TRUE(res);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. EXPECT_EQ(LARGE_DATA, res->body);
  5032. // The compressed size should be less than a 10th of the original. May vary
  5033. // depending on the zlib library.
  5034. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5035. static_cast<uint64_t>(10 * 1024 * 1024));
  5036. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5037. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5038. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5039. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5040. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5041. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5042. #endif
  5043. }
  5044. TEST_F(ServerTest, PutContentWithDeflate) {
  5045. cli_.set_compress(false);
  5046. Headers headers;
  5047. headers.emplace("Content-Encoding", "deflate");
  5048. // PUT in deflate format:
  5049. auto res = cli_.Put("/put", headers,
  5050. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. EXPECT_EQ("PUT", res->body);
  5054. }
  5055. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5056. Headers headers;
  5057. headers.emplace("Accept-Encoding", "gzip, deflate");
  5058. auto res = cli_.Get("/streamed-chunked", headers);
  5059. ASSERT_TRUE(res);
  5060. EXPECT_EQ(StatusCode::OK_200, res->status);
  5061. EXPECT_EQ(std::string("123456789"), res->body);
  5062. }
  5063. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5064. Headers headers;
  5065. headers.emplace("Accept-Encoding", "gzip, deflate");
  5066. auto res = cli_.Get("/streamed-chunked2", headers);
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. EXPECT_EQ(std::string("123456789"), res->body);
  5070. }
  5071. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5072. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5073. ASSERT_TRUE(res);
  5074. EXPECT_EQ(StatusCode::OK_200, res->status);
  5075. }
  5076. TEST(GzipDecompressor, ChunkedDecompression) {
  5077. std::string data;
  5078. for (size_t i = 0; i < 32 * 1024; ++i) {
  5079. data.push_back(static_cast<char>('a' + i % 26));
  5080. }
  5081. std::string compressed_data;
  5082. {
  5083. httplib::detail::gzip_compressor compressor;
  5084. bool result = compressor.compress(
  5085. data.data(), data.size(),
  5086. /*last=*/true,
  5087. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5088. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5089. compressed_data_size);
  5090. return true;
  5091. });
  5092. ASSERT_TRUE(result);
  5093. }
  5094. std::string decompressed_data;
  5095. {
  5096. httplib::detail::gzip_decompressor decompressor;
  5097. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5098. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5099. size_t chunk_size = 130;
  5100. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5101. chunk_begin += chunk_size) {
  5102. size_t current_chunk_size =
  5103. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5104. bool result = decompressor.decompress(
  5105. compressed_data.data() + chunk_begin, current_chunk_size,
  5106. [&](const char *decompressed_data_chunk,
  5107. size_t decompressed_data_chunk_size) {
  5108. decompressed_data.insert(decompressed_data.size(),
  5109. decompressed_data_chunk,
  5110. decompressed_data_chunk_size);
  5111. return true;
  5112. });
  5113. ASSERT_TRUE(result);
  5114. }
  5115. }
  5116. ASSERT_EQ(data, decompressed_data);
  5117. }
  5118. TEST(GzipDecompressor, DeflateDecompression) {
  5119. std::string original_text = "Raw deflate without gzip";
  5120. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5121. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5122. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5123. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5124. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5125. std::string decompressed_data;
  5126. {
  5127. httplib::detail::gzip_decompressor decompressor;
  5128. bool result = decompressor.decompress(
  5129. compressed_data.data(), compressed_data.size(),
  5130. [&](const char *decompressed_data_chunk,
  5131. size_t decompressed_data_chunk_size) {
  5132. decompressed_data.insert(decompressed_data.size(),
  5133. decompressed_data_chunk,
  5134. decompressed_data_chunk_size);
  5135. return true;
  5136. });
  5137. ASSERT_TRUE(result);
  5138. }
  5139. ASSERT_EQ(original_text, decompressed_data);
  5140. }
  5141. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5142. std::string original_text = "Raw deflate without gzip";
  5143. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5144. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5145. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5146. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5147. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5148. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5149. std::string decompressed_data;
  5150. {
  5151. httplib::detail::gzip_decompressor decompressor;
  5152. bool result = decompressor.decompress(
  5153. compressed_data.data(), compressed_data.size(),
  5154. [&](const char *decompressed_data_chunk,
  5155. size_t decompressed_data_chunk_size) {
  5156. decompressed_data.insert(decompressed_data.size(),
  5157. decompressed_data_chunk,
  5158. decompressed_data_chunk_size);
  5159. return true;
  5160. });
  5161. ASSERT_TRUE(result);
  5162. }
  5163. ASSERT_EQ(original_text, decompressed_data);
  5164. }
  5165. #endif
  5166. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5167. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5168. Headers headers;
  5169. headers.emplace("Accept-Encoding", "br");
  5170. auto res = cli_.Get("/streamed-chunked", headers);
  5171. ASSERT_TRUE(res);
  5172. EXPECT_EQ(StatusCode::OK_200, res->status);
  5173. EXPECT_EQ(std::string("123456789"), res->body);
  5174. }
  5175. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5176. Headers headers;
  5177. headers.emplace("Accept-Encoding", "br");
  5178. auto res = cli_.Get("/streamed-chunked2", headers);
  5179. ASSERT_TRUE(res);
  5180. EXPECT_EQ(StatusCode::OK_200, res->status);
  5181. EXPECT_EQ(std::string("123456789"), res->body);
  5182. }
  5183. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5184. cli_.set_compress(true);
  5185. auto res = cli_.Put(
  5186. "/put", 3,
  5187. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5188. sink.os << "PUT";
  5189. return true;
  5190. },
  5191. "text/plain");
  5192. ASSERT_TRUE(res);
  5193. EXPECT_EQ(StatusCode::OK_200, res->status);
  5194. EXPECT_EQ("PUT", res->body);
  5195. }
  5196. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5197. cli_.set_compress(true);
  5198. auto res = cli_.Put(
  5199. "/put",
  5200. [](size_t /*offset*/, DataSink &sink) {
  5201. sink.os << "PUT";
  5202. sink.done();
  5203. return true;
  5204. },
  5205. "text/plain");
  5206. ASSERT_TRUE(res);
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. EXPECT_EQ("PUT", res->body);
  5209. }
  5210. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5211. cli_.set_compress(true);
  5212. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5213. ASSERT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. EXPECT_EQ(LARGE_DATA, res->body);
  5216. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5217. }
  5218. #endif
  5219. TEST_F(ServerTest, Patch) {
  5220. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5221. ASSERT_TRUE(res);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ("PATCH", res->body);
  5224. }
  5225. TEST_F(ServerTest, Delete) {
  5226. auto res = cli_.Delete("/delete");
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. EXPECT_EQ("DELETE", res->body);
  5230. }
  5231. TEST_F(ServerTest, DeleteContentReceiver) {
  5232. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5233. ASSERT_TRUE(res);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. EXPECT_EQ("content", res->body);
  5236. }
  5237. TEST_F(ServerTest, Options) {
  5238. auto res = cli_.Options("*");
  5239. ASSERT_TRUE(res);
  5240. EXPECT_EQ(StatusCode::OK_200, res->status);
  5241. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5242. EXPECT_TRUE(res->body.empty());
  5243. }
  5244. TEST_F(ServerTest, URL) {
  5245. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(StatusCode::OK_200, res->status);
  5248. }
  5249. TEST_F(ServerTest, ArrayParam) {
  5250. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5251. ASSERT_TRUE(res);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, ArrayParamValues) {
  5255. auto res =
  5256. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. }
  5260. TEST_F(ServerTest, NoMultipleHeaders) {
  5261. Headers headers = {{"Content-Length", "5"}};
  5262. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5263. "text/plain");
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, PostContentReceiver) {
  5268. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5269. ASSERT_TRUE(res);
  5270. ASSERT_EQ(StatusCode::OK_200, res->status);
  5271. ASSERT_EQ("content", res->body);
  5272. }
  5273. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5274. UploadFormDataItems items = {
  5275. {"text1", "text default", "", ""},
  5276. {"text2", "aωb", "", ""},
  5277. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5278. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5279. {"file3", "", "", "application/octet-stream"},
  5280. };
  5281. auto res = cli_.Post("/content_receiver", items);
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. }
  5285. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5286. UploadFormDataItems items = {
  5287. {"text1", "text default", "", ""},
  5288. {"text2", "aωb", "", ""},
  5289. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5290. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5291. {"file3", "", "", "application/octet-stream"},
  5292. };
  5293. auto boundary = std::string("+++++");
  5294. std::string body;
  5295. for (const auto &item : items) {
  5296. body += "--" + boundary + "\r\n";
  5297. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5298. if (!item.filename.empty()) {
  5299. body += "; filename=\"" + item.filename + "\"";
  5300. }
  5301. body += "\r\n";
  5302. if (!item.content_type.empty()) {
  5303. body += "Content-Type: " + item.content_type + "\r\n";
  5304. }
  5305. body += "\r\n";
  5306. body += item.content + "\r\n";
  5307. }
  5308. body += "--" + boundary + "--\r\n";
  5309. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5310. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. }
  5314. TEST_F(ServerTest, PostContentReceiverGzip) {
  5315. cli_.set_compress(true);
  5316. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5317. ASSERT_TRUE(res);
  5318. ASSERT_EQ(StatusCode::OK_200, res->status);
  5319. ASSERT_EQ("content", res->body);
  5320. }
  5321. TEST_F(ServerTest, PutContentReceiver) {
  5322. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5323. ASSERT_TRUE(res);
  5324. ASSERT_EQ(StatusCode::OK_200, res->status);
  5325. ASSERT_EQ("content", res->body);
  5326. }
  5327. TEST_F(ServerTest, PatchContentReceiver) {
  5328. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5329. ASSERT_TRUE(res);
  5330. ASSERT_EQ(StatusCode::OK_200, res->status);
  5331. ASSERT_EQ("content", res->body);
  5332. }
  5333. template <typename ClientType>
  5334. void TestWithHeadersAndContentReceiver(
  5335. ClientType &cli,
  5336. std::function<Result(ClientType &, const std::string &, const Headers &,
  5337. const std::string &, const std::string &,
  5338. ContentReceiver, DownloadProgress)>
  5339. request_func) {
  5340. Headers headers;
  5341. headers.emplace("X-Custom-Header", "test-value");
  5342. std::string received_body;
  5343. auto res = request_func(
  5344. cli, "/content_receiver", headers, "content", "application/json",
  5345. [&](const char *data, size_t data_length) {
  5346. received_body.append(data, data_length);
  5347. return true;
  5348. },
  5349. nullptr);
  5350. ASSERT_TRUE(res);
  5351. EXPECT_EQ(StatusCode::OK_200, res->status);
  5352. EXPECT_EQ("content", received_body);
  5353. }
  5354. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5355. #ifdef CPPHTTPLIB_SSL_ENABLED
  5356. using ClientT = SSLClient;
  5357. #else
  5358. using ClientT = Client;
  5359. #endif
  5360. TestWithHeadersAndContentReceiver<ClientT>(
  5361. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5362. const std::string &body, const std::string &content_type,
  5363. ContentReceiver receiver, DownloadProgress progress) {
  5364. return cli.Post(path, headers, body, content_type, receiver, progress);
  5365. });
  5366. }
  5367. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5368. #ifdef CPPHTTPLIB_SSL_ENABLED
  5369. using ClientT = SSLClient;
  5370. #else
  5371. using ClientT = Client;
  5372. #endif
  5373. TestWithHeadersAndContentReceiver<ClientT>(
  5374. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5375. const std::string &body, const std::string &content_type,
  5376. ContentReceiver receiver, DownloadProgress progress) {
  5377. return cli.Put(path, headers, body, content_type, receiver, progress);
  5378. });
  5379. }
  5380. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5381. #ifdef CPPHTTPLIB_SSL_ENABLED
  5382. using ClientT = SSLClient;
  5383. #else
  5384. using ClientT = Client;
  5385. #endif
  5386. TestWithHeadersAndContentReceiver<ClientT>(
  5387. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5388. const std::string &body, const std::string &content_type,
  5389. ContentReceiver receiver, DownloadProgress progress) {
  5390. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5391. });
  5392. }
  5393. template <typename ClientType>
  5394. void TestWithHeadersAndContentReceiverWithProgress(
  5395. ClientType &cli,
  5396. std::function<Result(ClientType &, const std::string &, const Headers &,
  5397. const std::string &, const std::string &,
  5398. ContentReceiver, DownloadProgress)>
  5399. request_func) {
  5400. Headers headers;
  5401. headers.emplace("X-Test-Header", "progress-test");
  5402. std::string received_body;
  5403. auto progress_called = false;
  5404. auto res = request_func(
  5405. cli, "/content_receiver", headers, "content", "text/plain",
  5406. [&](const char *data, size_t data_length) {
  5407. received_body.append(data, data_length);
  5408. return true;
  5409. },
  5410. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5411. progress_called = true;
  5412. return true;
  5413. });
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ("content", received_body);
  5417. EXPECT_TRUE(progress_called);
  5418. }
  5419. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5420. #ifdef CPPHTTPLIB_SSL_ENABLED
  5421. using ClientT = SSLClient;
  5422. #else
  5423. using ClientT = Client;
  5424. #endif
  5425. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5426. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5427. const std::string &body, const std::string &content_type,
  5428. ContentReceiver receiver, DownloadProgress progress) {
  5429. return cli.Post(path, headers, body, content_type, receiver, progress);
  5430. });
  5431. }
  5432. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5433. #ifdef CPPHTTPLIB_SSL_ENABLED
  5434. using ClientT = SSLClient;
  5435. #else
  5436. using ClientT = Client;
  5437. #endif
  5438. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5439. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5440. const std::string &body, const std::string &content_type,
  5441. ContentReceiver receiver, DownloadProgress progress) {
  5442. return cli.Put(path, headers, body, content_type, receiver, progress);
  5443. });
  5444. }
  5445. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5446. #ifdef CPPHTTPLIB_SSL_ENABLED
  5447. using ClientT = SSLClient;
  5448. #else
  5449. using ClientT = Client;
  5450. #endif
  5451. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5452. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5453. const std::string &body, const std::string &content_type,
  5454. ContentReceiver receiver, DownloadProgress progress) {
  5455. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5456. });
  5457. }
  5458. template <typename ClientType>
  5459. void TestWithHeadersAndContentReceiverError(
  5460. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5461. const Headers &, const std::string &,
  5462. const std::string &, ContentReceiver)>
  5463. request_func) {
  5464. Headers headers;
  5465. headers.emplace("X-Error-Test", "true");
  5466. std::string received_body;
  5467. auto receiver_failed = false;
  5468. auto res =
  5469. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5470. [&](const char *data, size_t data_length) {
  5471. received_body.append(data, data_length);
  5472. receiver_failed = true;
  5473. return false;
  5474. });
  5475. ASSERT_FALSE(res);
  5476. EXPECT_TRUE(receiver_failed);
  5477. }
  5478. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5479. #ifdef CPPHTTPLIB_SSL_ENABLED
  5480. using ClientT = SSLClient;
  5481. #else
  5482. using ClientT = Client;
  5483. #endif
  5484. TestWithHeadersAndContentReceiverError<ClientT>(
  5485. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5486. const std::string &body, const std::string &content_type,
  5487. ContentReceiver receiver) {
  5488. return cli.Post(path, headers, body, content_type, receiver);
  5489. });
  5490. }
  5491. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5492. #ifdef CPPHTTPLIB_SSL_ENABLED
  5493. using ClientT = SSLClient;
  5494. #else
  5495. using ClientT = Client;
  5496. #endif
  5497. TestWithHeadersAndContentReceiverError<ClientT>(
  5498. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5499. const std::string &body, const std::string &content_type,
  5500. ContentReceiver receiver) {
  5501. return cli.Put(path, headers, body, content_type, receiver);
  5502. });
  5503. }
  5504. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5505. #ifdef CPPHTTPLIB_SSL_ENABLED
  5506. using ClientT = SSLClient;
  5507. #else
  5508. using ClientT = Client;
  5509. #endif
  5510. TestWithHeadersAndContentReceiverError<ClientT>(
  5511. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5512. const std::string &body, const std::string &content_type,
  5513. ContentReceiver receiver) {
  5514. return cli.Patch(path, headers, body, content_type, receiver);
  5515. });
  5516. }
  5517. TEST_F(ServerTest, PostQueryStringAndBody) {
  5518. auto res =
  5519. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5520. ASSERT_TRUE(res);
  5521. ASSERT_EQ(StatusCode::OK_200, res->status);
  5522. }
  5523. TEST_F(ServerTest, HTTP2Magic) {
  5524. Request req;
  5525. req.method = "PRI";
  5526. req.path = "*";
  5527. req.body = "SM";
  5528. auto res = std::make_shared<Response>();
  5529. auto error = Error::Success;
  5530. auto ret = cli_.send(req, *res, error);
  5531. ASSERT_TRUE(ret);
  5532. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5533. }
  5534. TEST_F(ServerTest, KeepAlive) {
  5535. auto res = cli_.Get("/hi");
  5536. ASSERT_TRUE(res);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5539. EXPECT_EQ("Hello World!", res->body);
  5540. res = cli_.Get("/hi");
  5541. ASSERT_TRUE(res);
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5544. EXPECT_EQ("Hello World!", res->body);
  5545. res = cli_.Get("/hi");
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5549. EXPECT_EQ("Hello World!", res->body);
  5550. res = cli_.Get("/not-exist");
  5551. ASSERT_TRUE(res);
  5552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5553. res = cli_.Post("/empty", "", "text/plain");
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("empty", res->body);
  5558. EXPECT_EQ("close", res->get_header_value("Connection"));
  5559. res = cli_.Post(
  5560. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5561. "text/plain");
  5562. ASSERT_TRUE(res);
  5563. EXPECT_EQ(StatusCode::OK_200, res->status);
  5564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5565. EXPECT_EQ("empty", res->body);
  5566. cli_.set_keep_alive(false);
  5567. res = cli_.Get("/last-request");
  5568. ASSERT_TRUE(res);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. EXPECT_EQ("close", res->get_header_value("Connection"));
  5571. }
  5572. TEST_F(ServerTest, TooManyRedirect) {
  5573. cli_.set_follow_location(true);
  5574. auto res = cli_.Get("/redirect/0");
  5575. ASSERT_TRUE(!res);
  5576. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5577. }
  5578. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5579. Request req;
  5580. req.method = "FOOBAR";
  5581. req.path = "/hi";
  5582. cli_.set_keep_alive(true);
  5583. auto res = cli_.send(req);
  5584. ASSERT_TRUE(res);
  5585. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5586. EXPECT_EQ("close", res->get_header_value("Connection"));
  5587. EXPECT_FALSE(cli_.is_socket_open());
  5588. }
  5589. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5590. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5591. TEST_F(ServerTest, Gzip) {
  5592. Headers headers;
  5593. headers.emplace("Accept-Encoding", "gzip, deflate");
  5594. auto res = cli_.Get("/compress", headers);
  5595. ASSERT_TRUE(res);
  5596. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5598. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5599. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5600. "7890123456789012345678901234567890",
  5601. res->body);
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. }
  5604. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5605. Headers headers;
  5606. headers.emplace("Accept-Encoding", "gzip, deflate");
  5607. auto res = cli_.Get("/compress-with-charset", headers);
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5610. EXPECT_EQ("application/json; charset=utf-8",
  5611. res->get_header_value("Content-Type"));
  5612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5613. "7890123456789012345678901234567890",
  5614. res->body);
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. }
  5617. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5618. Headers headers;
  5619. headers.emplace("Accept-Encoding", "");
  5620. auto res = cli_.Get("/compress", headers);
  5621. ASSERT_TRUE(res);
  5622. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5626. "7890123456789012345678901234567890",
  5627. res->body);
  5628. EXPECT_EQ(StatusCode::OK_200, res->status);
  5629. }
  5630. TEST_F(ServerTest, GzipWithContentReceiver) {
  5631. Headers headers;
  5632. headers.emplace("Accept-Encoding", "gzip, deflate");
  5633. std::string body;
  5634. auto res = cli_.Get("/compress", headers,
  5635. [&](const char *data, uint64_t data_length) {
  5636. EXPECT_EQ(100U, data_length);
  5637. body.append(data, data_length);
  5638. return true;
  5639. });
  5640. ASSERT_TRUE(res);
  5641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5642. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5643. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5644. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5645. "7890123456789012345678901234567890",
  5646. body);
  5647. EXPECT_EQ(StatusCode::OK_200, res->status);
  5648. }
  5649. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5650. Headers headers;
  5651. headers.emplace("Accept-Encoding", "gzip, deflate");
  5652. cli_.set_decompress(false);
  5653. auto res = cli_.Get("/compress", headers);
  5654. ASSERT_TRUE(res);
  5655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5657. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5658. EXPECT_EQ(33U, res->body.size());
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5662. Headers headers;
  5663. headers.emplace("Accept-Encoding", "");
  5664. std::string body;
  5665. auto res = cli_.Get("/compress", headers,
  5666. [&](const char *data, uint64_t data_length) {
  5667. EXPECT_EQ(100U, data_length);
  5668. body.append(data, data_length);
  5669. return true;
  5670. });
  5671. ASSERT_TRUE(res);
  5672. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5673. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5674. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5675. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5676. "7890123456789012345678901234567890",
  5677. body);
  5678. EXPECT_EQ(StatusCode::OK_200, res->status);
  5679. }
  5680. TEST_F(ServerTest, NoGzip) {
  5681. Headers headers;
  5682. headers.emplace("Accept-Encoding", "gzip, deflate");
  5683. auto res = cli_.Get("/nocompress", headers);
  5684. ASSERT_TRUE(res);
  5685. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5686. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5687. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5688. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5689. "7890123456789012345678901234567890",
  5690. res->body);
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. }
  5693. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5694. Headers headers;
  5695. headers.emplace("Accept-Encoding", "gzip, deflate");
  5696. std::string body;
  5697. auto res = cli_.Get("/nocompress", headers,
  5698. [&](const char *data, uint64_t data_length) {
  5699. EXPECT_EQ(100U, data_length);
  5700. body.append(data, data_length);
  5701. return true;
  5702. });
  5703. ASSERT_TRUE(res);
  5704. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5705. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5706. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5707. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5708. "7890123456789012345678901234567890",
  5709. body);
  5710. EXPECT_EQ(StatusCode::OK_200, res->status);
  5711. }
  5712. TEST_F(ServerTest, MultipartFormDataGzip) {
  5713. UploadFormDataItems items = {
  5714. {"key1", "test", "", ""},
  5715. {"key2", "--abcdefg123", "", ""},
  5716. };
  5717. cli_.set_compress(true);
  5718. auto res = cli_.Post("/compress-multipart", items);
  5719. ASSERT_TRUE(res);
  5720. EXPECT_EQ(StatusCode::OK_200, res->status);
  5721. }
  5722. #endif
  5723. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5724. TEST_F(ServerTest, Brotli) {
  5725. Headers headers;
  5726. headers.emplace("Accept-Encoding", "br");
  5727. auto res = cli_.Get("/compress", headers);
  5728. ASSERT_TRUE(res);
  5729. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5731. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5733. "7890123456789012345678901234567890",
  5734. res->body);
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. }
  5737. #endif
  5738. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5739. TEST_F(ServerTest, Zstd) {
  5740. Headers headers;
  5741. headers.emplace("Accept-Encoding", "zstd");
  5742. auto res = cli_.Get("/compress", headers);
  5743. ASSERT_TRUE(res);
  5744. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5745. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5746. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5747. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5748. "7890123456789012345678901234567890",
  5749. res->body);
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. }
  5752. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5753. Headers headers;
  5754. headers.emplace("Accept-Encoding", "");
  5755. auto res = cli_.Get("/compress", headers);
  5756. ASSERT_TRUE(res);
  5757. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5758. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5759. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5760. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5761. "7890123456789012345678901234567890",
  5762. res->body);
  5763. EXPECT_EQ(StatusCode::OK_200, res->status);
  5764. }
  5765. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5766. Headers headers;
  5767. headers.emplace("Accept-Encoding", "zstd");
  5768. std::string body;
  5769. auto res = cli_.Get("/compress", headers,
  5770. [&](const char *data, uint64_t data_length) {
  5771. EXPECT_EQ(100U, data_length);
  5772. body.append(data, data_length);
  5773. return true;
  5774. });
  5775. ASSERT_TRUE(res);
  5776. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5778. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5779. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5780. "7890123456789012345678901234567890",
  5781. body);
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5785. Headers headers;
  5786. headers.emplace("Accept-Encoding", "zstd");
  5787. cli_.set_decompress(false);
  5788. auto res = cli_.Get("/compress", headers);
  5789. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5790. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5791. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5792. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5793. ASSERT_TRUE(res);
  5794. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5795. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. ASSERT_EQ(26U, res->body.size());
  5799. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5800. 0);
  5801. }
  5802. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5803. Headers headers;
  5804. headers.emplace("Accept-Encoding", "");
  5805. std::string body;
  5806. auto res = cli_.Get("/compress", headers,
  5807. [&](const char *data, uint64_t data_length) {
  5808. EXPECT_EQ(100U, data_length);
  5809. body.append(data, data_length);
  5810. return true;
  5811. });
  5812. ASSERT_TRUE(res);
  5813. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5814. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5815. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5816. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5817. "7890123456789012345678901234567890",
  5818. body);
  5819. EXPECT_EQ(StatusCode::OK_200, res->status);
  5820. }
  5821. TEST_F(ServerTest, NoZstd) {
  5822. Headers headers;
  5823. headers.emplace("Accept-Encoding", "zstd");
  5824. auto res = cli_.Get("/nocompress", headers);
  5825. ASSERT_TRUE(res);
  5826. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5827. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5828. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5829. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5830. "7890123456789012345678901234567890",
  5831. res->body);
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. }
  5834. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5835. Headers headers;
  5836. headers.emplace("Accept-Encoding", "zstd");
  5837. std::string body;
  5838. auto res = cli_.Get("/nocompress", headers,
  5839. [&](const char *data, uint64_t data_length) {
  5840. EXPECT_EQ(100U, data_length);
  5841. body.append(data, data_length);
  5842. return true;
  5843. });
  5844. ASSERT_TRUE(res);
  5845. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5846. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5847. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5848. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5849. "7890123456789012345678901234567890",
  5850. body);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. }
  5853. // TODO: How to enable zstd ??
  5854. TEST_F(ServerTest, MultipartFormDataZstd) {
  5855. UploadFormDataItems items = {
  5856. {"key1", "test", "", ""},
  5857. {"key2", "--abcdefg123", "", ""},
  5858. };
  5859. Headers headers;
  5860. headers.emplace("Accept-Encoding", "zstd");
  5861. cli_.set_compress(true);
  5862. auto res = cli_.Post("/compress-multipart", headers, items);
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. }
  5866. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5867. Headers headers;
  5868. headers.emplace("Accept-Encoding", "zstd");
  5869. cli_.set_compress(true);
  5870. auto res = cli_.Put(
  5871. "/put", headers, 3,
  5872. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5873. sink.os << "PUT";
  5874. return true;
  5875. },
  5876. "text/plain");
  5877. ASSERT_TRUE(res);
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("PUT", res->body);
  5880. }
  5881. // Pre-compression logging tests
  5882. TEST_F(ServerTest, PreCompressionLogging) {
  5883. // Test data for compression (matches the actual /compress endpoint content)
  5884. const std::string test_content =
  5885. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5886. "3456789012345678901234567890";
  5887. // Variables to capture logging data
  5888. std::string pre_compression_body;
  5889. std::string pre_compression_content_type;
  5890. std::string pre_compression_content_encoding;
  5891. std::string post_compression_body;
  5892. std::string post_compression_content_type;
  5893. std::string post_compression_content_encoding;
  5894. // Set up pre-compression logger
  5895. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5896. const Response &res) {
  5897. pre_compression_body = res.body;
  5898. pre_compression_content_type = res.get_header_value("Content-Type");
  5899. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5900. });
  5901. // Set up post-compression logger
  5902. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5903. post_compression_body = res.body;
  5904. post_compression_content_type = res.get_header_value("Content-Type");
  5905. post_compression_content_encoding =
  5906. res.get_header_value("Content-Encoding");
  5907. });
  5908. // Test with gzip compression
  5909. Headers headers;
  5910. headers.emplace("Accept-Encoding", "gzip");
  5911. auto res = cli_.Get("/compress", headers);
  5912. // Verify response was compressed
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5916. // Verify pre-compression logger captured uncompressed content
  5917. EXPECT_EQ(test_content, pre_compression_body);
  5918. EXPECT_EQ("text/plain", pre_compression_content_type);
  5919. EXPECT_TRUE(pre_compression_content_encoding
  5920. .empty()); // No encoding header before compression
  5921. // Verify post-compression logger captured compressed content
  5922. EXPECT_NE(test_content,
  5923. post_compression_body); // Should be different after compression
  5924. EXPECT_EQ("text/plain", post_compression_content_type);
  5925. EXPECT_EQ("gzip", post_compression_content_encoding);
  5926. // Verify compressed content is smaller
  5927. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5928. }
  5929. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5930. const std::string test_content =
  5931. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5932. "3456789012345678901234567890";
  5933. std::string pre_compression_body;
  5934. std::string post_compression_body;
  5935. svr_.set_pre_compression_logger(
  5936. [&](const Request & /*req*/, const Response &res) {
  5937. pre_compression_body = res.body;
  5938. });
  5939. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5940. post_compression_body = res.body;
  5941. });
  5942. Headers headers;
  5943. headers.emplace("Accept-Encoding", "br");
  5944. auto res = cli_.Get("/compress", headers);
  5945. ASSERT_TRUE(res);
  5946. EXPECT_EQ(StatusCode::OK_200, res->status);
  5947. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5948. // Verify pre-compression content is uncompressed
  5949. EXPECT_EQ(test_content, pre_compression_body);
  5950. // Verify post-compression content is compressed
  5951. EXPECT_NE(test_content, post_compression_body);
  5952. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5953. }
  5954. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5955. const std::string test_content =
  5956. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5957. "3456789012345678901234567890";
  5958. std::string pre_compression_body;
  5959. std::string post_compression_body;
  5960. svr_.set_pre_compression_logger(
  5961. [&](const Request & /*req*/, const Response &res) {
  5962. pre_compression_body = res.body;
  5963. });
  5964. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5965. post_compression_body = res.body;
  5966. });
  5967. // Request without compression (use /nocompress endpoint)
  5968. Headers headers;
  5969. auto res = cli_.Get("/nocompress", headers);
  5970. ASSERT_TRUE(res);
  5971. EXPECT_EQ(StatusCode::OK_200, res->status);
  5972. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5973. // Pre-compression logger should not be called when no compression is applied
  5974. EXPECT_TRUE(
  5975. pre_compression_body.empty()); // Pre-compression logger not called
  5976. EXPECT_EQ(
  5977. test_content,
  5978. post_compression_body); // Post-compression logger captures final content
  5979. }
  5980. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5981. const std::string test_content =
  5982. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5983. "3456789012345678901234567890";
  5984. std::string pre_compression_body;
  5985. bool pre_logger_called = false;
  5986. // Set only pre-compression logger
  5987. svr_.set_pre_compression_logger(
  5988. [&](const Request & /*req*/, const Response &res) {
  5989. pre_compression_body = res.body;
  5990. pre_logger_called = true;
  5991. });
  5992. Headers headers;
  5993. headers.emplace("Accept-Encoding", "gzip");
  5994. auto res = cli_.Get("/compress", headers);
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5998. // Verify pre-compression logger was called
  5999. EXPECT_TRUE(pre_logger_called);
  6000. EXPECT_EQ(test_content, pre_compression_body);
  6001. }
  6002. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6003. {
  6004. // Test with Expect: 100-continue header - success case
  6005. // Server returns 100 Continue, client sends body, server returns 200 OK
  6006. Request req;
  6007. req.method = "POST";
  6008. req.path = "/post-large";
  6009. req.set_header("Expect", "100-continue");
  6010. req.body = LARGE_DATA;
  6011. Response res;
  6012. auto error = Error::Success;
  6013. cli_.set_keep_alive(true);
  6014. auto ret = cli_.send(req, res, error);
  6015. EXPECT_TRUE(ret);
  6016. EXPECT_EQ(StatusCode::OK_200, res.status);
  6017. EXPECT_EQ(LARGE_DATA, res.body);
  6018. }
  6019. {
  6020. // Test with Expect: 100-continue header - error case
  6021. // Client should not send the body when server returns an error
  6022. Request req;
  6023. req.method = "POST";
  6024. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6025. req.set_header("Expect", "100-continue");
  6026. req.body = LARGE_DATA;
  6027. Response res;
  6028. auto error = Error::Success;
  6029. auto start = std::chrono::high_resolution_clock::now();
  6030. cli_.set_keep_alive(true);
  6031. auto ret = cli_.send(req, res, error);
  6032. auto end = std::chrono::high_resolution_clock::now();
  6033. auto elapsed =
  6034. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6035. .count();
  6036. // With Expect: 100-continue, request completes successfully but with error
  6037. EXPECT_TRUE(ret);
  6038. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6039. EXPECT_EQ("close", res.get_header_value("Connection"));
  6040. EXPECT_FALSE(cli_.is_socket_open());
  6041. EXPECT_LE(elapsed, 2000);
  6042. }
  6043. {
  6044. // Send an extra GET request to ensure error recovery without hanging
  6045. Request req;
  6046. req.method = "GET";
  6047. req.path = "/hi";
  6048. auto start = std::chrono::high_resolution_clock::now();
  6049. auto res = cli_.send(req);
  6050. auto end = std::chrono::high_resolution_clock::now();
  6051. auto elapsed =
  6052. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6053. .count();
  6054. ASSERT_TRUE(res);
  6055. EXPECT_EQ(StatusCode::OK_200, res->status);
  6056. EXPECT_EQ("Hello World!", res->body);
  6057. EXPECT_LE(elapsed, 500);
  6058. }
  6059. }
  6060. TEST(ZstdDecompressor, ChunkedDecompression) {
  6061. std::string data;
  6062. for (size_t i = 0; i < 32 * 1024; ++i) {
  6063. data.push_back(static_cast<char>('a' + i % 26));
  6064. }
  6065. std::string compressed_data;
  6066. {
  6067. httplib::detail::zstd_compressor compressor;
  6068. bool result = compressor.compress(
  6069. data.data(), data.size(),
  6070. /*last=*/true,
  6071. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6072. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6073. compressed_data_size);
  6074. return true;
  6075. });
  6076. ASSERT_TRUE(result);
  6077. }
  6078. std::string decompressed_data;
  6079. {
  6080. httplib::detail::zstd_decompressor decompressor;
  6081. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6082. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6083. size_t chunk_size = 130;
  6084. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6085. chunk_begin += chunk_size) {
  6086. size_t current_chunk_size =
  6087. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6088. bool result = decompressor.decompress(
  6089. compressed_data.data() + chunk_begin, current_chunk_size,
  6090. [&](const char *decompressed_data_chunk,
  6091. size_t decompressed_data_chunk_size) {
  6092. decompressed_data.insert(decompressed_data.size(),
  6093. decompressed_data_chunk,
  6094. decompressed_data_chunk_size);
  6095. return true;
  6096. });
  6097. ASSERT_TRUE(result);
  6098. }
  6099. }
  6100. ASSERT_EQ(data, decompressed_data);
  6101. }
  6102. TEST(ZstdDecompressor, Decompress) {
  6103. std::string original_text = "Compressed with ZSTD";
  6104. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6105. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6106. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6107. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6108. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6109. std::string decompressed_data;
  6110. {
  6111. httplib::detail::zstd_decompressor decompressor;
  6112. bool result = decompressor.decompress(
  6113. compressed_data.data(), compressed_data.size(),
  6114. [&](const char *decompressed_data_chunk,
  6115. size_t decompressed_data_chunk_size) {
  6116. decompressed_data.insert(decompressed_data.size(),
  6117. decompressed_data_chunk,
  6118. decompressed_data_chunk_size);
  6119. return true;
  6120. });
  6121. ASSERT_TRUE(result);
  6122. }
  6123. ASSERT_EQ(original_text, decompressed_data);
  6124. }
  6125. #endif
  6126. // Sends a raw request to a server listening at HOST:PORT.
  6127. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6128. std::string *resp = nullptr) {
  6129. auto error = Error::Success;
  6130. auto client_sock = detail::create_client_socket(
  6131. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6132. /*connection_timeout_sec=*/5, 0,
  6133. /*read_timeout_sec=*/5, 0,
  6134. /*write_timeout_sec=*/5, 0, std::string(), error);
  6135. if (client_sock == INVALID_SOCKET) { return false; }
  6136. auto ret = detail::process_client_socket(
  6137. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6138. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6139. if (req.size() !=
  6140. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6141. return false;
  6142. }
  6143. char buf[512];
  6144. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6145. while (line_reader.getline()) {
  6146. if (resp) { *resp += line_reader.ptr(); }
  6147. }
  6148. return true;
  6149. });
  6150. detail::close_socket(client_sock);
  6151. return ret;
  6152. }
  6153. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6154. Server svr;
  6155. std::string header_value;
  6156. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6157. header_value = req.get_header_value("foo");
  6158. res.set_content("ok", "text/plain");
  6159. });
  6160. thread t = thread([&] { svr.listen(HOST, PORT); });
  6161. auto se = detail::scope_exit([&] {
  6162. svr.stop();
  6163. t.join();
  6164. ASSERT_FALSE(svr.is_running());
  6165. });
  6166. svr.wait_until_ready();
  6167. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6168. // like characters are not treated the same - use vertical tab and escape.
  6169. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6170. "foo: \t \v bar \x1B\t \r\n"
  6171. "Connection: close\r\n"
  6172. "\r\n";
  6173. std::string res;
  6174. ASSERT_TRUE(send_request(5, req, &res));
  6175. EXPECT_EQ(header_value, "");
  6176. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6177. }
  6178. // Sends a raw request and verifies that there isn't a crash or exception.
  6179. static void test_raw_request(const std::string &req,
  6180. std::string *out = nullptr) {
  6181. Server svr;
  6182. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6183. res.set_content("ok", "text/plain");
  6184. });
  6185. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6186. res.set_content("ok", "text/plain");
  6187. });
  6188. svr.Get("/header_field_value_check",
  6189. [&](const Request & /*req*/, Response &res) {
  6190. res.set_content("ok", "text/plain");
  6191. });
  6192. // Server read timeout must be longer than the client read timeout for the
  6193. // bug to reproduce, probably to force the server to process a request
  6194. // without a trailing blank line.
  6195. const time_t client_read_timeout_sec = 1;
  6196. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6197. bool listen_thread_ok = false;
  6198. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6199. auto se = detail::scope_exit([&] {
  6200. svr.stop();
  6201. t.join();
  6202. ASSERT_FALSE(svr.is_running());
  6203. EXPECT_TRUE(listen_thread_ok);
  6204. });
  6205. svr.wait_until_ready();
  6206. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6207. }
  6208. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6209. // A certain header line causes an exception if the header property is parsed
  6210. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6211. test_raw_request(
  6212. "GET /hi HTTP/1.1\r\n"
  6213. " : "
  6214. " "
  6215. " ");
  6216. }
  6217. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6218. // A certain header line causes an exception if the header property *name* is
  6219. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6220. // greedy matcher and requires backtracking when there are a lot of ":"
  6221. // characters.
  6222. // This occurs with libc++ but not libstdc++.
  6223. test_raw_request(
  6224. "GET /hi HTTP/1.1\r\n"
  6225. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6226. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6227. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6228. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6229. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6230. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6231. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6232. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6233. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6234. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6235. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6236. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6237. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6238. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6239. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6240. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6241. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6242. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6243. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6244. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6245. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6246. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6247. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6248. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6249. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6250. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6251. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6252. "&&&%%%");
  6253. }
  6254. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6255. // Make sure this doesn't crash the server.
  6256. // In a previous version of the header line regex, the "\r" rendered the line
  6257. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6258. // a new position where the leading white space ended and the field value
  6259. // began.
  6260. // The crash occurs with libc++ but not libstdc++.
  6261. test_raw_request("GET /hi HTTP/1.1\r\n"
  6262. "a:" +
  6263. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6264. "\r\n"
  6265. "\r\n");
  6266. }
  6267. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6268. std::string out;
  6269. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6270. "Content-Type: text/plain\r\n"
  6271. "Transfer-Encoding: chunked\r\n"
  6272. "\r\n"
  6273. "nothex\r\n",
  6274. &out);
  6275. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6276. }
  6277. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6278. std::string out;
  6279. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6280. "Content-Type: text/plain\r\n"
  6281. "Transfer-Encoding: chunked\r\n"
  6282. "\r\n"
  6283. "3\r\n"
  6284. "xyz\r\n"
  6285. "NaN\r\n",
  6286. &out);
  6287. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6288. }
  6289. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6290. std::string out;
  6291. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6292. "Content-Type: text/plain\r\n"
  6293. "Transfer-Encoding: chunked\r\n"
  6294. "\r\n"
  6295. // Length is too large for 64 bits.
  6296. "1ffffffffffffffff\r\n"
  6297. "xyz\r\n",
  6298. &out);
  6299. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6300. }
  6301. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6302. test_raw_request("GET /hi HTTP/1.1\r\n"
  6303. "Content-Type: text/plain\r\n\r");
  6304. }
  6305. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6306. std::string out;
  6307. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6308. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6309. }
  6310. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6311. Server svr;
  6312. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6313. EXPECT_TRUE(!req.remote_addr.empty());
  6314. });
  6315. thread t = thread([&] { svr.listen(HOST, PORT); });
  6316. auto se = detail::scope_exit([&] {
  6317. svr.stop();
  6318. t.join();
  6319. ASSERT_FALSE(svr.is_running());
  6320. });
  6321. svr.wait_until_ready();
  6322. // Send an invalid request line to trigger Bad Request
  6323. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6324. std::string out;
  6325. ASSERT_TRUE(send_request(5, bad_req, &out));
  6326. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6327. }
  6328. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6329. std::string out;
  6330. std::string request(
  6331. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6332. test_raw_request(request, &out);
  6333. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6334. }
  6335. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6336. std::string out;
  6337. std::string request(
  6338. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6339. test_raw_request(request, &out);
  6340. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6341. }
  6342. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6343. std::string out;
  6344. std::string request(
  6345. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6346. test_raw_request(request, &out);
  6347. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6348. }
  6349. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6350. std::string out;
  6351. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6352. "Test: \r\n\r\n",
  6353. &out);
  6354. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6355. }
  6356. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6357. Server svr;
  6358. std::string x_custom;
  6359. std::string cookie;
  6360. std::string xff;
  6361. std::string x_unicode;
  6362. std::string x_iis;
  6363. svr.Get("/check", [&](const Request &req, Response &res) {
  6364. x_custom = req.get_header_value("X-Custom");
  6365. cookie = req.get_header_value("Cookie");
  6366. xff = req.get_header_value("X-Forwarded-For");
  6367. x_unicode = req.get_header_value("X-Unicode");
  6368. x_iis = req.get_header_value("X-IIS");
  6369. res.set_content("ok", "text/plain");
  6370. });
  6371. thread t = thread([&] { svr.listen(HOST, PORT); });
  6372. auto se = detail::scope_exit([&] {
  6373. svr.stop();
  6374. t.join();
  6375. ASSERT_FALSE(svr.is_running());
  6376. });
  6377. svr.wait_until_ready();
  6378. const std::string req = "GET /check HTTP/1.1\r\n"
  6379. "Host: localhost\r\n"
  6380. "X-Custom: a%0D%0AInjected: b\r\n"
  6381. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6382. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6383. "X-Unicode: %E3%81%82\r\n"
  6384. "X-IIS: %u00E9\r\n"
  6385. "Connection: close\r\n"
  6386. "\r\n";
  6387. std::string res;
  6388. ASSERT_TRUE(send_request(5, req, &res));
  6389. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6390. // Every value must be returned verbatim (wire form), with no decoding.
  6391. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6392. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6393. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6394. EXPECT_EQ("%E3%81%82", x_unicode);
  6395. EXPECT_EQ("%u00E9", x_iis);
  6396. }
  6397. // Applications that previously relied on automatic percent-decoding can
  6398. // reproduce the old behavior by explicitly calling decode_path_component()
  6399. // or, for RFC 3986 conformance, decode_uri_component().
  6400. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6401. Server svr;
  6402. std::string decoded;
  6403. svr.Get("/check", [&](const Request &req, Response &res) {
  6404. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6405. res.set_content("ok", "text/plain");
  6406. });
  6407. thread t = thread([&] { svr.listen(HOST, PORT); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. ASSERT_FALSE(svr.is_running());
  6412. });
  6413. svr.wait_until_ready();
  6414. const std::string req = "GET /check HTTP/1.1\r\n"
  6415. "Host: localhost\r\n"
  6416. "X-Custom: hello%20world\r\n"
  6417. "Connection: close\r\n"
  6418. "\r\n";
  6419. std::string res;
  6420. ASSERT_TRUE(send_request(5, req, &res));
  6421. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6422. EXPECT_EQ("hello world", decoded);
  6423. }
  6424. // Regression test for #2033. Browsers send Referer values that include
  6425. // percent-encoded characters such as %0A inside the URL. Decoding the
  6426. // header value would either trip the post-decode CR/LF/NUL guard (the
  6427. // original bug, returning 400) or, after that guard was relaxed, silently
  6428. // store a literal LF — both unacceptable. The wire form must round-trip.
  6429. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6430. Server svr;
  6431. std::string referer;
  6432. svr.Get("/check", [&](const Request &req, Response &res) {
  6433. referer = req.get_header_value("Referer");
  6434. res.set_content("ok", "text/plain");
  6435. });
  6436. thread t = thread([&] { svr.listen(HOST, PORT); });
  6437. auto se = detail::scope_exit([&] {
  6438. svr.stop();
  6439. t.join();
  6440. ASSERT_FALSE(svr.is_running());
  6441. });
  6442. svr.wait_until_ready();
  6443. const std::string req = "GET /check HTTP/1.1\r\n"
  6444. "Host: localhost\r\n"
  6445. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6446. "Connection: close\r\n"
  6447. "\r\n";
  6448. std::string res;
  6449. ASSERT_TRUE(send_request(5, req, &res));
  6450. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6451. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6452. }
  6453. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6454. Server svr;
  6455. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6456. res.set_header("Cache-Control", "no-cache");
  6457. res.set_chunked_content_provider(
  6458. "text/event-stream", [](size_t offset, DataSink &sink) {
  6459. std::string s = "data:";
  6460. s += std::to_string(offset);
  6461. s += "\n\n";
  6462. auto ret = sink.write(s.data(), s.size());
  6463. EXPECT_TRUE(ret);
  6464. std::this_thread::sleep_for(std::chrono::seconds(1));
  6465. return true;
  6466. });
  6467. });
  6468. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6469. svr.wait_until_ready();
  6470. Client client(HOST, PORT);
  6471. const Headers headers = {{"Accept", "text/event-stream"}};
  6472. auto get_thread = std::thread([&client, &headers]() {
  6473. auto res = client.Get(
  6474. "/events", headers,
  6475. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6476. });
  6477. auto se = detail::scope_exit([&] {
  6478. svr.stop();
  6479. get_thread.join();
  6480. listen_thread.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. // Give GET time to get a few messages.
  6484. std::this_thread::sleep_for(std::chrono::seconds(2));
  6485. }
  6486. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6487. httplib::Server svr;
  6488. svr.Post("/hi",
  6489. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6490. res.status = StatusCode::OK_200;
  6491. });
  6492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6493. svr.wait_until_ready();
  6494. Client cli(HOST, PORT);
  6495. auto res = cli.Post("/hi", "data", "text/plain");
  6496. ASSERT_TRUE(res);
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. svr.stop();
  6499. thread.join();
  6500. ASSERT_FALSE(svr.is_running());
  6501. res = cli.Post("/hi", "data", "text/plain");
  6502. ASSERT_FALSE(res);
  6503. }
  6504. TEST(ServerStopTest, ListenFailure) {
  6505. Server svr;
  6506. auto t = thread([&]() {
  6507. auto ret = svr.listen("????", PORT);
  6508. EXPECT_FALSE(ret);
  6509. });
  6510. svr.wait_until_ready();
  6511. svr.stop();
  6512. t.join();
  6513. }
  6514. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6515. TEST(ServerStopTest, Decommision) {
  6516. Server svr;
  6517. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6518. for (int i = 0; i < 4; i++) {
  6519. auto is_even = !(i % 2);
  6520. std::thread t{[&] {
  6521. try {
  6522. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6523. if (is_even) {
  6524. throw std::runtime_error("Some thing that happens to go wrong.");
  6525. }
  6526. svr.listen(HOST, PORT);
  6527. } catch (...) { svr.decommission(); }
  6528. }};
  6529. svr.wait_until_ready();
  6530. // Server is up
  6531. {
  6532. Client cli(HOST, PORT);
  6533. auto res = cli.Get("/hi");
  6534. if (is_even) {
  6535. EXPECT_FALSE(res);
  6536. } else {
  6537. EXPECT_TRUE(res);
  6538. EXPECT_EQ("hi...", res->body);
  6539. }
  6540. }
  6541. svr.stop();
  6542. t.join();
  6543. // Server is down...
  6544. {
  6545. Client cli(HOST, PORT);
  6546. auto res = cli.Get("/hi");
  6547. EXPECT_FALSE(res);
  6548. }
  6549. }
  6550. }
  6551. #endif
  6552. // Helper function for string body upload progress tests
  6553. template <typename SetupHandler, typename ClientCall>
  6554. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6555. ClientCall &&client_call,
  6556. const string &body) {
  6557. Server svr;
  6558. setup_handler(svr);
  6559. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6560. auto se = detail::scope_exit([&] {
  6561. svr.stop();
  6562. t.join();
  6563. });
  6564. svr.wait_until_ready();
  6565. Client cli(HOST, PORT);
  6566. vector<uint64_t> progress_values;
  6567. bool progress_called = false;
  6568. auto res =
  6569. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6570. progress_values.push_back(current);
  6571. progress_called = true;
  6572. return true;
  6573. });
  6574. ASSERT_TRUE(res);
  6575. EXPECT_EQ(200, res->status);
  6576. EXPECT_TRUE(progress_called);
  6577. }
  6578. TEST(UploadProgressTest, PostStringBodyBasic) {
  6579. TestStringBodyUploadProgress(
  6580. [](Server &svr) {
  6581. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6582. res.set_content("received", "text/plain");
  6583. });
  6584. },
  6585. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6586. return cli.Post("/test", body, "text/plain", progress_callback);
  6587. },
  6588. "test data for upload progress");
  6589. }
  6590. TEST(UploadProgressTest, PutStringBodyBasic) {
  6591. TestStringBodyUploadProgress(
  6592. [](Server &svr) {
  6593. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6594. res.set_content("put received", "text/plain");
  6595. });
  6596. },
  6597. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6598. return cli.Put("/test", body, "text/plain", progress_callback);
  6599. },
  6600. "put test data for upload progress");
  6601. }
  6602. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6603. TestStringBodyUploadProgress(
  6604. [](Server &svr) {
  6605. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6606. res.set_content("patch received", "text/plain");
  6607. });
  6608. },
  6609. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6610. return cli.Patch("/test", body, "text/plain", progress_callback);
  6611. },
  6612. "patch test data for upload progress");
  6613. }
  6614. // Helper function for content provider upload progress tests
  6615. template <typename SetupHandler, typename ClientCall>
  6616. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6617. ClientCall &&client_call) {
  6618. Server svr;
  6619. setup_handler(svr);
  6620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6621. auto se = detail::scope_exit([&] {
  6622. svr.stop();
  6623. t.join();
  6624. });
  6625. svr.wait_until_ready();
  6626. Client cli(HOST, PORT);
  6627. vector<uint64_t> progress_values;
  6628. auto res =
  6629. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6630. progress_values.push_back(current);
  6631. return true;
  6632. });
  6633. ASSERT_TRUE(res);
  6634. EXPECT_EQ(200, res->status);
  6635. EXPECT_FALSE(progress_values.empty());
  6636. }
  6637. TEST(UploadProgressTest, PostContentProviderProgress) {
  6638. TestContentProviderUploadProgress(
  6639. [](Server &svr) {
  6640. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6641. res.set_content("provider received", "text/plain");
  6642. });
  6643. },
  6644. [](Client &cli, UploadProgress progress_callback) {
  6645. return cli.Post(
  6646. "/test", 10,
  6647. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6648. sink.os << "test data";
  6649. return true;
  6650. },
  6651. "text/plain", progress_callback);
  6652. });
  6653. }
  6654. // Helper function for multipart upload progress tests
  6655. template <typename SetupHandler, typename ClientCall>
  6656. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6657. ClientCall &&client_call,
  6658. const string &endpoint) {
  6659. Server svr;
  6660. setup_handler(svr);
  6661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6662. auto se = detail::scope_exit([&] {
  6663. svr.stop();
  6664. t.join();
  6665. });
  6666. svr.wait_until_ready();
  6667. Client cli(HOST, PORT);
  6668. vector<uint64_t> progress_values;
  6669. UploadFormDataItems items = {
  6670. {"field1", "value1", "", ""},
  6671. {"field2", "longer value for progress tracking test", "", ""},
  6672. {"file1", "file content data for upload progress", "test.txt",
  6673. "text/plain"}};
  6674. auto res = client_call(cli, endpoint, items,
  6675. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6676. progress_values.push_back(current);
  6677. return true;
  6678. });
  6679. ASSERT_TRUE(res);
  6680. EXPECT_EQ(200, res->status);
  6681. EXPECT_FALSE(progress_values.empty());
  6682. }
  6683. TEST(UploadProgressTest, PostMultipartProgress) {
  6684. TestMultipartUploadProgress(
  6685. [](Server &svr) {
  6686. svr.Post("/multipart", [](const Request &req, Response &res) {
  6687. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6688. res.set_content("multipart received", "text/plain");
  6689. });
  6690. },
  6691. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6692. UploadProgress progress_callback) {
  6693. return cli.Post(endpoint, items, progress_callback);
  6694. },
  6695. "/multipart");
  6696. }
  6697. // Helper function for basic download progress tests
  6698. template <typename SetupHandler, typename ClientCall>
  6699. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6700. ClientCall &&client_call, const string &endpoint,
  6701. size_t expected_content_size) {
  6702. Server svr;
  6703. setup_handler(svr);
  6704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6705. auto se = detail::scope_exit([&] {
  6706. svr.stop();
  6707. t.join();
  6708. });
  6709. svr.wait_until_ready();
  6710. Client cli(HOST, PORT);
  6711. vector<uint64_t> progress_values;
  6712. auto res = client_call(cli, endpoint,
  6713. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6714. progress_values.push_back(current);
  6715. return true;
  6716. });
  6717. ASSERT_TRUE(res);
  6718. EXPECT_EQ(200, res->status);
  6719. EXPECT_FALSE(progress_values.empty());
  6720. EXPECT_EQ(expected_content_size, res->body.size());
  6721. }
  6722. TEST(DownloadProgressTest, GetBasic) {
  6723. TestBasicDownloadProgress(
  6724. [](Server &svr) {
  6725. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6726. string content(1000, 'D');
  6727. res.set_content(content, "text/plain");
  6728. });
  6729. },
  6730. [](Client &cli, const string &endpoint,
  6731. DownloadProgress progress_callback) {
  6732. return cli.Get(endpoint, progress_callback);
  6733. },
  6734. "/download", 1000u);
  6735. }
  6736. // Helper function for content receiver download progress tests
  6737. template <typename SetupHandler, typename ClientCall>
  6738. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6739. ClientCall &&client_call,
  6740. const string &endpoint,
  6741. size_t expected_content_size) {
  6742. Server svr;
  6743. setup_handler(svr);
  6744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. t.join();
  6748. });
  6749. svr.wait_until_ready();
  6750. Client cli(HOST, PORT);
  6751. vector<uint64_t> progress_values;
  6752. string received_body;
  6753. auto res = client_call(
  6754. cli, endpoint,
  6755. [&](const char *data, size_t data_length) -> bool {
  6756. received_body.append(data, data_length);
  6757. return true;
  6758. },
  6759. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6760. progress_values.push_back(current);
  6761. return true;
  6762. });
  6763. ASSERT_TRUE(res);
  6764. EXPECT_EQ(200, res->status);
  6765. EXPECT_FALSE(progress_values.empty());
  6766. EXPECT_EQ(expected_content_size, received_body.size());
  6767. EXPECT_TRUE(res->body.empty());
  6768. }
  6769. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6770. TestContentReceiverDownloadProgress(
  6771. [](Server &svr) {
  6772. svr.Get("/download-receiver",
  6773. [](const Request & /*req*/, Response &res) {
  6774. string content(2000, 'R');
  6775. res.set_content(content, "text/plain");
  6776. });
  6777. },
  6778. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6779. DownloadProgress progress_callback) {
  6780. return cli.Get(endpoint, content_receiver, progress_callback);
  6781. },
  6782. "/download-receiver", 2000u);
  6783. }
  6784. TEST(StreamingTest, NoContentLengthStreaming) {
  6785. Server svr;
  6786. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6787. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6788. if (offset < 6) {
  6789. sink.os << (offset < 3 ? "a" : "b");
  6790. } else {
  6791. sink.done();
  6792. }
  6793. return true;
  6794. });
  6795. });
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto listen_se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.wait_until_ready();
  6803. Client client(HOST, PORT);
  6804. auto get_thread = std::thread([&client]() {
  6805. std::string s;
  6806. auto res =
  6807. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6808. s += std::string(data, len);
  6809. return true;
  6810. });
  6811. ASSERT_TRUE(res);
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ("aaabbb", s);
  6814. });
  6815. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6816. // Give GET time to get a few messages.
  6817. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6818. }
  6819. TEST(MountTest, Unmount) {
  6820. Server svr;
  6821. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6822. auto se = detail::scope_exit([&] {
  6823. svr.stop();
  6824. listen_thread.join();
  6825. ASSERT_FALSE(svr.is_running());
  6826. });
  6827. svr.wait_until_ready();
  6828. Client cli("localhost", PORT);
  6829. svr.set_mount_point("/mount2", "./www2");
  6830. auto res = cli.Get("/");
  6831. ASSERT_TRUE(res);
  6832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6833. res = cli.Get("/mount2/dir/test.html");
  6834. ASSERT_TRUE(res);
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. svr.set_mount_point("/", "./www");
  6837. res = cli.Get("/dir/");
  6838. ASSERT_TRUE(res);
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. svr.remove_mount_point("/");
  6841. res = cli.Get("/dir/");
  6842. ASSERT_TRUE(res);
  6843. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6844. svr.remove_mount_point("/mount2");
  6845. res = cli.Get("/mount2/dir/test.html");
  6846. ASSERT_TRUE(res);
  6847. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6848. }
  6849. TEST(MountTest, Redicect) {
  6850. Server svr;
  6851. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6852. auto se = detail::scope_exit([&] {
  6853. svr.stop();
  6854. listen_thread.join();
  6855. ASSERT_FALSE(svr.is_running());
  6856. });
  6857. svr.set_mount_point("/", "./www");
  6858. svr.wait_until_ready();
  6859. Client cli("localhost", PORT);
  6860. auto res = cli.Get("/dir/");
  6861. ASSERT_TRUE(res);
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. res = cli.Get("/dir");
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6866. res = cli.Get("/file");
  6867. ASSERT_TRUE(res);
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. res = cli.Get("/file/");
  6870. ASSERT_TRUE(res);
  6871. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6872. cli.set_follow_location(true);
  6873. res = cli.Get("/dir");
  6874. ASSERT_TRUE(res);
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. }
  6877. TEST(MountTest, MultibytesPathName) {
  6878. Server svr;
  6879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6880. auto se = detail::scope_exit([&] {
  6881. svr.stop();
  6882. listen_thread.join();
  6883. ASSERT_FALSE(svr.is_running());
  6884. });
  6885. svr.set_mount_point("/", "./www");
  6886. svr.wait_until_ready();
  6887. Client cli("localhost", PORT);
  6888. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6889. ASSERT_TRUE(res);
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6892. }
  6893. #ifdef _WIN32
  6894. // Issue #2435: mmap::open() must succeed even when another handle holds
  6895. // the file open for writing (e.g. an active log file).
  6896. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6897. const char *path = "mmap_concurrent_writer_test.txt";
  6898. const char *content = "hello";
  6899. {
  6900. std::ofstream f(path, std::ios::binary);
  6901. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6902. }
  6903. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6904. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6905. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6906. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6907. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6908. detail::mmap m(path);
  6909. ASSERT_TRUE(m.is_open());
  6910. EXPECT_EQ(strlen(content), m.size());
  6911. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6912. }
  6913. #endif
  6914. TEST(KeepAliveTest, ReadTimeout) {
  6915. Server svr;
  6916. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6917. std::this_thread::sleep_for(std::chrono::seconds(2));
  6918. res.set_content("a", "text/plain");
  6919. });
  6920. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6921. res.set_content("b", "text/plain");
  6922. });
  6923. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6924. auto se = detail::scope_exit([&] {
  6925. svr.stop();
  6926. listen_thread.join();
  6927. ASSERT_FALSE(svr.is_running());
  6928. });
  6929. svr.wait_until_ready();
  6930. Client cli("localhost", PORT);
  6931. cli.set_keep_alive(true);
  6932. cli.set_read_timeout(std::chrono::seconds(1));
  6933. auto resa = cli.Get("/a");
  6934. ASSERT_FALSE(resa);
  6935. EXPECT_EQ(Error::Read, resa.error());
  6936. auto resb = cli.Get("/b");
  6937. ASSERT_TRUE(resb);
  6938. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6939. EXPECT_EQ("b", resb->body);
  6940. }
  6941. TEST(KeepAliveTest, MaxCount) {
  6942. size_t keep_alive_max_count = 3;
  6943. Server svr;
  6944. svr.set_keep_alive_max_count(keep_alive_max_count);
  6945. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6946. res.set_content("Hello World!", "text/plain");
  6947. });
  6948. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6949. auto se = detail::scope_exit([&] {
  6950. svr.stop();
  6951. listen_thread.join();
  6952. ASSERT_FALSE(svr.is_running());
  6953. });
  6954. svr.wait_until_ready();
  6955. Client cli(HOST, PORT);
  6956. cli.set_keep_alive(true);
  6957. for (size_t i = 0; i < 5; i++) {
  6958. auto result = cli.Get("/hi");
  6959. ASSERT_TRUE(result);
  6960. EXPECT_EQ(StatusCode::OK_200, result->status);
  6961. if (i == keep_alive_max_count - 1) {
  6962. EXPECT_EQ("close", result->get_header_value("Connection"));
  6963. } else {
  6964. EXPECT_FALSE(result->has_header("Connection"));
  6965. }
  6966. }
  6967. }
  6968. TEST(KeepAliveTest, Issue1041) {
  6969. Server svr;
  6970. svr.set_keep_alive_timeout(3);
  6971. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6972. res.set_content("Hello World!", "text/plain");
  6973. });
  6974. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6975. auto se = detail::scope_exit([&] {
  6976. svr.stop();
  6977. listen_thread.join();
  6978. ASSERT_FALSE(svr.is_running());
  6979. });
  6980. svr.wait_until_ready();
  6981. Client cli(HOST, PORT);
  6982. cli.set_keep_alive(true);
  6983. auto result = cli.Get("/hi");
  6984. ASSERT_TRUE(result);
  6985. EXPECT_EQ(StatusCode::OK_200, result->status);
  6986. std::this_thread::sleep_for(std::chrono::seconds(5));
  6987. result = cli.Get("/hi");
  6988. ASSERT_TRUE(result);
  6989. EXPECT_EQ(StatusCode::OK_200, result->status);
  6990. }
  6991. TEST(KeepAliveTest, Issue1959) {
  6992. Server svr;
  6993. svr.set_keep_alive_timeout(5);
  6994. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6995. res.set_content("a", "text/plain");
  6996. });
  6997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. if (!svr.is_running()) return;
  7000. svr.stop();
  7001. listen_thread.join();
  7002. ASSERT_FALSE(svr.is_running());
  7003. });
  7004. svr.wait_until_ready();
  7005. Client cli("localhost", PORT);
  7006. cli.set_keep_alive(true);
  7007. using namespace std::chrono;
  7008. auto start = steady_clock::now();
  7009. cli.Get("/a");
  7010. svr.stop();
  7011. listen_thread.join();
  7012. auto end = steady_clock::now();
  7013. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7014. EXPECT_LT(elapsed, 5000);
  7015. }
  7016. #ifdef CPPHTTPLIB_SSL_ENABLED
  7017. TEST(KeepAliveTest, SSLClientReconnection) {
  7018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7019. ASSERT_TRUE(svr.is_valid());
  7020. svr.set_keep_alive_timeout(1);
  7021. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7022. res.set_content("Hello World!", "text/plain");
  7023. });
  7024. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7025. auto se = detail::scope_exit([&] {
  7026. svr.stop();
  7027. listen_thread.join();
  7028. ASSERT_FALSE(svr.is_running());
  7029. });
  7030. svr.wait_until_ready();
  7031. SSLClient cli(HOST, PORT);
  7032. cli.enable_server_certificate_verification(false);
  7033. cli.set_keep_alive(true);
  7034. auto result = cli.Get("/hi");
  7035. ASSERT_TRUE(result);
  7036. EXPECT_EQ(StatusCode::OK_200, result->status);
  7037. result = cli.Get("/hi");
  7038. ASSERT_TRUE(result);
  7039. EXPECT_EQ(StatusCode::OK_200, result->status);
  7040. std::this_thread::sleep_for(std::chrono::seconds(2));
  7041. // Recoonect
  7042. result = cli.Get("/hi");
  7043. ASSERT_TRUE(result);
  7044. EXPECT_EQ(StatusCode::OK_200, result->status);
  7045. result = cli.Get("/hi");
  7046. ASSERT_TRUE(result);
  7047. EXPECT_EQ(StatusCode::OK_200, result->status);
  7048. }
  7049. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7051. ASSERT_TRUE(svr.is_valid());
  7052. svr.set_keep_alive_timeout(1);
  7053. std::string content = "reconnect";
  7054. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7055. res.set_content("Hello World!", "text/plain");
  7056. });
  7057. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7058. auto se = detail::scope_exit([&] {
  7059. svr.stop();
  7060. listen_thread.join();
  7061. ASSERT_FALSE(svr.is_running());
  7062. });
  7063. svr.wait_until_ready();
  7064. SSLClient cli(HOST, PORT);
  7065. cli.enable_server_certificate_verification(false);
  7066. cli.set_keep_alive(true);
  7067. auto result = cli.Post(
  7068. "/hi", content.size(),
  7069. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7070. sink.write(content.c_str(), content.size());
  7071. return true;
  7072. },
  7073. "text/plain");
  7074. ASSERT_TRUE(result);
  7075. EXPECT_EQ(200, result->status);
  7076. std::this_thread::sleep_for(std::chrono::seconds(2));
  7077. // Recoonect
  7078. result = cli.Post(
  7079. "/hi", content.size(),
  7080. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7081. sink.write(content.c_str(), content.size());
  7082. return true;
  7083. },
  7084. "text/plain");
  7085. ASSERT_TRUE(result);
  7086. EXPECT_EQ(200, result->status);
  7087. result = cli.Post(
  7088. "/hi", content.size(),
  7089. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7090. sink.write(content.c_str(), content.size());
  7091. return true;
  7092. },
  7093. "text/plain");
  7094. ASSERT_TRUE(result);
  7095. EXPECT_EQ(200, result->status);
  7096. }
  7097. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7098. using namespace httplib::tls;
  7099. {
  7100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7101. ASSERT_TRUE(svr.is_valid());
  7102. svr.Get("/sni", [&](const Request &req, Response &res) {
  7103. std::string expected = req.sni();
  7104. EXPECT_EQ(expected, req.get_param_value("expected"));
  7105. res.set_content("ok", "text/plain");
  7106. });
  7107. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7108. auto se = detail::scope_exit([&] {
  7109. svr.stop();
  7110. listen_thread.join();
  7111. ASSERT_FALSE(svr.is_running());
  7112. });
  7113. svr.wait_until_ready();
  7114. {
  7115. SSLClient cli("localhost", PORT);
  7116. cli.enable_server_certificate_verification(false);
  7117. auto res = cli.Get("/sni?expected=localhost");
  7118. ASSERT_TRUE(res);
  7119. }
  7120. {
  7121. SSLClient cli("::1", PORT);
  7122. cli.enable_server_certificate_verification(false);
  7123. auto res = cli.Get("/sni?expected=");
  7124. // NOTE: This may fail if the server is listening on IPv4 only
  7125. // (e.g., when localhost resolves to 127.0.0.1 only)
  7126. if (res) {
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. } else {
  7129. EXPECT_EQ(Error::Connection, res.error());
  7130. }
  7131. }
  7132. }
  7133. }
  7134. #endif
  7135. TEST(ClientProblemDetectionTest, ContentProvider) {
  7136. Server svr;
  7137. size_t content_length = 1024 * 1024;
  7138. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7139. res.set_content_provider(
  7140. content_length, "text/plain",
  7141. [&](size_t offset, size_t length, DataSink &sink) {
  7142. auto out_len = std::min(length, static_cast<size_t>(1024));
  7143. std::string out(out_len, '@');
  7144. sink.write(out.data(), out_len);
  7145. return offset < 4096;
  7146. },
  7147. [](bool success) { ASSERT_FALSE(success); });
  7148. });
  7149. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7150. res.set_content_provider(
  7151. 0, "text/plain",
  7152. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7153. EXPECT_TRUE(false);
  7154. return true;
  7155. },
  7156. [](bool success) { ASSERT_FALSE(success); });
  7157. });
  7158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7159. auto se = detail::scope_exit([&] {
  7160. svr.stop();
  7161. listen_thread.join();
  7162. ASSERT_FALSE(svr.is_running());
  7163. });
  7164. svr.wait_until_ready();
  7165. Client cli("localhost", PORT);
  7166. {
  7167. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7168. size_t /*data_length*/) { return false; });
  7169. ASSERT_FALSE(res);
  7170. }
  7171. {
  7172. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7173. size_t /*data_length*/) { return false; });
  7174. ASSERT_TRUE(res);
  7175. }
  7176. }
  7177. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7178. Server svr;
  7179. svr.set_error_handler([](Request const &, Response &res) -> void {
  7180. res.set_chunked_content_provider(
  7181. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7182. sink.os << "hello";
  7183. sink.os << "world";
  7184. sink.done();
  7185. return true;
  7186. });
  7187. });
  7188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7189. auto se = detail::scope_exit([&] {
  7190. svr.stop();
  7191. listen_thread.join();
  7192. ASSERT_FALSE(svr.is_running());
  7193. });
  7194. svr.wait_until_ready();
  7195. Client cli("localhost", PORT);
  7196. auto res = cli.Get("/");
  7197. ASSERT_TRUE(res);
  7198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7199. EXPECT_EQ("helloworld", res->body);
  7200. }
  7201. TEST(LongPollingTest, ClientCloseDetection) {
  7202. Server svr;
  7203. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7204. res.set_chunked_content_provider(
  7205. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7206. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7207. sink.os << "hello";
  7208. auto count = 10;
  7209. while (count > 0 && sink.is_writable()) {
  7210. this_thread::sleep_for(chrono::milliseconds(10));
  7211. count--;
  7212. }
  7213. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7214. return true;
  7215. });
  7216. });
  7217. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7218. auto se = detail::scope_exit([&] {
  7219. svr.stop();
  7220. listen_thread.join();
  7221. ASSERT_FALSE(svr.is_running());
  7222. });
  7223. svr.wait_until_ready();
  7224. Client cli("localhost", PORT);
  7225. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7226. EXPECT_EQ("hello", string(data, data_length));
  7227. return false; // close the socket immediately.
  7228. });
  7229. ASSERT_FALSE(res);
  7230. }
  7231. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7232. Server svr;
  7233. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7234. res.set_chunked_content_provider(
  7235. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7236. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7237. sink.os << "hello";
  7238. EXPECT_TRUE(sink.os.good());
  7239. // Wait for the client to close the connection
  7240. auto count = 10;
  7241. while (count > 0 && sink.is_writable()) {
  7242. this_thread::sleep_for(chrono::milliseconds(10));
  7243. count--;
  7244. }
  7245. // After client disconnect, write repeatedly until the socket
  7246. // write actually fails (small writes may be absorbed by the
  7247. // kernel buffer)
  7248. std::string chunk(1024, 'x');
  7249. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7250. sink.os << chunk;
  7251. }
  7252. EXPECT_TRUE(sink.os.fail());
  7253. return true;
  7254. });
  7255. });
  7256. auto port = svr.bind_to_any_port("localhost");
  7257. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7258. auto se = detail::scope_exit([&] {
  7259. svr.stop();
  7260. listen_thread.join();
  7261. ASSERT_FALSE(svr.is_running());
  7262. });
  7263. svr.wait_until_ready();
  7264. Client cli("localhost", port);
  7265. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7266. EXPECT_EQ("hello", string(data, data_length));
  7267. return false; // close the socket immediately.
  7268. });
  7269. ASSERT_FALSE(res);
  7270. }
  7271. TEST(GetWithParametersTest, GetWithParameters) {
  7272. Server svr;
  7273. svr.Get("/", [&](const Request &req, Response &) {
  7274. EXPECT_EQ("world", req.get_param_value("hello"));
  7275. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7276. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7277. });
  7278. svr.Get("/params", [&](const Request &req, Response &) {
  7279. EXPECT_EQ("world", req.get_param_value("hello"));
  7280. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7281. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7282. });
  7283. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7284. EXPECT_EQ("resource-id", req.matches[1]);
  7285. EXPECT_EQ("foo", req.get_param_value("param1"));
  7286. EXPECT_EQ("bar", req.get_param_value("param2"));
  7287. });
  7288. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7289. EXPECT_EQ("user-id", req.path_params.at("id"));
  7290. EXPECT_EQ("foo", req.get_param_value("param1"));
  7291. EXPECT_EQ("bar", req.get_param_value("param2"));
  7292. });
  7293. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7294. auto se = detail::scope_exit([&] {
  7295. svr.stop();
  7296. listen_thread.join();
  7297. ASSERT_FALSE(svr.is_running());
  7298. });
  7299. svr.wait_until_ready();
  7300. {
  7301. Client cli(HOST, PORT);
  7302. Params params;
  7303. params.emplace("hello", "world");
  7304. params.emplace("hello2", "world2");
  7305. params.emplace("hello3", "world3");
  7306. auto res = cli.Get("/", params, Headers{});
  7307. ASSERT_TRUE(res);
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. }
  7310. {
  7311. Client cli(HOST, PORT);
  7312. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7313. ASSERT_TRUE(res);
  7314. EXPECT_EQ(StatusCode::OK_200, res->status);
  7315. }
  7316. {
  7317. Client cli(HOST, PORT);
  7318. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7319. ASSERT_TRUE(res);
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. {
  7323. Client cli(HOST, PORT);
  7324. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7325. ASSERT_TRUE(res);
  7326. EXPECT_EQ(StatusCode::OK_200, res->status);
  7327. }
  7328. }
  7329. TEST(GetWithParametersTest, GetWithParameters2) {
  7330. Server svr;
  7331. svr.Get("/", [&](const Request &req, Response &res) {
  7332. auto text = req.get_param_value("hello");
  7333. res.set_content(text, "text/plain");
  7334. });
  7335. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7336. auto se = detail::scope_exit([&] {
  7337. svr.stop();
  7338. listen_thread.join();
  7339. ASSERT_FALSE(svr.is_running());
  7340. });
  7341. svr.wait_until_ready();
  7342. Client cli("localhost", PORT);
  7343. Params params;
  7344. params.emplace("hello", "world");
  7345. std::string body;
  7346. auto res = cli.Get("/", params, Headers{},
  7347. [&](const char *data, size_t data_length) {
  7348. body.append(data, data_length);
  7349. return true;
  7350. });
  7351. ASSERT_TRUE(res);
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. EXPECT_EQ("world", body);
  7354. }
  7355. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7356. auto host = "httpbingo.org";
  7357. auto path = std::string{"/range/32"};
  7358. #ifdef CPPHTTPLIB_SSL_ENABLED
  7359. SSLClient cli(host);
  7360. #else
  7361. Client cli(host);
  7362. #endif
  7363. cli.set_default_headers({make_range_header({{1, 10}})});
  7364. cli.set_connection_timeout(5);
  7365. {
  7366. auto res = cli.Get(path);
  7367. ASSERT_TRUE(res);
  7368. EXPECT_EQ("bcdefghijk", res->body);
  7369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7370. }
  7371. {
  7372. auto res = cli.Get(path);
  7373. ASSERT_TRUE(res);
  7374. EXPECT_EQ("bcdefghijk", res->body);
  7375. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7376. }
  7377. }
  7378. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7379. Server svr;
  7380. svr.set_default_headers({{"Hello", "World"}});
  7381. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7382. res.set_content("ok", "text/plain");
  7383. });
  7384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7385. auto se = detail::scope_exit([&] {
  7386. svr.stop();
  7387. listen_thread.join();
  7388. ASSERT_FALSE(svr.is_running());
  7389. });
  7390. svr.wait_until_ready();
  7391. Client cli("localhost", PORT);
  7392. auto res = cli.Get("/");
  7393. ASSERT_TRUE(res);
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. EXPECT_EQ("ok", res->body);
  7396. EXPECT_EQ("World", res->get_header_value("Hello"));
  7397. }
  7398. #ifdef CPPHTTPLIB_SSL_ENABLED
  7399. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7401. ASSERT_TRUE(svr.is_valid());
  7402. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7403. std::this_thread::sleep_for(std::chrono::seconds(2));
  7404. res.set_content("a", "text/plain");
  7405. });
  7406. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7407. res.set_content("b", "text/plain");
  7408. });
  7409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7410. auto se = detail::scope_exit([&] {
  7411. svr.stop();
  7412. listen_thread.join();
  7413. ASSERT_FALSE(svr.is_running());
  7414. });
  7415. svr.wait_until_ready();
  7416. SSLClient cli("localhost", PORT);
  7417. cli.enable_server_certificate_verification(false);
  7418. cli.set_keep_alive(true);
  7419. cli.set_read_timeout(std::chrono::seconds(1));
  7420. auto resa = cli.Get("/a");
  7421. ASSERT_TRUE(!resa);
  7422. EXPECT_EQ(Error::Read, resa.error());
  7423. auto resb = cli.Get("/b");
  7424. ASSERT_TRUE(resb);
  7425. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7426. EXPECT_EQ("b", resb->body);
  7427. }
  7428. #endif
  7429. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7430. protected:
  7431. ServerTestWithAI_PASSIVE()
  7432. : cli_(HOST, PORT)
  7433. #ifdef CPPHTTPLIB_SSL_ENABLED
  7434. ,
  7435. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7436. #endif
  7437. {
  7438. #ifdef CPPHTTPLIB_SSL_ENABLED
  7439. cli_.enable_server_certificate_verification(false);
  7440. #endif
  7441. }
  7442. virtual void SetUp() {
  7443. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7444. res.set_content("Hello World!", "text/plain");
  7445. });
  7446. t_ = thread(
  7447. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7448. svr_.wait_until_ready();
  7449. }
  7450. virtual void TearDown() {
  7451. svr_.stop();
  7452. t_.join();
  7453. }
  7454. #ifdef CPPHTTPLIB_SSL_ENABLED
  7455. SSLClient cli_;
  7456. SSLServer svr_;
  7457. #else
  7458. Client cli_;
  7459. Server svr_;
  7460. #endif
  7461. thread t_;
  7462. };
  7463. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7464. auto res = cli_.Get("/hi");
  7465. ASSERT_TRUE(res);
  7466. EXPECT_EQ(StatusCode::OK_200, res->status);
  7467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7468. EXPECT_EQ("Hello World!", res->body);
  7469. }
  7470. class ServerUpDownTest : public ::testing::Test {
  7471. protected:
  7472. ServerUpDownTest() : cli_(HOST, PORT) {}
  7473. virtual void SetUp() {
  7474. t_ = thread([&]() {
  7475. svr_.bind_to_any_port(HOST);
  7476. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7477. ASSERT_TRUE(svr_.listen_after_bind());
  7478. });
  7479. svr_.wait_until_ready();
  7480. }
  7481. virtual void TearDown() {
  7482. svr_.stop();
  7483. t_.join();
  7484. }
  7485. Client cli_;
  7486. Server svr_;
  7487. thread t_;
  7488. };
  7489. TEST_F(ServerUpDownTest, QuickStartStop) {
  7490. // Should not crash, especially when run with
  7491. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7492. }
  7493. class PayloadMaxLengthTest : public ::testing::Test {
  7494. protected:
  7495. PayloadMaxLengthTest()
  7496. : cli_(HOST, PORT)
  7497. #ifdef CPPHTTPLIB_SSL_ENABLED
  7498. ,
  7499. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7500. #endif
  7501. {
  7502. #ifdef CPPHTTPLIB_SSL_ENABLED
  7503. cli_.enable_server_certificate_verification(false);
  7504. #endif
  7505. }
  7506. virtual void SetUp() {
  7507. svr_.set_payload_max_length(8);
  7508. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7509. res.set_content("test", "text/plain");
  7510. });
  7511. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7512. svr_.wait_until_ready();
  7513. }
  7514. virtual void TearDown() {
  7515. svr_.stop();
  7516. t_.join();
  7517. }
  7518. #ifdef CPPHTTPLIB_SSL_ENABLED
  7519. SSLClient cli_;
  7520. SSLServer svr_;
  7521. #else
  7522. Client cli_;
  7523. Server svr_;
  7524. #endif
  7525. thread t_;
  7526. };
  7527. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7528. auto res = cli_.Post("/test", "123456789", "text/plain");
  7529. ASSERT_TRUE(res);
  7530. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7531. res = cli_.Post("/test", "12345678", "text/plain");
  7532. ASSERT_TRUE(res);
  7533. EXPECT_EQ(StatusCode::OK_200, res->status);
  7534. }
  7535. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7536. // Test chunked encoding with payload exceeding the 8-byte limit
  7537. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7538. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7539. ASSERT_TRUE(res);
  7540. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7541. }
  7542. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7543. // Test chunked encoding with payload within the 8-byte limit
  7544. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7545. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7546. ASSERT_TRUE(res);
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. }
  7549. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7550. // Test using send_request to send chunked data exceeding payload limit
  7551. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7552. "Host: " +
  7553. std::string(HOST) + ":" + std::to_string(PORT) +
  7554. "\r\n"
  7555. "Transfer-Encoding: chunked\r\n"
  7556. "Connection: close\r\n"
  7557. "\r\n"
  7558. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7559. "0123456789\r\n"
  7560. "0\r\n" // End chunk
  7561. "\r\n";
  7562. std::string response;
  7563. bool result = send_request(1, chunked_request, &response);
  7564. if (!result) {
  7565. // If send_request fails, it might be because the server closed the
  7566. // connection due to payload limit enforcement, which is acceptable
  7567. SUCCEED()
  7568. << "Server rejected oversized chunked request (connection closed)";
  7569. } else {
  7570. // If we got a response, check if it's an error response or connection was
  7571. // closed early Short response length indicates connection was closed due to
  7572. // payload limit
  7573. if (response.length() <= 10) {
  7574. SUCCEED() << "Server closed connection for oversized chunked request";
  7575. } else {
  7576. // Check for error status codes
  7577. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7578. response.find("Payload Too Large") != std::string::npos ||
  7579. response.find("400") != std::string::npos);
  7580. }
  7581. }
  7582. }
  7583. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7584. // Test request without Content-Length header exceeding payload limit
  7585. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7586. "Host: " +
  7587. std::string(HOST) + ":" +
  7588. std::to_string(PORT) +
  7589. "\r\n"
  7590. "Connection: close\r\n"
  7591. "\r\n";
  7592. // Add payload exceeding the 8-byte limit
  7593. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7594. request_without_content_length += large_payload;
  7595. std::string response;
  7596. bool result = send_request(1, request_without_content_length, &response);
  7597. if (!result) {
  7598. // If send_request fails, server likely closed connection due to payload
  7599. // limit
  7600. SUCCEED() << "Server rejected oversized request without Content-Length "
  7601. "(connection closed)";
  7602. } else {
  7603. // Check if server responded with error or closed connection early
  7604. if (response.length() <= 10) {
  7605. SUCCEED() << "Server closed connection for oversized request without "
  7606. "Content-Length";
  7607. } else {
  7608. // Check for error status codes
  7609. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7610. response.find("Payload Too Large") != std::string::npos ||
  7611. response.find("400") != std::string::npos);
  7612. }
  7613. }
  7614. }
  7615. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7616. // Test request without Content-Length header within payload limit
  7617. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7618. "Host: " +
  7619. std::string(HOST) + ":" +
  7620. std::to_string(PORT) +
  7621. "\r\n"
  7622. "Connection: close\r\n"
  7623. "\r\n";
  7624. // Add payload within the 8-byte limit
  7625. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7626. request_without_content_length += small_payload;
  7627. std::string response;
  7628. bool result = send_request(1, request_without_content_length, &response);
  7629. // For requests without Content-Length, the server may have different behavior
  7630. // The key is that it should not reject due to payload limit for small
  7631. // payloads
  7632. if (result) {
  7633. // Check for any HTTP response (success or error, but not connection closed)
  7634. if (response.length() > 10) {
  7635. SUCCEED()
  7636. << "Server processed request without Content-Length within limit";
  7637. } else {
  7638. // Short response might indicate connection closed, which is acceptable
  7639. SUCCEED() << "Server closed connection for request without "
  7640. "Content-Length (acceptable behavior)";
  7641. }
  7642. } else {
  7643. // Connection failure might be due to protocol requirements
  7644. SUCCEED() << "Connection issue with request without Content-Length "
  7645. "(environment-specific)";
  7646. }
  7647. }
  7648. class LargePayloadMaxLengthTest : public ::testing::Test {
  7649. protected:
  7650. LargePayloadMaxLengthTest()
  7651. : cli_(HOST, PORT)
  7652. #ifdef CPPHTTPLIB_SSL_ENABLED
  7653. ,
  7654. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7655. #endif
  7656. {
  7657. #ifdef CPPHTTPLIB_SSL_ENABLED
  7658. cli_.enable_server_certificate_verification(false);
  7659. #endif
  7660. }
  7661. virtual void SetUp() {
  7662. // Set 10MB payload limit
  7663. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7664. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7665. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7666. res.set_content("Large payload test", "text/plain");
  7667. });
  7668. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7669. svr_.wait_until_ready();
  7670. }
  7671. virtual void TearDown() {
  7672. svr_.stop();
  7673. t_.join();
  7674. }
  7675. #ifdef CPPHTTPLIB_SSL_ENABLED
  7676. SSLClient cli_;
  7677. SSLServer svr_;
  7678. #else
  7679. Client cli_;
  7680. Server svr_;
  7681. #endif
  7682. thread t_;
  7683. };
  7684. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7685. // Test chunked encoding with payload within 10MB limit
  7686. std::string medium_payload(5 * 1024 * 1024,
  7687. 'A'); // 5MB payload, within 10MB limit
  7688. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7689. ASSERT_TRUE(res);
  7690. EXPECT_EQ(StatusCode::OK_200, res->status);
  7691. }
  7692. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7693. // Test chunked encoding with payload exceeding 10MB limit
  7694. std::string large_payload(12 * 1024 * 1024,
  7695. 'B'); // 12MB payload, exceeds 10MB limit
  7696. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7697. // Server may either return 413 or close the connection
  7698. if (res) {
  7699. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7700. } else {
  7701. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7702. }
  7703. }
  7704. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7705. // Test request without Content-Length header within 10MB limit
  7706. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7707. "Host: " +
  7708. std::string(HOST) + ":" +
  7709. std::to_string(PORT) +
  7710. "\r\n"
  7711. "Connection: close\r\n"
  7712. "\r\n";
  7713. // Add 1MB payload (within 10MB limit)
  7714. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7715. request_without_content_length += medium_payload;
  7716. std::string response;
  7717. bool result = send_request(5, request_without_content_length, &response);
  7718. if (result) {
  7719. // Should get a proper HTTP response for payloads within limit
  7720. if (response.length() > 10) {
  7721. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7722. "10MB limit";
  7723. } else {
  7724. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7725. "Content-Length)";
  7726. }
  7727. } else {
  7728. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7729. }
  7730. }
  7731. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7732. // Test request without Content-Length header exceeding 10MB limit
  7733. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7734. "Host: " +
  7735. std::string(HOST) + ":" +
  7736. std::to_string(PORT) +
  7737. "\r\n"
  7738. "Connection: close\r\n"
  7739. "\r\n";
  7740. // Add 12MB payload (exceeds 10MB limit)
  7741. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7742. request_without_content_length += large_payload;
  7743. std::string response;
  7744. bool result = send_request(10, request_without_content_length, &response);
  7745. if (!result) {
  7746. // Server should close connection due to payload limit
  7747. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7748. "(connection closed)";
  7749. } else {
  7750. // Check for error response
  7751. if (response.length() <= 10) {
  7752. SUCCEED()
  7753. << "Server closed connection for 12MB request exceeding 10MB limit";
  7754. } else {
  7755. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7756. response.find("Payload Too Large") != std::string::npos ||
  7757. response.find("400") != std::string::npos);
  7758. }
  7759. }
  7760. }
  7761. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7762. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7763. // path.
  7764. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7765. Server svr;
  7766. const size_t LIMIT = 64 * 1024; // 64KB
  7767. svr.set_payload_max_length(LIMIT);
  7768. size_t total = 0;
  7769. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7770. const ContentReader &content_reader) {
  7771. content_reader([&](const char * /*data*/, size_t len) {
  7772. total += len;
  7773. return true;
  7774. });
  7775. res.status = 200;
  7776. res.set_content("stream_ok", "text/plain");
  7777. });
  7778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7779. auto se = detail::scope_exit([&] {
  7780. svr.stop();
  7781. thread.join();
  7782. ASSERT_FALSE(svr.is_running());
  7783. });
  7784. svr.wait_until_ready();
  7785. // Prepare 256KB raw data and gzip-compress it
  7786. std::string raw(256 * 1024, 'A');
  7787. std::string gz;
  7788. {
  7789. z_stream zs{};
  7790. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7791. Z_DEFAULT_STRATEGY);
  7792. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7793. zs.avail_in = static_cast<uInt>(raw.size());
  7794. char outbuf[4096];
  7795. int ret;
  7796. do {
  7797. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7798. zs.avail_out = sizeof(outbuf);
  7799. ret = deflate(&zs, Z_FINISH);
  7800. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7801. } while (ret != Z_STREAM_END);
  7802. deflateEnd(&zs);
  7803. }
  7804. Client cli(HOST, PORT);
  7805. cli.set_connection_timeout(std::chrono::seconds(5));
  7806. Headers headers = {{"Content-Encoding", "gzip"}};
  7807. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7808. "application/octet-stream");
  7809. ASSERT_TRUE(res);
  7810. // Server must reject oversized decompressed payloads with 413.
  7811. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7812. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7813. EXPECT_LE(total, LIMIT);
  7814. }
  7815. #endif
  7816. // Regression test for DoS vulnerability: a malicious server sending a response
  7817. // without Content-Length header must not cause unbounded memory consumption on
  7818. // the client side. The client should stop reading after a reasonable limit,
  7819. // similar to the server-side set_payload_max_length protection.
  7820. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7821. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7822. #ifndef _WIN32
  7823. signal(SIGPIPE, SIG_IGN);
  7824. #endif
  7825. auto server_thread = std::thread([] {
  7826. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7827. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7828. default_socket_options(srv);
  7829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7831. sockaddr_in addr{};
  7832. addr.sin_family = AF_INET;
  7833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7835. int opt = 1;
  7836. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7837. #ifdef _WIN32
  7838. reinterpret_cast<const char *>(&opt),
  7839. #else
  7840. &opt,
  7841. #endif
  7842. sizeof(opt));
  7843. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7844. ::listen(srv, 1);
  7845. sockaddr_in cli_addr{};
  7846. socklen_t cli_len = sizeof(cli_addr);
  7847. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7848. if (cli != INVALID_SOCKET) {
  7849. char buf[4096];
  7850. ::recv(cli, buf, sizeof(buf), 0);
  7851. // Malicious response: no Content-Length, no chunked encoding
  7852. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7853. "Connection: close\r\n"
  7854. "\r\n";
  7855. ::send(cli,
  7856. #ifdef _WIN32
  7857. static_cast<const char *>(response_header.c_str()),
  7858. static_cast<int>(response_header.size()),
  7859. #else
  7860. response_header.c_str(), response_header.size(),
  7861. #endif
  7862. 0);
  7863. // Send 10MB of data
  7864. std::string chunk(64 * 1024, 'A');
  7865. size_t total_sent = 0;
  7866. while (total_sent < MALICIOUS_DATA_SIZE) {
  7867. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7868. auto sent = ::send(cli,
  7869. #ifdef _WIN32
  7870. static_cast<const char *>(chunk.c_str()),
  7871. static_cast<int>(to_send),
  7872. #else
  7873. chunk.c_str(), to_send,
  7874. #endif
  7875. 0);
  7876. if (sent <= 0) break;
  7877. total_sent += static_cast<size_t>(sent);
  7878. }
  7879. detail::close_socket(cli);
  7880. }
  7881. detail::close_socket(srv);
  7882. });
  7883. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7884. size_t total_read = 0;
  7885. {
  7886. Client cli("127.0.0.1", PORT + 2);
  7887. cli.set_read_timeout(5, 0);
  7888. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7889. auto stream = cli.open_stream("GET", "/malicious");
  7890. ASSERT_TRUE(stream.is_valid());
  7891. char buffer[64 * 1024];
  7892. ssize_t n;
  7893. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7894. total_read += static_cast<size_t>(n);
  7895. }
  7896. } // StreamHandle and Client destroyed here, closing the socket
  7897. server_thread.join();
  7898. // With set_payload_max_length, the client must stop reading before consuming
  7899. // all 10MB. The read loop should be cut off at or near the configured limit.
  7900. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7901. << "Client read " << total_read << " bytes, exceeding the configured "
  7902. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7903. }
  7904. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7905. // the entire response body without truncation.
  7906. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7907. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7908. #ifndef _WIN32
  7909. signal(SIGPIPE, SIG_IGN);
  7910. #endif
  7911. auto server_thread = std::thread([] {
  7912. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7913. default_socket_options(srv);
  7914. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7915. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7916. sockaddr_in addr{};
  7917. addr.sin_family = AF_INET;
  7918. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7919. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7920. int opt = 1;
  7921. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7922. #ifdef _WIN32
  7923. reinterpret_cast<const char *>(&opt),
  7924. #else
  7925. &opt,
  7926. #endif
  7927. sizeof(opt));
  7928. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7929. ::listen(srv, 1);
  7930. sockaddr_in cli_addr{};
  7931. socklen_t cli_len = sizeof(cli_addr);
  7932. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7933. if (cli != INVALID_SOCKET) {
  7934. char buf[4096];
  7935. ::recv(cli, buf, sizeof(buf), 0);
  7936. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7937. "Connection: close\r\n"
  7938. "\r\n";
  7939. ::send(cli,
  7940. #ifdef _WIN32
  7941. static_cast<const char *>(response_header.c_str()),
  7942. static_cast<int>(response_header.size()),
  7943. #else
  7944. response_header.c_str(), response_header.size(),
  7945. #endif
  7946. 0);
  7947. std::string chunk(64 * 1024, 'A');
  7948. size_t total_sent = 0;
  7949. while (total_sent < DATA_SIZE) {
  7950. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7951. auto sent = ::send(cli,
  7952. #ifdef _WIN32
  7953. static_cast<const char *>(chunk.c_str()),
  7954. static_cast<int>(to_send),
  7955. #else
  7956. chunk.c_str(), to_send,
  7957. #endif
  7958. 0);
  7959. if (sent <= 0) break;
  7960. total_sent += static_cast<size_t>(sent);
  7961. }
  7962. #ifdef _WIN32
  7963. ::shutdown(cli, SD_SEND);
  7964. #else
  7965. ::shutdown(cli, SHUT_WR);
  7966. #endif
  7967. // Drain until the client closes its end, ensuring all data is delivered
  7968. char drain[1024];
  7969. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7970. detail::close_socket(cli);
  7971. }
  7972. detail::close_socket(srv);
  7973. });
  7974. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7975. size_t total_read = 0;
  7976. {
  7977. Client cli("127.0.0.1", PORT + 2);
  7978. cli.set_read_timeout(5, 0);
  7979. cli.set_payload_max_length(0); // 0 means no limit
  7980. auto stream = cli.open_stream("GET", "/data");
  7981. ASSERT_TRUE(stream.is_valid());
  7982. char buffer[64 * 1024];
  7983. ssize_t n;
  7984. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7985. total_read += static_cast<size_t>(n);
  7986. }
  7987. }
  7988. server_thread.join();
  7989. EXPECT_EQ(total_read, DATA_SIZE)
  7990. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7991. << " bytes without truncation, but only read " << total_read << " bytes.";
  7992. }
  7993. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7994. // enormous Content-Length must not cause the client to pre-allocate a huge
  7995. // response body buffer. The reservation is capped at payload_max_length_, and
  7996. // the read itself fails when the body exceeds the limit.
  7997. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7998. #ifndef _WIN32
  7999. signal(SIGPIPE, SIG_IGN);
  8000. #endif
  8001. auto server_thread = std::thread([] {
  8002. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8003. default_socket_options(srv);
  8004. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8006. sockaddr_in addr{};
  8007. addr.sin_family = AF_INET;
  8008. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8009. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8010. int opt = 1;
  8011. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8012. #ifdef _WIN32
  8013. reinterpret_cast<const char *>(&opt),
  8014. #else
  8015. &opt,
  8016. #endif
  8017. sizeof(opt));
  8018. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8019. ::listen(srv, 1);
  8020. sockaddr_in cli_addr{};
  8021. socklen_t cli_len = sizeof(cli_addr);
  8022. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8023. if (cli != INVALID_SOCKET) {
  8024. char buf[4096];
  8025. ::recv(cli, buf, sizeof(buf), 0);
  8026. // Malicious response: claim a 20GB body but send only a tiny payload.
  8027. std::string response = "HTTP/1.1 200 OK\r\n"
  8028. "Content-Length: 20000000000\r\n"
  8029. "\r\n"
  8030. "abc";
  8031. ::send(cli,
  8032. #ifdef _WIN32
  8033. static_cast<const char *>(response.c_str()),
  8034. static_cast<int>(response.size()),
  8035. #else
  8036. response.c_str(), response.size(),
  8037. #endif
  8038. 0);
  8039. detail::close_socket(cli);
  8040. }
  8041. detail::close_socket(srv);
  8042. });
  8043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8044. {
  8045. Client cli("127.0.0.1", PORT + 2);
  8046. cli.set_read_timeout(5, 0);
  8047. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8048. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8049. // (server claims more bytes than payload_max_length permits), but it must
  8050. // not exhaust memory before getting there.
  8051. auto res = cli.Get("/malicious");
  8052. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8053. }
  8054. server_thread.join();
  8055. }
  8056. // Verify that content_receiver bypasses the default payload_max_length,
  8057. // allowing streaming downloads larger than 100MB without requiring an explicit
  8058. // set_payload_max_length call.
  8059. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8060. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8061. #ifndef _WIN32
  8062. signal(SIGPIPE, SIG_IGN);
  8063. #endif
  8064. auto server_thread = std::thread([] {
  8065. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8066. default_socket_options(srv);
  8067. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8069. sockaddr_in addr{};
  8070. addr.sin_family = AF_INET;
  8071. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8072. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8073. int opt = 1;
  8074. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8075. #ifdef _WIN32
  8076. reinterpret_cast<const char *>(&opt),
  8077. #else
  8078. &opt,
  8079. #endif
  8080. sizeof(opt));
  8081. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8082. ::listen(srv, 1);
  8083. sockaddr_in cli_addr{};
  8084. socklen_t cli_len = sizeof(cli_addr);
  8085. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8086. if (cli != INVALID_SOCKET) {
  8087. char buf[4096];
  8088. ::recv(cli, buf, sizeof(buf), 0);
  8089. // Response with Content-Length larger than default 100MB limit
  8090. auto content_length = std::to_string(DATA_SIZE);
  8091. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8092. "Content-Length: " +
  8093. content_length +
  8094. "\r\n"
  8095. "Connection: close\r\n"
  8096. "\r\n";
  8097. ::send(cli,
  8098. #ifdef _WIN32
  8099. static_cast<const char *>(response_header.c_str()),
  8100. static_cast<int>(response_header.size()),
  8101. #else
  8102. response_header.c_str(), response_header.size(),
  8103. #endif
  8104. 0);
  8105. std::string chunk(64 * 1024, 'A');
  8106. size_t total_sent = 0;
  8107. while (total_sent < DATA_SIZE) {
  8108. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8109. auto sent = ::send(cli,
  8110. #ifdef _WIN32
  8111. static_cast<const char *>(chunk.c_str()),
  8112. static_cast<int>(to_send),
  8113. #else
  8114. chunk.c_str(), to_send,
  8115. #endif
  8116. 0);
  8117. if (sent <= 0) break;
  8118. total_sent += static_cast<size_t>(sent);
  8119. }
  8120. detail::close_socket(cli);
  8121. }
  8122. detail::close_socket(srv);
  8123. });
  8124. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8125. size_t total_received = 0;
  8126. {
  8127. Client cli("127.0.0.1", PORT + 2);
  8128. cli.set_read_timeout(10, 0);
  8129. // Do NOT call set_payload_max_length — use the default 100MB limit
  8130. auto res =
  8131. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8132. total_received += data_length;
  8133. return true;
  8134. });
  8135. ASSERT_TRUE(res);
  8136. EXPECT_EQ(StatusCode::OK_200, res->status);
  8137. }
  8138. server_thread.join();
  8139. EXPECT_EQ(total_received, DATA_SIZE)
  8140. << "With content_receiver, the client should read all " << DATA_SIZE
  8141. << " bytes despite the default 100MB payload_max_length, but only read "
  8142. << total_received << " bytes.";
  8143. }
  8144. // Verify that an explicit set_payload_max_length smaller than the response is
  8145. // enforced even when a content_receiver is used.
  8146. TEST(ClientVulnerabilityTest,
  8147. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8148. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8149. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8150. #ifndef _WIN32
  8151. signal(SIGPIPE, SIG_IGN);
  8152. #endif
  8153. auto server_thread = std::thread([] {
  8154. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8155. default_socket_options(srv);
  8156. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8157. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8158. sockaddr_in addr{};
  8159. addr.sin_family = AF_INET;
  8160. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8161. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8162. int opt = 1;
  8163. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8164. #ifdef _WIN32
  8165. reinterpret_cast<const char *>(&opt),
  8166. #else
  8167. &opt,
  8168. #endif
  8169. sizeof(opt));
  8170. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8171. ::listen(srv, 1);
  8172. sockaddr_in cli_addr{};
  8173. socklen_t cli_len = sizeof(cli_addr);
  8174. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8175. if (cli != INVALID_SOCKET) {
  8176. char buf[4096];
  8177. ::recv(cli, buf, sizeof(buf), 0);
  8178. auto content_length = std::to_string(DATA_SIZE);
  8179. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8180. "Content-Length: " +
  8181. content_length +
  8182. "\r\n"
  8183. "Connection: close\r\n"
  8184. "\r\n";
  8185. ::send(cli,
  8186. #ifdef _WIN32
  8187. static_cast<const char *>(response_header.c_str()),
  8188. static_cast<int>(response_header.size()),
  8189. #else
  8190. response_header.c_str(), response_header.size(),
  8191. #endif
  8192. 0);
  8193. std::string chunk(64 * 1024, 'A');
  8194. size_t total_sent = 0;
  8195. while (total_sent < DATA_SIZE) {
  8196. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8197. auto sent = ::send(cli,
  8198. #ifdef _WIN32
  8199. static_cast<const char *>(chunk.c_str()),
  8200. static_cast<int>(to_send),
  8201. #else
  8202. chunk.c_str(), to_send,
  8203. #endif
  8204. 0);
  8205. if (sent <= 0) break;
  8206. total_sent += static_cast<size_t>(sent);
  8207. }
  8208. detail::close_socket(cli);
  8209. }
  8210. detail::close_socket(srv);
  8211. });
  8212. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8213. size_t total_received = 0;
  8214. {
  8215. Client cli("127.0.0.1", PORT + 2);
  8216. cli.set_read_timeout(10, 0);
  8217. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8218. auto res =
  8219. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8220. total_received += data_length;
  8221. return true;
  8222. });
  8223. // Should fail because 200MB exceeds the explicit 150MB limit
  8224. EXPECT_FALSE(res);
  8225. }
  8226. server_thread.join();
  8227. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8228. << "Client with content_receiver should respect the explicit "
  8229. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8230. << total_received << " bytes.";
  8231. }
  8232. // Verify that an explicit set_payload_max_length larger than the response
  8233. // allows the content_receiver to read all data successfully.
  8234. TEST(ClientVulnerabilityTest,
  8235. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8236. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8237. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8238. #ifndef _WIN32
  8239. signal(SIGPIPE, SIG_IGN);
  8240. #endif
  8241. auto server_thread = std::thread([] {
  8242. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8243. default_socket_options(srv);
  8244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8245. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8246. sockaddr_in addr{};
  8247. addr.sin_family = AF_INET;
  8248. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8250. int opt = 1;
  8251. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8252. #ifdef _WIN32
  8253. reinterpret_cast<const char *>(&opt),
  8254. #else
  8255. &opt,
  8256. #endif
  8257. sizeof(opt));
  8258. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8259. ::listen(srv, 1);
  8260. sockaddr_in cli_addr{};
  8261. socklen_t cli_len = sizeof(cli_addr);
  8262. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8263. if (cli != INVALID_SOCKET) {
  8264. char buf[4096];
  8265. ::recv(cli, buf, sizeof(buf), 0);
  8266. auto content_length = std::to_string(DATA_SIZE);
  8267. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8268. "Content-Length: " +
  8269. content_length +
  8270. "\r\n"
  8271. "Connection: close\r\n"
  8272. "\r\n";
  8273. ::send(cli,
  8274. #ifdef _WIN32
  8275. static_cast<const char *>(response_header.c_str()),
  8276. static_cast<int>(response_header.size()),
  8277. #else
  8278. response_header.c_str(), response_header.size(),
  8279. #endif
  8280. 0);
  8281. std::string chunk(64 * 1024, 'A');
  8282. size_t total_sent = 0;
  8283. while (total_sent < DATA_SIZE) {
  8284. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8285. auto sent = ::send(cli,
  8286. #ifdef _WIN32
  8287. static_cast<const char *>(chunk.c_str()),
  8288. static_cast<int>(to_send),
  8289. #else
  8290. chunk.c_str(), to_send,
  8291. #endif
  8292. 0);
  8293. if (sent <= 0) break;
  8294. total_sent += static_cast<size_t>(sent);
  8295. }
  8296. #ifdef _WIN32
  8297. ::shutdown(cli, SD_SEND);
  8298. #else
  8299. ::shutdown(cli, SHUT_WR);
  8300. #endif
  8301. char drain[1024];
  8302. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8303. detail::close_socket(cli);
  8304. }
  8305. detail::close_socket(srv);
  8306. });
  8307. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8308. size_t total_received = 0;
  8309. {
  8310. Client cli("127.0.0.1", PORT + 2);
  8311. cli.set_read_timeout(10, 0);
  8312. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8313. auto res =
  8314. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8315. total_received += data_length;
  8316. return true;
  8317. });
  8318. ASSERT_TRUE(res);
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. }
  8321. server_thread.join();
  8322. EXPECT_EQ(total_received, DATA_SIZE)
  8323. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8324. << " bytes (larger than " << DATA_SIZE
  8325. << " bytes response), content_receiver should read all data, but only "
  8326. "read "
  8327. << total_received << " bytes.";
  8328. }
  8329. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8330. // Regression test for "zip bomb" attack on the client side: a malicious server
  8331. // sends a small gzip-compressed response that decompresses to a huge payload.
  8332. // The client must enforce payload_max_length on the decompressed size.
  8333. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8334. constexpr size_t DECOMPRESSED_SIZE =
  8335. 10 * 1024 * 1024; // 10MB after decompression
  8336. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8337. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8338. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8339. std::string compressed;
  8340. {
  8341. httplib::detail::gzip_compressor compressor;
  8342. bool ok =
  8343. compressor.compress(uncompressed.data(), uncompressed.size(),
  8344. /*last=*/true, [&](const char *buf, size_t len) {
  8345. compressed.append(buf, len);
  8346. return true;
  8347. });
  8348. ASSERT_TRUE(ok);
  8349. }
  8350. // Sanity: compressed data should be much smaller than the decompressed size
  8351. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8352. #ifndef _WIN32
  8353. signal(SIGPIPE, SIG_IGN);
  8354. #endif
  8355. // Set up the listening socket in the main thread so the server is guaranteed
  8356. // to be ready before the client connects (eliminates race condition).
  8357. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8358. default_socket_options(srv);
  8359. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8360. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8361. sockaddr_in addr{};
  8362. addr.sin_family = AF_INET;
  8363. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8364. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8365. int opt = 1;
  8366. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8367. #ifdef _WIN32
  8368. reinterpret_cast<const char *>(&opt),
  8369. #else
  8370. &opt,
  8371. #endif
  8372. sizeof(opt));
  8373. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8374. ASSERT_EQ(0, ::listen(srv, 1));
  8375. auto server_thread = std::thread([&compressed, srv] {
  8376. sockaddr_in cli_addr{};
  8377. socklen_t cli_len = sizeof(cli_addr);
  8378. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8379. if (cli != INVALID_SOCKET) {
  8380. // Read the full HTTP request (until \r\n\r\n)
  8381. char buf[4096];
  8382. size_t total = 0;
  8383. while (total < sizeof(buf)) {
  8384. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8385. if (n <= 0) break;
  8386. total += static_cast<size_t>(n);
  8387. // Check for end of headers
  8388. if (total >= 4) {
  8389. std::string req(buf, total);
  8390. if (req.find("\r\n\r\n") != std::string::npos) break;
  8391. }
  8392. }
  8393. // Malicious response: gzip-compressed body, no Content-Length
  8394. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8395. "Content-Encoding: gzip\r\n"
  8396. "Connection: close\r\n"
  8397. "\r\n";
  8398. ::send(cli,
  8399. #ifdef _WIN32
  8400. static_cast<const char *>(response_header.c_str()),
  8401. static_cast<int>(response_header.size()),
  8402. #else
  8403. response_header.c_str(), response_header.size(),
  8404. #endif
  8405. 0);
  8406. // Send the compressed payload (small on the wire, huge when decompressed)
  8407. size_t total_sent = 0;
  8408. while (total_sent < compressed.size()) {
  8409. auto to_send = std::min(compressed.size() - total_sent,
  8410. static_cast<size_t>(64 * 1024));
  8411. auto sent =
  8412. ::send(cli,
  8413. #ifdef _WIN32
  8414. static_cast<const char *>(compressed.c_str() + total_sent),
  8415. static_cast<int>(to_send),
  8416. #else
  8417. compressed.c_str() + total_sent, to_send,
  8418. #endif
  8419. 0);
  8420. if (sent <= 0) break;
  8421. total_sent += static_cast<size_t>(sent);
  8422. }
  8423. detail::close_socket(cli);
  8424. }
  8425. });
  8426. auto se = detail::scope_exit([&] {
  8427. detail::close_socket(srv);
  8428. server_thread.join();
  8429. });
  8430. size_t total_decompressed = 0;
  8431. {
  8432. Client cli("127.0.0.1", PORT + 3);
  8433. cli.set_read_timeout(5, 0);
  8434. cli.set_decompress(true);
  8435. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8436. auto stream = cli.open_stream("GET", "/zipbomb");
  8437. ASSERT_TRUE(stream.is_valid());
  8438. char buffer[64 * 1024];
  8439. ssize_t n;
  8440. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8441. total_decompressed += static_cast<size_t>(n);
  8442. }
  8443. }
  8444. // The decompressed size must be capped by payload_max_length. Without
  8445. // protection, the client would decompress the full 10MB from a tiny
  8446. // compressed payload, enabling a zip bomb DoS attack.
  8447. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8448. << "Client decompressed " << total_decompressed
  8449. << " bytes from a gzip response. The decompressed size should be "
  8450. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8451. }
  8452. #endif
  8453. TEST(HostAndPortPropertiesTest, NoSSL) {
  8454. httplib::Client cli("www.google.com", 1234);
  8455. ASSERT_EQ("www.google.com", cli.host());
  8456. ASSERT_EQ(1234, cli.port());
  8457. }
  8458. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8459. httplib::Client cli("www.google.com:1234");
  8460. ASSERT_EQ("www.google.com", cli.host());
  8461. ASSERT_EQ(1234, cli.port());
  8462. }
  8463. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8464. // Port number that overflows int — should not crash, client becomes invalid
  8465. httplib::Client cli("http://www.google.com:99999999999999999999");
  8466. ASSERT_FALSE(cli.is_valid());
  8467. }
  8468. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8469. // Port 99999 exceeds valid range (1-65535) — should not crash
  8470. httplib::Client cli("http://www.google.com:99999");
  8471. ASSERT_FALSE(cli.is_valid());
  8472. }
  8473. #ifdef CPPHTTPLIB_SSL_ENABLED
  8474. TEST(HostAndPortPropertiesTest, SSL) {
  8475. httplib::SSLClient cli("www.google.com");
  8476. ASSERT_EQ("www.google.com", cli.host());
  8477. ASSERT_EQ(443, cli.port());
  8478. }
  8479. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8480. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8481. std::string cert;
  8482. read_file(CA_CERT_FILE, cert);
  8483. httplib::SSLClient httplib_client("www.google.com");
  8484. // Load CA store first time
  8485. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8486. // Load CA store second time (update)
  8487. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8488. // Verify client is still valid and can make connections
  8489. httplib_client.enable_server_certificate_verification(true);
  8490. auto res = httplib_client.Get("/");
  8491. ASSERT_TRUE(res);
  8492. // Google may return 200 or 301 depending on various factors
  8493. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8494. res->status == StatusCode::MovedPermanently_301);
  8495. }
  8496. TEST(SSLClientTest, ServerNameIndication_Online) {
  8497. auto host = "httpbingo.org";
  8498. auto path = std::string{"/get"};
  8499. SSLClient cli(host, 443);
  8500. auto res = cli.Get(path);
  8501. ASSERT_TRUE(res);
  8502. ASSERT_EQ(StatusCode::OK_200, res->status);
  8503. }
  8504. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8505. // Use a site that will cause SSL verification failure due to self-signed cert
  8506. SSLClient cli("self-signed.badssl.com", 443);
  8507. cli.enable_server_certificate_verification(true);
  8508. auto res = cli.Get("/");
  8509. ASSERT_TRUE(!res);
  8510. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8511. // Verify backend error is captured for SSLServerVerification
  8512. // This occurs when certificate verification fails
  8513. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8514. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8515. EXPECT_NE(0UL, res.ssl_backend_error());
  8516. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8517. // For OpenSSL, ssl_error is 0 for verification errors
  8518. EXPECT_EQ(0, res.ssl_error());
  8519. #if !defined(_WIN32) || \
  8520. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8521. // On non-Windows or when Windows Schannel is disabled, the error comes
  8522. // from OpenSSL's verification
  8523. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8524. res.ssl_backend_error());
  8525. #endif
  8526. #endif
  8527. }
  8528. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8529. // Use a site where hostname doesn't match the certificate
  8530. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8531. SSLClient cli("wrong.host.badssl.com", 443);
  8532. cli.enable_server_certificate_verification(true);
  8533. cli.enable_server_hostname_verification(true);
  8534. auto res = cli.Get("/");
  8535. ASSERT_TRUE(!res);
  8536. // The error type depends on when hostname verification occurs:
  8537. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8538. // - Mbed TLS: SSLServerVerification (during handshake)
  8539. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8540. res.error() == Error::SSLServerVerification);
  8541. // Verify backend error is captured for hostname verification failure
  8542. EXPECT_NE(0UL, res.ssl_backend_error());
  8543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8544. // For OpenSSL, ssl_error is 0 for verification errors
  8545. EXPECT_EQ(0, res.ssl_error());
  8546. #if !defined(_WIN32) || \
  8547. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8548. // On non-Windows or when Windows Schannel is disabled, the error comes
  8549. // from OpenSSL's hostname verification
  8550. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8551. res.ssl_backend_error());
  8552. #endif
  8553. #endif
  8554. }
  8555. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8556. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8557. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8558. SSLClient cli("www.google.com", 443);
  8559. cli.enable_server_certificate_verification(true);
  8560. auto res = cli.Get("/");
  8561. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8562. }
  8563. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8564. SSLClient cli("www.google.com", 443);
  8565. cli.enable_server_certificate_verification(true);
  8566. cli.enable_windows_certificate_verification(false);
  8567. auto res = cli.Get("/");
  8568. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8569. }
  8570. #endif
  8571. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8572. Client cli("https://google.com");
  8573. auto res = cli.Get("/");
  8574. ASSERT_TRUE(res);
  8575. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8576. }
  8577. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8578. SSLClient cli("google.com");
  8579. cli.set_ca_cert_path(CA_CERT_FILE);
  8580. auto res = cli.Get("/");
  8581. ASSERT_TRUE(res);
  8582. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8583. }
  8584. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8585. SSLClient cli("google.com");
  8586. cli.enable_server_certificate_verification(true);
  8587. cli.set_ca_cert_path("hello");
  8588. auto res = cli.Get("/");
  8589. ASSERT_TRUE(!res);
  8590. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8591. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8592. // should be set
  8593. EXPECT_EQ(0, res.ssl_error());
  8594. // Verify backend error is captured for SSLLoadingCerts
  8595. // This error occurs when loading CA certificates fails
  8596. EXPECT_NE(0UL, res.ssl_backend_error());
  8597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8598. // OpenSSL specific error codes:
  8599. // > openssl errstr 0x80000002
  8600. // error:80000002:system library::No such file or directory
  8601. // > openssl errstr 0xA000126
  8602. // error:0A000126:SSL routines::unexpected eof while reading
  8603. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8604. res.ssl_backend_error() == 0xA000126);
  8605. #endif
  8606. }
  8607. TEST(SSLClientTest, ServerCertificateVerification4) {
  8608. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8609. ASSERT_TRUE(svr.is_valid());
  8610. svr.Get("/test", [&](const Request &, Response &res) {
  8611. res.set_content("test", "text/plain");
  8612. svr.stop();
  8613. ASSERT_TRUE(true);
  8614. });
  8615. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8616. auto se = detail::scope_exit([&] {
  8617. t.join();
  8618. ASSERT_FALSE(svr.is_running());
  8619. });
  8620. svr.wait_until_ready();
  8621. SSLClient cli("127.0.0.1", PORT);
  8622. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8623. cli.enable_server_certificate_verification(true);
  8624. cli.set_connection_timeout(30);
  8625. auto res = cli.Get("/test");
  8626. ASSERT_TRUE(res);
  8627. ASSERT_EQ(StatusCode::OK_200, res->status);
  8628. }
  8629. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8630. std::string cert;
  8631. read_file(CA_CERT_FILE, cert);
  8632. SSLClient cli("google.com");
  8633. cli.load_ca_cert_store(cert.data(), cert.size());
  8634. const auto res = cli.Get("/");
  8635. ASSERT_TRUE(res);
  8636. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8637. }
  8638. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8639. // clang-format off
  8640. static constexpr char cert[] =
  8641. "GlobalSign Root CA\n"
  8642. "==================\n"
  8643. "-----BEGIN CERTIFICATE-----\n"
  8644. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8645. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8646. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8647. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8648. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8649. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8650. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8651. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8652. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8653. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8654. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8655. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8656. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8657. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8658. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8659. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8660. "-----END CERTIFICATE-----\n";
  8661. // clang-format on
  8662. SSLClient cli("google.com");
  8663. cli.load_ca_cert_store(cert, sizeof(cert));
  8664. const auto res = cli.Get("/");
  8665. ASSERT_TRUE(res);
  8666. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8667. }
  8668. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8669. SSLClient cli("www.youtube.com");
  8670. cli.set_ca_cert_path(CA_CERT_FILE);
  8671. cli.enable_server_certificate_verification(true);
  8672. cli.set_follow_location(true);
  8673. auto res = cli.Get("/");
  8674. ASSERT_TRUE(res);
  8675. ASSERT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8678. SSLClient cli("wWw.YouTube.Com");
  8679. cli.set_ca_cert_path(CA_CERT_FILE);
  8680. cli.enable_server_certificate_verification(true);
  8681. cli.enable_server_hostname_verification(true);
  8682. cli.set_follow_location(true);
  8683. auto res = cli.Get("/");
  8684. ASSERT_TRUE(res);
  8685. ASSERT_EQ(StatusCode::OK_200, res->status);
  8686. }
  8687. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8688. SSLClient cli("gOoGlE.COm");
  8689. cli.enable_server_certificate_verification(true);
  8690. cli.enable_server_hostname_verification(true);
  8691. cli.set_follow_location(true);
  8692. auto res = cli.Get("/");
  8693. ASSERT_TRUE(res);
  8694. ASSERT_EQ(StatusCode::OK_200, res->status);
  8695. }
  8696. TEST(SSLClientTest, Issue2004_Online) {
  8697. Client client("https://google.com");
  8698. client.set_follow_location(true);
  8699. auto res = client.Get("/");
  8700. ASSERT_TRUE(res);
  8701. ASSERT_EQ(StatusCode::OK_200, res->status);
  8702. auto body = res->body;
  8703. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8704. }
  8705. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8706. // Create SSLClient with invalid cert/key to make is_valid() return false
  8707. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8708. "nonexistent_key.pem");
  8709. // is_valid() should be false due to cert loading failure
  8710. ASSERT_FALSE(cli.is_valid());
  8711. auto res = cli.Get("/");
  8712. ASSERT_FALSE(res);
  8713. EXPECT_EQ(Error::SSLConnection, res.error());
  8714. }
  8715. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8716. // Test for Issue #2251: SSL error not properly reported when client cert
  8717. // and key paths are swapped or mismatched
  8718. // This simulates the scenario where user accidentally swaps the cert and key
  8719. // files
  8720. // Using client cert file as private key and vice versa (completely wrong)
  8721. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8722. // Should fail validation due to cert/key mismatch
  8723. ASSERT_FALSE(cli.is_valid());
  8724. // Attempt to make a request should fail with proper error
  8725. auto res = cli.Get("/");
  8726. ASSERT_FALSE(res);
  8727. EXPECT_EQ(Error::SSLConnection, res.error());
  8728. // SSL error should be recorded in the Result object (this is the key fix for
  8729. // Issue #2251)
  8730. auto backend_error = res.ssl_backend_error();
  8731. EXPECT_NE(0u, backend_error);
  8732. }
  8733. // Tests cert/key mismatch detection at the TLS context level
  8734. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8735. // Test that using mismatched cert/key causes connection failure.
  8736. // We verify this at the SSLClient level rather than through internal
  8737. // TLS API functions.
  8738. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8739. cli.enable_server_certificate_verification(false);
  8740. cli.set_connection_timeout(2);
  8741. // The mismatch should cause a connection or handshake error
  8742. auto res = cli.Get("/test");
  8743. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8744. // Either way, the request should fail
  8745. EXPECT_FALSE(res);
  8746. }
  8747. #endif
  8748. #if 0
  8749. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8750. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8751. ASSERT_TRUE(cli != nullptr);
  8752. cli->set_address_family(AF_INET6);
  8753. cli->set_interface("en0");
  8754. auto res = cli->Get("/get");
  8755. ASSERT_TRUE(res);
  8756. ASSERT_EQ(StatusCode::OK_200, res->status);
  8757. }
  8758. #endif
  8759. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8760. #ifdef CPPHTTPLIB_SSL_ENABLED
  8761. void ClientCertPresent(
  8762. const std::string &client_cert_file,
  8763. const std::string &client_private_key_file,
  8764. const std::string &client_encrypted_private_key_pass = std::string()) {
  8765. using namespace httplib::tls;
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8767. CLIENT_CA_CERT_DIR);
  8768. ASSERT_TRUE(svr.is_valid());
  8769. svr.Get("/test", [&](const Request &req, Response &res) {
  8770. res.set_content("test", "text/plain");
  8771. auto cert = req.peer_cert();
  8772. ASSERT_TRUE(static_cast<bool>(cert));
  8773. std::string common_name = cert.subject_cn();
  8774. EXPECT_EQ("Common Name", common_name);
  8775. });
  8776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8777. auto se = detail::scope_exit([&] {
  8778. svr.stop();
  8779. t.join();
  8780. ASSERT_FALSE(svr.is_running());
  8781. });
  8782. svr.wait_until_ready();
  8783. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8784. client_encrypted_private_key_pass);
  8785. cli.enable_server_certificate_verification(false);
  8786. cli.set_connection_timeout(30);
  8787. auto res = cli.Get("/test");
  8788. ASSERT_TRUE(res);
  8789. ASSERT_EQ(StatusCode::OK_200, res->status);
  8790. }
  8791. TEST(SSLClientServerTest, ClientCertPresent) {
  8792. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8793. }
  8794. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8795. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8796. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8797. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8798. }
  8799. // PEM memory-based constructor tests (works with all TLS backends)
  8800. void PemMemoryClientCertPresent(
  8801. const std::string &client_cert_file,
  8802. const std::string &client_private_key_file,
  8803. const std::string &client_encrypted_private_key_pass = std::string()) {
  8804. // Read PEM files into memory
  8805. std::string server_cert_pem, server_key_pem;
  8806. std::string client_ca_pem;
  8807. std::string client_cert_pem, client_key_pem;
  8808. read_file(SERVER_CERT_FILE, server_cert_pem);
  8809. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8810. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8811. read_file(client_cert_file, client_cert_pem);
  8812. read_file(client_private_key_file, client_key_pem);
  8813. // Create server with PEM memory
  8814. SSLServer::PemMemory server_pem = {
  8815. server_cert_pem.c_str(),
  8816. server_cert_pem.size(),
  8817. server_key_pem.c_str(),
  8818. server_key_pem.size(),
  8819. client_ca_pem.c_str(),
  8820. client_ca_pem.size(),
  8821. nullptr // no password for server key
  8822. };
  8823. SSLServer svr(server_pem);
  8824. ASSERT_TRUE(svr.is_valid());
  8825. svr.Get("/test", [&](const Request &, Response &res) {
  8826. res.set_content("test", "text/plain");
  8827. });
  8828. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. t.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. // Create client with PEM memory
  8836. const char *password = client_encrypted_private_key_pass.empty()
  8837. ? nullptr
  8838. : client_encrypted_private_key_pass.c_str();
  8839. SSLClient::PemMemory client_pem = {
  8840. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8841. client_key_pem.size(), password};
  8842. SSLClient cli(HOST, PORT, client_pem);
  8843. cli.enable_server_certificate_verification(false);
  8844. cli.set_connection_timeout(30);
  8845. auto res = cli.Get("/test");
  8846. ASSERT_TRUE(res);
  8847. ASSERT_EQ(StatusCode::OK_200, res->status);
  8848. }
  8849. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8850. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8851. }
  8852. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8853. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8854. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8855. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8856. }
  8857. TEST(SSLClientServerTest, ClientCertMissing) {
  8858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8859. CLIENT_CA_CERT_DIR);
  8860. ASSERT_TRUE(svr.is_valid());
  8861. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8862. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8863. auto se = detail::scope_exit([&] {
  8864. svr.stop();
  8865. t.join();
  8866. ASSERT_FALSE(svr.is_running());
  8867. });
  8868. svr.wait_until_ready();
  8869. SSLClient cli(HOST, PORT);
  8870. cli.set_connection_timeout(30);
  8871. auto res = cli.Get("/test");
  8872. ASSERT_TRUE(!res);
  8873. // When client cert is missing and server requires it, connection fails
  8874. // Error type depends on backend implementation
  8875. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8876. res.error() == Error::SSLConnection);
  8877. // Verify backend error is captured
  8878. // Note: This test may have different error codes depending on the exact
  8879. // verification failure
  8880. EXPECT_NE(0UL, res.ssl_backend_error());
  8881. }
  8882. TEST(SSLClientServerTest, TrustDirOptional) {
  8883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8884. ASSERT_TRUE(svr.is_valid());
  8885. svr.Get("/test", [&](const Request &, Response &res) {
  8886. res.set_content("test", "text/plain");
  8887. });
  8888. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. t.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.wait_until_ready();
  8895. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8896. cli.enable_server_certificate_verification(false);
  8897. cli.set_connection_timeout(30);
  8898. auto res = cli.Get("/test");
  8899. ASSERT_TRUE(res);
  8900. ASSERT_EQ(StatusCode::OK_200, res->status);
  8901. }
  8902. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8903. class NoListenSSLServer : public SSLServer {
  8904. public:
  8905. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8906. const char *client_ca_cert_file_path,
  8907. const char *client_ca_cert_dir_path = nullptr)
  8908. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8909. client_ca_cert_dir_path),
  8910. stop_(false) {}
  8911. std::atomic_bool stop_;
  8912. private:
  8913. bool process_and_close_socket(socket_t /*sock*/) override {
  8914. // Don't create SSL context
  8915. while (!stop_.load()) {
  8916. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8917. }
  8918. return true;
  8919. }
  8920. };
  8921. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8922. CLIENT_CA_CERT_FILE);
  8923. ASSERT_TRUE(svr.is_valid());
  8924. svr.Get("/test", [&](const Request &, Response &res) {
  8925. res.set_content("test", "text/plain");
  8926. });
  8927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8928. auto se = detail::scope_exit([&] {
  8929. svr.stop_ = true;
  8930. svr.stop();
  8931. t.join();
  8932. ASSERT_FALSE(svr.is_running());
  8933. });
  8934. svr.wait_until_ready();
  8935. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8936. cli.enable_server_certificate_verification(false);
  8937. cli.set_connection_timeout(1);
  8938. auto res = cli.Get("/test");
  8939. ASSERT_TRUE(!res);
  8940. EXPECT_EQ(Error::SSLConnection, res.error());
  8941. // Timeout results in WantRead error code (maps to backend-specific value)
  8942. EXPECT_NE(0, res.ssl_error());
  8943. }
  8944. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8945. // Test SSLServer with client certificate verification using the standard
  8946. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8948. CLIENT_CA_CERT_DIR);
  8949. ASSERT_TRUE(svr.is_valid());
  8950. svr.Get("/test", [&](const Request &req, Response &res) {
  8951. res.set_content("test", "text/plain");
  8952. auto cert = req.peer_cert();
  8953. ASSERT_TRUE(static_cast<bool>(cert));
  8954. auto common_name = cert.subject_cn();
  8955. EXPECT_EQ("Common Name", common_name);
  8956. });
  8957. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8958. auto se = detail::scope_exit([&] {
  8959. svr.stop();
  8960. t.join();
  8961. ASSERT_FALSE(svr.is_running());
  8962. });
  8963. svr.wait_until_ready();
  8964. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8965. cli.enable_server_certificate_verification(false);
  8966. cli.set_connection_timeout(30);
  8967. auto res = cli.Get("/test");
  8968. ASSERT_TRUE(res);
  8969. ASSERT_EQ(StatusCode::OK_200, res->status);
  8970. }
  8971. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8972. // Verifies that wildcard matching and exact matching work consistently
  8973. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8974. using namespace httplib::tls;
  8975. // We need a running server to test against
  8976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8977. ASSERT_TRUE(svr.is_valid());
  8978. svr.Get("/test", [](const Request &, Response &res) {
  8979. res.set_content("ok", "text/plain");
  8980. });
  8981. thread t([&]() { svr.listen(HOST, PORT); });
  8982. auto se = detail::scope_exit([&] {
  8983. svr.stop();
  8984. t.join();
  8985. });
  8986. svr.wait_until_ready();
  8987. bool verify_callback_called = false;
  8988. bool verify_result_wrong = false;
  8989. SSLClient cli(HOST, PORT);
  8990. cli.enable_server_certificate_verification(true);
  8991. cli.set_ca_cert_path(CA_CERT_FILE);
  8992. cli.set_connection_timeout(5);
  8993. // Note: Test certificate has CN="Common Name", not "localhost"
  8994. bool verify_result_cn = false;
  8995. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8996. verify_callback_called = true;
  8997. if (!ctx.cert) return false;
  8998. // Test 1: "Common Name" should match (our test server cert CN)
  8999. verify_result_cn = ctx.check_hostname("Common Name");
  9000. // Test 2: wrong hostname should not match
  9001. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9002. return true; // Accept for the purpose of this test
  9003. });
  9004. auto res = cli.Get("/test");
  9005. // The request may succeed or fail depending on cert configuration
  9006. // but the callback should have been called
  9007. ASSERT_TRUE(verify_callback_called)
  9008. << "Verify callback should have been called";
  9009. // CN="Common Name" should match our test certificate
  9010. //
  9011. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9012. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9013. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9014. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9015. // <openssl/base.h>, which is included transitively when
  9016. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9017. #if defined(OPENSSL_IS_BORINGSSL)
  9018. EXPECT_FALSE(verify_result_cn)
  9019. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9020. #else
  9021. EXPECT_TRUE(verify_result_cn)
  9022. << "verify_hostname should match 'Common Name' (certificate CN)";
  9023. #endif
  9024. // Wrong hostname should not match
  9025. EXPECT_FALSE(verify_result_wrong)
  9026. << "verify_hostname should not match 'wronghost.example.com'";
  9027. }
  9028. #endif
  9029. // mbedTLS-specific callback constructor test
  9030. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9031. #ifdef CPPHTTPLIB_SSL_ENABLED
  9032. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9034. ASSERT_TRUE(svr.is_valid());
  9035. // Set up a handler to verify client certificate is present
  9036. bool client_cert_verified = false;
  9037. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9038. // Verify that client certificate was provided
  9039. client_cert_verified = true;
  9040. res.set_content("success", "text/plain");
  9041. });
  9042. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9043. auto se = detail::scope_exit([&] {
  9044. svr.stop();
  9045. t.join();
  9046. ASSERT_FALSE(svr.is_running());
  9047. });
  9048. svr.wait_until_ready();
  9049. // Client with certificate
  9050. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9051. cli.enable_server_certificate_verification(false);
  9052. cli.set_connection_timeout(30);
  9053. auto res = cli.Get("/test");
  9054. ASSERT_TRUE(res);
  9055. ASSERT_EQ(StatusCode::OK_200, res->status);
  9056. ASSERT_TRUE(client_cert_verified);
  9057. EXPECT_EQ("success", res->body);
  9058. }
  9059. #endif
  9060. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9061. // backends
  9062. #ifdef CPPHTTPLIB_SSL_ENABLED
  9063. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9064. using namespace httplib::tls;
  9065. // Test that when client CA cert file is provided,
  9066. // the server properly requests and validates client certificates
  9067. // Create a server with client authentication
  9068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9069. ASSERT_TRUE(svr.is_valid());
  9070. bool handler_called = false;
  9071. svr.Get("/test", [&](const Request &req, Response &res) {
  9072. handler_called = true;
  9073. // Verify that a client certificate was provided
  9074. auto cert = req.peer_cert();
  9075. ASSERT_TRUE(static_cast<bool>(cert));
  9076. // Get the issuer name
  9077. std::string issuer_str = cert.issuer_name();
  9078. ASSERT_FALSE(issuer_str.empty());
  9079. // The client certificate should be issued by our test CA
  9080. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9081. res.set_content("authenticated", "text/plain");
  9082. });
  9083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9084. auto se = detail::scope_exit([&] {
  9085. svr.stop();
  9086. t.join();
  9087. ASSERT_FALSE(svr.is_running());
  9088. });
  9089. svr.wait_until_ready();
  9090. // Connect with a client certificate issued by the CA
  9091. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9092. cli.enable_server_certificate_verification(false);
  9093. cli.set_connection_timeout(30);
  9094. auto res = cli.Get("/test");
  9095. ASSERT_TRUE(res);
  9096. ASSERT_EQ(StatusCode::OK_200, res->status);
  9097. ASSERT_TRUE(handler_called);
  9098. EXPECT_EQ("authenticated", res->body);
  9099. }
  9100. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9101. using namespace httplib::tls;
  9102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9103. ASSERT_TRUE(svr.is_valid());
  9104. svr.Get("/test", [](const Request &, Response &res) {
  9105. res.set_content("ok", "text/plain");
  9106. });
  9107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9108. auto se = detail::scope_exit([&] {
  9109. svr.stop();
  9110. t.join();
  9111. });
  9112. svr.wait_until_ready();
  9113. SSLClient cli(HOST, PORT);
  9114. cli.enable_server_certificate_verification(false);
  9115. cli.set_connection_timeout(30);
  9116. bool cert_checked = false;
  9117. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9118. if (ctx.cert) {
  9119. auto sans = ctx.sans();
  9120. // Test certificate may or may not have SANs - just verify the API
  9121. // works If SANs exist, verify the types are valid
  9122. for (const auto &san : sans) {
  9123. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9124. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9125. san.type == SanType::OTHER);
  9126. EXPECT_FALSE(san.value.empty());
  9127. }
  9128. cert_checked = true;
  9129. }
  9130. return true;
  9131. });
  9132. auto res = cli.Get("/test");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_TRUE(cert_checked);
  9135. }
  9136. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9137. using namespace httplib::tls;
  9138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9139. ASSERT_TRUE(svr.is_valid());
  9140. svr.Get("/test", [](const Request &, Response &res) {
  9141. res.set_content("ok", "text/plain");
  9142. });
  9143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9144. auto se = detail::scope_exit([&] {
  9145. svr.stop();
  9146. t.join();
  9147. });
  9148. svr.wait_until_ready();
  9149. SSLClient cli(HOST, PORT);
  9150. cli.enable_server_certificate_verification(false);
  9151. cli.set_connection_timeout(30);
  9152. bool validity_checked = false;
  9153. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9154. if (ctx.cert) {
  9155. time_t not_before = 0, not_after = 0;
  9156. bool result = ctx.validity(not_before, not_after);
  9157. EXPECT_TRUE(result);
  9158. // Verify that not_before < now < not_after for a valid cert
  9159. time_t now = time(nullptr);
  9160. EXPECT_LT(not_before, now);
  9161. EXPECT_GT(not_after, now);
  9162. validity_checked = true;
  9163. }
  9164. return true;
  9165. });
  9166. auto res = cli.Get("/test");
  9167. ASSERT_TRUE(res);
  9168. EXPECT_TRUE(validity_checked);
  9169. }
  9170. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9171. using namespace httplib::tls;
  9172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9173. ASSERT_TRUE(svr.is_valid());
  9174. svr.Get("/test", [](const Request &, Response &res) {
  9175. res.set_content("ok", "text/plain");
  9176. });
  9177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9178. auto se = detail::scope_exit([&] {
  9179. svr.stop();
  9180. t.join();
  9181. });
  9182. svr.wait_until_ready();
  9183. SSLClient cli(HOST, PORT);
  9184. cli.enable_server_certificate_verification(false);
  9185. cli.set_connection_timeout(30);
  9186. bool serial_checked = false;
  9187. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9188. if (ctx.cert) {
  9189. std::string serial = ctx.serial();
  9190. EXPECT_FALSE(serial.empty());
  9191. // Serial should be a hex string
  9192. for (char c : serial) {
  9193. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9194. (c >= 'a' && c <= 'f'));
  9195. }
  9196. serial_checked = true;
  9197. }
  9198. return true;
  9199. });
  9200. auto res = cli.Get("/test");
  9201. ASSERT_TRUE(res);
  9202. EXPECT_TRUE(serial_checked);
  9203. }
  9204. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9205. // Test 1: Valid CA file - no error should be recorded
  9206. {
  9207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9208. CLIENT_CA_CERT_FILE);
  9209. ASSERT_TRUE(svr.is_valid());
  9210. // With valid setup, last_ssl_error should be 0
  9211. EXPECT_EQ(0, svr.ssl_last_error());
  9212. }
  9213. // Test 2: Invalid CA file content
  9214. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9215. {
  9216. // Create a temporary file with completely invalid content
  9217. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9218. {
  9219. std::ofstream ofs(temp_invalid_ca);
  9220. ofs << "This is not a certificate file at all\n";
  9221. ofs << "Just plain text content\n";
  9222. }
  9223. // Create server with invalid CA file
  9224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9225. // Clean up temporary file
  9226. std::remove(temp_invalid_ca);
  9227. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9228. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9229. // Note: SSL_CTX_load_verify_locations typically fails first,
  9230. // but our error handling code path is still exercised
  9231. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9232. }
  9233. }
  9234. TEST(VerifyCallbackTest, VerifyContextFields) {
  9235. using namespace httplib::tls;
  9236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9237. ASSERT_TRUE(svr.is_valid());
  9238. svr.Get("/test", [](const Request &, Response &res) {
  9239. res.set_content("ok", "text/plain");
  9240. });
  9241. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9242. auto se = detail::scope_exit([&] {
  9243. svr.stop();
  9244. t.join();
  9245. });
  9246. svr.wait_until_ready();
  9247. SSLClient cli(HOST, PORT);
  9248. cli.enable_server_certificate_verification(false);
  9249. cli.set_connection_timeout(30);
  9250. int callback_count = 0;
  9251. bool saw_leaf_cert = false;
  9252. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9253. if (ctx.cert) {
  9254. callback_count++;
  9255. // We should see at least one certificate (the leaf)
  9256. std::string cn = ctx.subject_cn();
  9257. if (!cn.empty()) { saw_leaf_cert = true; }
  9258. // Verify context fields are populated
  9259. EXPECT_NE(ctx.session, nullptr);
  9260. EXPECT_GE(ctx.depth, 0);
  9261. }
  9262. return true;
  9263. });
  9264. auto res = cli.Get("/test");
  9265. ASSERT_TRUE(res);
  9266. EXPECT_GT(callback_count, 0);
  9267. EXPECT_TRUE(saw_leaf_cert);
  9268. }
  9269. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9270. using httplib::tls::TlsError;
  9271. // Test that verify_error_to_string returns empty for success
  9272. std::string success_str = TlsError::verify_error_to_string(0);
  9273. EXPECT_TRUE(success_str.empty());
  9274. // Test that verify_error_to_string returns non-empty for error codes
  9275. // Using a common error code (certificate expired)
  9276. std::string error_str =
  9277. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9278. EXPECT_FALSE(error_str.empty());
  9279. }
  9280. TEST(SessionVerifierTest, CertificateAccepted) {
  9281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9282. ASSERT_TRUE(svr.is_valid());
  9283. svr.Get("/test", [](const Request &, Response &res) {
  9284. res.set_content("ok", "text/plain");
  9285. });
  9286. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9287. auto se = detail::scope_exit([&] {
  9288. svr.stop();
  9289. t.join();
  9290. });
  9291. svr.wait_until_ready();
  9292. SSLClient cli(HOST, PORT);
  9293. cli.enable_server_certificate_verification(false);
  9294. cli.set_connection_timeout(30);
  9295. bool callback_called = false;
  9296. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9297. EXPECT_NE(session, nullptr);
  9298. callback_called = true;
  9299. return SSLVerifierResponse::CertificateAccepted;
  9300. });
  9301. auto res = cli.Get("/test");
  9302. ASSERT_TRUE(res);
  9303. EXPECT_EQ(200, res->status);
  9304. EXPECT_TRUE(callback_called);
  9305. }
  9306. TEST(SessionVerifierTest, CertificateRejected) {
  9307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9308. ASSERT_TRUE(svr.is_valid());
  9309. svr.Get("/test", [](const Request &, Response &res) {
  9310. res.set_content("ok", "text/plain");
  9311. });
  9312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9313. auto se = detail::scope_exit([&] {
  9314. svr.stop();
  9315. t.join();
  9316. });
  9317. svr.wait_until_ready();
  9318. SSLClient cli(HOST, PORT);
  9319. cli.enable_server_certificate_verification(false);
  9320. cli.set_connection_timeout(30);
  9321. bool callback_called = false;
  9322. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9323. EXPECT_NE(session, nullptr);
  9324. callback_called = true;
  9325. return SSLVerifierResponse::CertificateRejected;
  9326. });
  9327. auto res = cli.Get("/test");
  9328. EXPECT_FALSE(res);
  9329. EXPECT_TRUE(callback_called);
  9330. }
  9331. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9333. ASSERT_TRUE(svr.is_valid());
  9334. svr.Get("/test", [](const Request &, Response &res) {
  9335. res.set_content("ok", "text/plain");
  9336. });
  9337. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9338. auto se = detail::scope_exit([&] {
  9339. svr.stop();
  9340. t.join();
  9341. });
  9342. svr.wait_until_ready();
  9343. // NoDecisionMade with verification disabled should succeed (no default check)
  9344. SSLClient cli(HOST, PORT);
  9345. cli.enable_server_certificate_verification(false);
  9346. cli.set_connection_timeout(30);
  9347. bool callback_called = false;
  9348. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9349. EXPECT_NE(session, nullptr);
  9350. callback_called = true;
  9351. return SSLVerifierResponse::NoDecisionMade;
  9352. });
  9353. auto res = cli.Get("/test");
  9354. ASSERT_TRUE(res);
  9355. EXPECT_EQ(200, res->status);
  9356. EXPECT_TRUE(callback_called);
  9357. }
  9358. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9360. ASSERT_TRUE(svr.is_valid());
  9361. svr.Get("/test", [](const Request &, Response &res) {
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. });
  9369. svr.wait_until_ready();
  9370. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9371. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9372. // so we only check that the request fails, not whether the callback was
  9373. // called.
  9374. SSLClient cli(HOST, PORT);
  9375. cli.enable_server_certificate_verification(true);
  9376. cli.set_connection_timeout(30);
  9377. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9378. EXPECT_NE(session, nullptr);
  9379. return SSLVerifierResponse::NoDecisionMade;
  9380. });
  9381. auto res = cli.Get("/test");
  9382. EXPECT_FALSE(res);
  9383. }
  9384. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9385. // Test SSL server using PemMemory constructor with client CA certificates
  9386. // Read PEM files
  9387. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9388. read_file(SERVER_CERT_FILE, server_cert_pem);
  9389. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9390. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9391. // Create SSLServer with PemMemory constructor including client CA
  9392. SSLServer::PemMemory server_pem = {
  9393. server_cert_pem.c_str(),
  9394. server_cert_pem.size(),
  9395. server_key_pem.c_str(),
  9396. server_key_pem.size(),
  9397. client_ca_pem.c_str(),
  9398. client_ca_pem.size(),
  9399. nullptr // no password for server key
  9400. };
  9401. SSLServer svr(server_pem);
  9402. ASSERT_TRUE(svr.is_valid());
  9403. // No SSL error should be recorded for valid setup
  9404. EXPECT_EQ(0, svr.ssl_last_error());
  9405. // Set up server endpoints
  9406. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9407. res.set_content("ok", "text/plain");
  9408. });
  9409. // Start server in a thread
  9410. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9411. svr.wait_until_ready();
  9412. // Connect with client certificate (using constructor with paths)
  9413. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9414. cli.enable_server_certificate_verification(false);
  9415. auto res = cli.Get("/test-pem-ca");
  9416. ASSERT_TRUE(res);
  9417. EXPECT_EQ(200, res->status);
  9418. EXPECT_EQ("ok", res->body);
  9419. svr.stop();
  9420. server_thread.join();
  9421. }
  9422. #endif
  9423. #ifdef _WIN32
  9424. TEST(CleanupTest, WSACleanup) {
  9425. int ret = WSACleanup();
  9426. ASSERT_EQ(0, ret);
  9427. }
  9428. #endif
  9429. #ifndef CPPHTTPLIB_SSL_ENABLED
  9430. TEST(NoSSLSupport, SimpleInterface) {
  9431. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9432. }
  9433. #endif
  9434. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9435. TEST(InvalidScheme, SimpleInterface) {
  9436. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9437. }
  9438. #endif
  9439. TEST(NoScheme, SimpleInterface) {
  9440. Client cli("yahoo.com:80");
  9441. ASSERT_TRUE(cli.is_valid());
  9442. }
  9443. TEST(SendAPI, SimpleInterface_Online) {
  9444. Client cli("http://yahoo.com");
  9445. Request req;
  9446. req.method = "GET";
  9447. req.path = "/";
  9448. auto res = cli.send(req);
  9449. ASSERT_TRUE(res);
  9450. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9451. }
  9452. TEST(SendAPI, WithParamsInRequest) {
  9453. Server svr;
  9454. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9455. EXPECT_TRUE(req.has_param("test"));
  9456. EXPECT_EQ("test_value", req.get_param_value("test"));
  9457. });
  9458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. Client cli(HOST, PORT);
  9466. {
  9467. Request req;
  9468. req.method = "GET";
  9469. req.path = "/";
  9470. req.params.emplace("test", "test_value");
  9471. auto res = cli.send(req);
  9472. ASSERT_TRUE(res);
  9473. }
  9474. {
  9475. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9476. ASSERT_TRUE(res);
  9477. }
  9478. }
  9479. TEST(ClientImplMethods, GetSocketTest) {
  9480. httplib::Server svr;
  9481. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9482. res.status = StatusCode::OK_200;
  9483. });
  9484. auto port = svr.bind_to_any_port("127.0.0.1");
  9485. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9486. auto se = detail::scope_exit([&] {
  9487. svr.stop();
  9488. thread.join();
  9489. ASSERT_FALSE(svr.is_running());
  9490. });
  9491. svr.wait_until_ready();
  9492. {
  9493. httplib::Client cli("127.0.0.1", port);
  9494. cli.set_keep_alive(true);
  9495. // Use the behavior of cpp-httplib of opening the connection
  9496. // only when the first request happens. If that changes,
  9497. // this test would be obsolete.
  9498. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9499. // This also implicitly tests the server. But other tests would fail much
  9500. // earlier than this one to be considered.
  9501. auto res = cli.Get("/");
  9502. ASSERT_TRUE(res);
  9503. EXPECT_EQ(StatusCode::OK_200, res->status);
  9504. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9505. }
  9506. }
  9507. #ifdef CPPHTTPLIB_SSL_ENABLED
  9508. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9509. Client cli("http://yahoo.com");
  9510. auto res = cli.Get("/");
  9511. ASSERT_TRUE(res);
  9512. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9513. cli.set_follow_location(true);
  9514. res = cli.Get("/");
  9515. ASSERT_TRUE(res);
  9516. EXPECT_EQ(StatusCode::OK_200, res->status);
  9517. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9518. }
  9519. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9520. Client cli("https://yahoo.com");
  9521. auto res = cli.Get("/");
  9522. ASSERT_TRUE(res);
  9523. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9524. cli.set_follow_location(true);
  9525. res = cli.Get("/");
  9526. ASSERT_TRUE(res);
  9527. EXPECT_EQ(StatusCode::OK_200, res->status);
  9528. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9529. }
  9530. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9531. Client cli("https://yahoo.com");
  9532. auto res = cli.Get("/");
  9533. ASSERT_TRUE(res);
  9534. ASSERT_FALSE(!res);
  9535. ASSERT_TRUE(res);
  9536. ASSERT_FALSE(res == nullptr);
  9537. ASSERT_TRUE(res != nullptr);
  9538. EXPECT_EQ(Error::Success, res.error());
  9539. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9540. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9541. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9542. cli.set_follow_location(true);
  9543. res = cli.Get("/");
  9544. ASSERT_TRUE(res);
  9545. EXPECT_EQ(Error::Success, res.error());
  9546. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9547. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9548. EXPECT_EQ(StatusCode::OK_200, res->status);
  9549. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9550. }
  9551. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9552. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9553. Client cli("https://cdnjs.cloudflare.com");
  9554. auto res =
  9555. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9556. ASSERT_TRUE(res);
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. EXPECT_EQ(287630U, res->body.size());
  9559. EXPECT_EQ("application/javascript; charset=utf-8",
  9560. res->get_header_value("Content-Type"));
  9561. }
  9562. #endif
  9563. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9564. #undef REDIR_HOST // Silence compiler warning
  9565. #define REDIR_HOST "https://httpbingo.org"
  9566. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9567. Client cli(REDIR_HOST);
  9568. cli.set_follow_location(true);
  9569. auto res =
  9570. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9571. ASSERT_TRUE(res);
  9572. EXPECT_EQ(StatusCode::OK_200, res->status);
  9573. }
  9574. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9575. Client cli(REDIR_HOST);
  9576. cli.set_follow_location(true);
  9577. Params params;
  9578. params.emplace("url", "http://example.com");
  9579. params.emplace("status_code", "302");
  9580. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9581. ASSERT_TRUE(res);
  9582. EXPECT_EQ(StatusCode::OK_200, res->status);
  9583. }
  9584. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9585. Client cli(REDIR_HOST);
  9586. cli.set_follow_location(true);
  9587. Params params;
  9588. params.emplace("url", "http://example.com");
  9589. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9590. ASSERT_TRUE(res);
  9591. EXPECT_EQ(StatusCode::OK_200, res->status);
  9592. }
  9593. TEST(HttpToHttpsRedirectTest, CertFile) {
  9594. auto ssl_port = PORT + 1;
  9595. Server svr;
  9596. ASSERT_TRUE(svr.is_valid());
  9597. svr.Get("/index", [&](const Request &, Response &res) {
  9598. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9599. "/index");
  9600. svr.stop();
  9601. });
  9602. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9603. ASSERT_TRUE(ssl_svr.is_valid());
  9604. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9605. res.set_content("test", "text/plain");
  9606. ssl_svr.stop();
  9607. });
  9608. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9609. thread t2 =
  9610. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9611. auto se = detail::scope_exit([&] {
  9612. t2.join();
  9613. t.join();
  9614. ASSERT_FALSE(svr.is_running());
  9615. });
  9616. svr.wait_until_ready();
  9617. ssl_svr.wait_until_ready();
  9618. Client cli("127.0.0.1", PORT);
  9619. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9620. cli.enable_server_certificate_verification(true);
  9621. cli.set_follow_location(true);
  9622. cli.set_connection_timeout(30);
  9623. auto res = cli.Get("/index");
  9624. ASSERT_TRUE(res);
  9625. ASSERT_EQ(StatusCode::OK_200, res->status);
  9626. }
  9627. TEST(SSLClientRedirectTest, CertFile) {
  9628. auto ssl_port = PORT + 1;
  9629. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9630. ASSERT_TRUE(ssl_svr1.is_valid());
  9631. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9632. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9633. "/index");
  9634. ssl_svr1.stop();
  9635. });
  9636. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9637. ASSERT_TRUE(ssl_svr2.is_valid());
  9638. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9639. res.set_content("test", "text/plain");
  9640. ssl_svr2.stop();
  9641. });
  9642. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9643. thread t2 =
  9644. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9645. auto se = detail::scope_exit([&] {
  9646. t2.join();
  9647. t.join();
  9648. ASSERT_FALSE(ssl_svr1.is_running());
  9649. });
  9650. ssl_svr1.wait_until_ready();
  9651. ssl_svr2.wait_until_ready();
  9652. SSLClient cli("127.0.0.1", PORT);
  9653. std::string cert;
  9654. read_file(SERVER_CERT2_FILE, cert);
  9655. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9656. cli.enable_server_certificate_verification(true);
  9657. cli.set_follow_location(true);
  9658. cli.set_connection_timeout(30);
  9659. auto res = cli.Get("/index");
  9660. ASSERT_TRUE(res);
  9661. ASSERT_EQ(StatusCode::OK_200, res->status);
  9662. }
  9663. #endif
  9664. #ifdef CPPHTTPLIB_SSL_ENABLED
  9665. // Test that set_ca_cert_store() skips system certs (consistent with
  9666. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9667. // should be trusted - system certs should NOT be loaded.
  9668. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9669. // Load a specific cert that is NOT a system CA cert
  9670. std::string cert;
  9671. read_file(SERVER_CERT2_FILE, cert);
  9672. SSLClient cli("google.com");
  9673. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9674. cli.enable_server_certificate_verification(true);
  9675. // This should FAIL because:
  9676. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9677. // 2. System certs should NOT be loaded when custom store is set
  9678. // If system certs WERE loaded, this would succeed
  9679. auto res = cli.Get("/");
  9680. ASSERT_FALSE(res);
  9681. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9682. }
  9683. TEST(MultipartFormDataTest, LargeData) {
  9684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9685. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9686. const ContentReader &content_reader) {
  9687. if (req.is_multipart_form_data()) {
  9688. std::vector<FormData> items;
  9689. content_reader(
  9690. [&](const FormData &file) {
  9691. items.push_back(file);
  9692. return true;
  9693. },
  9694. [&](const char *data, size_t data_length) {
  9695. items.back().content.append(data, data_length);
  9696. return true;
  9697. });
  9698. EXPECT_TRUE(std::string(items[0].name) == "document");
  9699. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9700. EXPECT_TRUE(items[0].filename == "2MB_data");
  9701. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9702. EXPECT_TRUE(items[1].name == "hello");
  9703. EXPECT_TRUE(items[1].content == "world");
  9704. EXPECT_TRUE(items[1].filename == "");
  9705. EXPECT_TRUE(items[1].content_type == "");
  9706. } else {
  9707. std::string body;
  9708. content_reader([&](const char *data, size_t data_length) {
  9709. body.append(data, data_length);
  9710. return true;
  9711. });
  9712. }
  9713. });
  9714. auto port = svr.bind_to_any_port(HOST);
  9715. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9716. auto se = detail::scope_exit([&] {
  9717. svr.stop();
  9718. t.join();
  9719. ASSERT_FALSE(svr.is_running());
  9720. });
  9721. svr.wait_until_ready();
  9722. {
  9723. std::string data(1024 * 1024 * 2, '.');
  9724. std::stringstream buffer;
  9725. buffer << data;
  9726. SSLClient cli(HOST, port);
  9727. cli.enable_server_certificate_verification(false);
  9728. UploadFormDataItems items{
  9729. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9730. {"hello", "world", "", ""},
  9731. };
  9732. auto res = cli.Post("/post", items);
  9733. ASSERT_TRUE(res);
  9734. ASSERT_EQ(StatusCode::OK_200, res->status);
  9735. }
  9736. }
  9737. TEST(MultipartFormDataTest, DataProviderItems) {
  9738. std::random_device seed_gen;
  9739. std::mt19937 random(seed_gen());
  9740. std::string rand1;
  9741. rand1.resize(1000);
  9742. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9743. std::string rand2;
  9744. rand2.resize(3000);
  9745. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9747. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9748. const ContentReader &content_reader) {
  9749. ASSERT_FALSE(req.is_multipart_form_data());
  9750. std::string body;
  9751. content_reader([&](const char *data, size_t data_length) {
  9752. body.append(data, data_length);
  9753. return true;
  9754. });
  9755. EXPECT_EQ(body, "");
  9756. });
  9757. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9758. const ContentReader &content_reader) {
  9759. ASSERT_TRUE(req.is_multipart_form_data());
  9760. std::vector<FormData> items;
  9761. content_reader(
  9762. [&](const FormData &file) {
  9763. items.push_back(file);
  9764. return true;
  9765. },
  9766. [&](const char *data, size_t data_length) {
  9767. items.back().content.append(data, data_length);
  9768. return true;
  9769. });
  9770. ASSERT_TRUE(items.size() == 2);
  9771. EXPECT_EQ(std::string(items[0].name), "name1");
  9772. EXPECT_EQ(items[0].content, "Testing123");
  9773. EXPECT_EQ(items[0].filename, "filename1");
  9774. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9775. EXPECT_EQ(items[1].name, "name2");
  9776. EXPECT_EQ(items[1].content, "Testing456");
  9777. EXPECT_EQ(items[1].filename, "");
  9778. EXPECT_EQ(items[1].content_type, "");
  9779. });
  9780. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9781. const ContentReader &content_reader) {
  9782. ASSERT_TRUE(req.is_multipart_form_data());
  9783. std::vector<FormData> items;
  9784. content_reader(
  9785. [&](const FormData &file) {
  9786. items.push_back(file);
  9787. return true;
  9788. },
  9789. [&](const char *data, size_t data_length) {
  9790. items.back().content.append(data, data_length);
  9791. return true;
  9792. });
  9793. ASSERT_TRUE(items.size() == 2);
  9794. EXPECT_EQ(items[0].name, "name3");
  9795. EXPECT_EQ(items[0].content, rand1);
  9796. EXPECT_EQ(items[0].filename, "filename3");
  9797. EXPECT_EQ(items[0].content_type, "");
  9798. EXPECT_EQ(items[1].name, "name4");
  9799. EXPECT_EQ(items[1].content, rand2);
  9800. EXPECT_EQ(items[1].filename, "filename4");
  9801. EXPECT_EQ(items[1].content_type, "");
  9802. });
  9803. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9804. const ContentReader &content_reader) {
  9805. ASSERT_TRUE(req.is_multipart_form_data());
  9806. std::vector<FormData> items;
  9807. content_reader(
  9808. [&](const FormData &file) {
  9809. items.push_back(file);
  9810. return true;
  9811. },
  9812. [&](const char *data, size_t data_length) {
  9813. items.back().content.append(data, data_length);
  9814. return true;
  9815. });
  9816. ASSERT_TRUE(items.size() == 4);
  9817. EXPECT_EQ(std::string(items[0].name), "name1");
  9818. EXPECT_EQ(items[0].content, "Testing123");
  9819. EXPECT_EQ(items[0].filename, "filename1");
  9820. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9821. EXPECT_EQ(items[1].name, "name2");
  9822. EXPECT_EQ(items[1].content, "Testing456");
  9823. EXPECT_EQ(items[1].filename, "");
  9824. EXPECT_EQ(items[1].content_type, "");
  9825. EXPECT_EQ(items[2].name, "name3");
  9826. EXPECT_EQ(items[2].content, rand1);
  9827. EXPECT_EQ(items[2].filename, "filename3");
  9828. EXPECT_EQ(items[2].content_type, "");
  9829. EXPECT_EQ(items[3].name, "name4");
  9830. EXPECT_EQ(items[3].content, rand2);
  9831. EXPECT_EQ(items[3].filename, "filename4");
  9832. EXPECT_EQ(items[3].content_type, "");
  9833. });
  9834. auto port = svr.bind_to_any_port("localhost");
  9835. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9836. auto se = detail::scope_exit([&] {
  9837. svr.stop();
  9838. t.join();
  9839. ASSERT_FALSE(svr.is_running());
  9840. });
  9841. svr.wait_until_ready();
  9842. {
  9843. SSLClient cli("localhost", port);
  9844. cli.enable_server_certificate_verification(false);
  9845. UploadFormDataItems items{
  9846. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9847. {"name2", "Testing456", "", ""}, // not a file
  9848. };
  9849. {
  9850. auto res = cli.Post("/post-none", {}, {}, {});
  9851. ASSERT_TRUE(res);
  9852. ASSERT_EQ(StatusCode::OK_200, res->status);
  9853. }
  9854. FormDataProviderItems providers;
  9855. {
  9856. auto res =
  9857. cli.Post("/post-items", {}, items, providers); // empty providers
  9858. ASSERT_TRUE(res);
  9859. ASSERT_EQ(StatusCode::OK_200, res->status);
  9860. }
  9861. providers.push_back({"name3",
  9862. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9863. // test the offset is given correctly at each step
  9864. if (!offset)
  9865. sink.os.write(rand1.data(), 30);
  9866. else if (offset == 30)
  9867. sink.os.write(rand1.data() + 30, 300);
  9868. else if (offset == 330)
  9869. sink.os.write(rand1.data() + 330, 670);
  9870. else if (offset == rand1.size())
  9871. sink.done();
  9872. return true;
  9873. },
  9874. "filename3",
  9875. {}});
  9876. providers.push_back({"name4",
  9877. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9878. // test the offset is given correctly at each step
  9879. if (!offset)
  9880. sink.os.write(rand2.data(), 2000);
  9881. else if (offset == 2000)
  9882. sink.os.write(rand2.data() + 2000, 1);
  9883. else if (offset == 2001)
  9884. sink.os.write(rand2.data() + 2001, 999);
  9885. else if (offset == rand2.size())
  9886. sink.done();
  9887. return true;
  9888. },
  9889. "filename4",
  9890. {}});
  9891. {
  9892. auto res = cli.Post("/post-providers", {}, {}, providers);
  9893. ASSERT_TRUE(res);
  9894. ASSERT_EQ(StatusCode::OK_200, res->status);
  9895. }
  9896. {
  9897. auto res = cli.Post("/post-both", {}, items, providers);
  9898. ASSERT_TRUE(res);
  9899. ASSERT_EQ(StatusCode::OK_200, res->status);
  9900. }
  9901. }
  9902. }
  9903. TEST(MultipartFormDataTest, BadHeader) {
  9904. Server svr;
  9905. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9906. res.set_content("ok", "text/plain");
  9907. });
  9908. thread t = thread([&] { svr.listen(HOST, PORT); });
  9909. auto se = detail::scope_exit([&] {
  9910. svr.stop();
  9911. t.join();
  9912. ASSERT_FALSE(svr.is_running());
  9913. });
  9914. svr.wait_until_ready();
  9915. const std::string body =
  9916. "This is the preamble. It is to be ignored, though it\r\n"
  9917. "is a handy place for composition agents to include an\r\n"
  9918. "explanatory note to non-MIME conformant readers.\r\n"
  9919. "\r\n"
  9920. "\r\n"
  9921. "--simple boundary\r\n"
  9922. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9923. ": BAD...\r\n"
  9924. "\r\n"
  9925. "value1\r\n"
  9926. "--simple boundary\r\n"
  9927. "Content-Disposition: form-data; name=\"field2\"; "
  9928. "filename=\"example.txt\"\r\n"
  9929. "\r\n"
  9930. "value2\r\n"
  9931. "--simple boundary--\r\n"
  9932. "This is the epilogue. It is also to be ignored.\r\n";
  9933. std::string content_type =
  9934. R"(multipart/form-data; boundary="simple boundary")";
  9935. Client cli(HOST, PORT);
  9936. auto res = cli.Post("/post", body, content_type.c_str());
  9937. ASSERT_TRUE(res);
  9938. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9939. }
  9940. TEST(MultipartFormDataTest, WithPreamble) {
  9941. Server svr;
  9942. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9943. res.set_content("ok", "text/plain");
  9944. });
  9945. thread t = thread([&] { svr.listen(HOST, PORT); });
  9946. auto se = detail::scope_exit([&] {
  9947. svr.stop();
  9948. t.join();
  9949. ASSERT_FALSE(svr.is_running());
  9950. });
  9951. svr.wait_until_ready();
  9952. const std::string body =
  9953. "This is the preamble. It is to be ignored, though it\r\n"
  9954. "is a handy place for composition agents to include an\r\n"
  9955. "explanatory note to non-MIME conformant readers.\r\n"
  9956. "\r\n"
  9957. "\r\n"
  9958. "--simple boundary\r\n"
  9959. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9960. "\r\n"
  9961. "value1\r\n"
  9962. "--simple boundary\r\n"
  9963. "Content-Disposition: form-data; name=\"field2\"; "
  9964. "filename=\"example.txt\"\r\n"
  9965. "\r\n"
  9966. "value2\r\n"
  9967. "--simple boundary--\r\n"
  9968. "This is the epilogue. It is also to be ignored.\r\n";
  9969. std::string content_type =
  9970. R"(multipart/form-data; boundary="simple boundary")";
  9971. Client cli(HOST, PORT);
  9972. auto res = cli.Post("/post", body, content_type.c_str());
  9973. ASSERT_TRUE(res);
  9974. EXPECT_EQ(StatusCode::OK_200, res->status);
  9975. }
  9976. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9978. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9979. const ContentReader &content_reader) {
  9980. if (req.is_multipart_form_data()) {
  9981. std::vector<FormData> items;
  9982. content_reader(
  9983. [&](const FormData &file) {
  9984. items.push_back(file);
  9985. return true;
  9986. },
  9987. [&](const char *data, size_t data_length) {
  9988. items.back().content.append(data, data_length);
  9989. return true;
  9990. });
  9991. EXPECT_TRUE(std::string(items[0].name) == "document");
  9992. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9993. EXPECT_TRUE(items[0].filename == "2MB_data");
  9994. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9995. EXPECT_TRUE(items[1].name == "hello");
  9996. EXPECT_TRUE(items[1].content == "world");
  9997. EXPECT_TRUE(items[1].filename == "");
  9998. EXPECT_TRUE(items[1].content_type == "");
  9999. } else {
  10000. std::string body;
  10001. content_reader([&](const char *data, size_t data_length) {
  10002. body.append(data, data_length);
  10003. return true;
  10004. });
  10005. }
  10006. });
  10007. auto port = svr.bind_to_any_port("localhost");
  10008. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10009. auto se = detail::scope_exit([&] {
  10010. svr.stop();
  10011. t.join();
  10012. ASSERT_FALSE(svr.is_running());
  10013. });
  10014. svr.wait_until_ready();
  10015. {
  10016. std::string data(1024 * 1024 * 2, '.');
  10017. std::stringstream buffer;
  10018. buffer << data;
  10019. SSLClient cli("localhost", port);
  10020. cli.enable_server_certificate_verification(false);
  10021. UploadFormDataItems items{
  10022. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10023. {"hello", "world", "", ""},
  10024. };
  10025. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10026. ASSERT_TRUE(res);
  10027. ASSERT_EQ(StatusCode::OK_200, res->status);
  10028. }
  10029. }
  10030. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10031. std::string data(1024 * 1024 * 2, '&');
  10032. std::stringstream buffer;
  10033. buffer << data;
  10034. Client cli("https://localhost:8080");
  10035. UploadFormDataItems items{
  10036. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10037. {"hello", "world", "", ""},
  10038. };
  10039. for (const char &c : " \t\r\n") {
  10040. auto res =
  10041. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10042. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10043. ASSERT_FALSE(res);
  10044. }
  10045. }
  10046. TEST(MultipartFormDataTest, PutFormData) {
  10047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10048. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10049. const ContentReader &content_reader) {
  10050. if (req.is_multipart_form_data()) {
  10051. std::vector<FormData> items;
  10052. content_reader(
  10053. [&](const FormData &file) {
  10054. items.push_back(file);
  10055. return true;
  10056. },
  10057. [&](const char *data, size_t data_length) {
  10058. items.back().content.append(data, data_length);
  10059. return true;
  10060. });
  10061. EXPECT_TRUE(std::string(items[0].name) == "document");
  10062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10063. EXPECT_TRUE(items[0].filename == "2MB_data");
  10064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10065. EXPECT_TRUE(items[1].name == "hello");
  10066. EXPECT_TRUE(items[1].content == "world");
  10067. EXPECT_TRUE(items[1].filename == "");
  10068. EXPECT_TRUE(items[1].content_type == "");
  10069. } else {
  10070. std::string body;
  10071. content_reader([&](const char *data, size_t data_length) {
  10072. body.append(data, data_length);
  10073. return true;
  10074. });
  10075. }
  10076. });
  10077. auto port = svr.bind_to_any_port("localhost");
  10078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. t.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. {
  10086. std::string data(1024 * 1024 * 2, '&');
  10087. std::stringstream buffer;
  10088. buffer << data;
  10089. SSLClient cli("localhost", port);
  10090. cli.enable_server_certificate_verification(false);
  10091. UploadFormDataItems items{
  10092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10093. {"hello", "world", "", ""},
  10094. };
  10095. auto res = cli.Put("/put", items);
  10096. ASSERT_TRUE(res);
  10097. ASSERT_EQ(StatusCode::OK_200, res->status);
  10098. }
  10099. }
  10100. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10102. svr.Put("/put_customboundary",
  10103. [&](const Request &req, const Response & /*res*/,
  10104. const ContentReader &content_reader) {
  10105. if (req.is_multipart_form_data()) {
  10106. std::vector<FormData> items;
  10107. content_reader(
  10108. [&](const FormData &file) {
  10109. items.push_back(file);
  10110. return true;
  10111. },
  10112. [&](const char *data, size_t data_length) {
  10113. items.back().content.append(data, data_length);
  10114. return true;
  10115. });
  10116. EXPECT_TRUE(std::string(items[0].name) == "document");
  10117. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10118. EXPECT_TRUE(items[0].filename == "2MB_data");
  10119. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10120. EXPECT_TRUE(items[1].name == "hello");
  10121. EXPECT_TRUE(items[1].content == "world");
  10122. EXPECT_TRUE(items[1].filename == "");
  10123. EXPECT_TRUE(items[1].content_type == "");
  10124. } else {
  10125. std::string body;
  10126. content_reader([&](const char *data, size_t data_length) {
  10127. body.append(data, data_length);
  10128. return true;
  10129. });
  10130. }
  10131. });
  10132. auto port = svr.bind_to_any_port("localhost");
  10133. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10134. auto se = detail::scope_exit([&] {
  10135. svr.stop();
  10136. t.join();
  10137. ASSERT_FALSE(svr.is_running());
  10138. });
  10139. svr.wait_until_ready();
  10140. {
  10141. std::string data(1024 * 1024 * 2, '&');
  10142. std::stringstream buffer;
  10143. buffer << data;
  10144. SSLClient cli("localhost", port);
  10145. cli.enable_server_certificate_verification(false);
  10146. UploadFormDataItems items{
  10147. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10148. {"hello", "world", "", ""},
  10149. };
  10150. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10151. ASSERT_TRUE(res);
  10152. ASSERT_EQ(StatusCode::OK_200, res->status);
  10153. }
  10154. }
  10155. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10156. std::string data(1024 * 1024 * 2, '&');
  10157. std::stringstream buffer;
  10158. buffer << data;
  10159. Client cli("https://localhost:8080");
  10160. cli.enable_server_certificate_verification(false);
  10161. UploadFormDataItems items{
  10162. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10163. {"hello", "world", "", ""},
  10164. };
  10165. for (const char &c : " \t\r\n") {
  10166. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10167. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10168. ASSERT_FALSE(res);
  10169. }
  10170. }
  10171. TEST(MultipartFormDataTest, AlternateFilename) {
  10172. auto handled = false;
  10173. Server svr;
  10174. svr.Post("/test", [&](const Request &req, Response &res) {
  10175. ASSERT_EQ(2u, req.form.files.size());
  10176. ASSERT_EQ(1u, req.form.fields.size());
  10177. // Test files
  10178. const auto &file1 = req.form.get_file("file1");
  10179. ASSERT_EQ("file1", file1.name);
  10180. ASSERT_EQ("A.txt", file1.filename);
  10181. ASSERT_EQ("text/plain", file1.content_type);
  10182. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10183. const auto &file2 = req.form.get_file("file2");
  10184. ASSERT_EQ("file2", file2.name);
  10185. ASSERT_EQ("a.html", file2.filename);
  10186. ASSERT_EQ("text/html", file2.content_type);
  10187. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10188. file2.content);
  10189. // Test text field
  10190. const auto &text = req.form.get_field("text");
  10191. ASSERT_EQ("text default", text);
  10192. res.set_content("ok", "text/plain");
  10193. handled = true;
  10194. });
  10195. thread t = thread([&] { svr.listen(HOST, PORT); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. t.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. ASSERT_TRUE(handled);
  10201. });
  10202. svr.wait_until_ready();
  10203. auto req = "POST /test HTTP/1.1\r\n"
  10204. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10205. "Content-Length: 399\r\n"
  10206. "\r\n"
  10207. "----------\r\n"
  10208. "Content-Disposition: form-data; name=\"text\"\r\n"
  10209. "\r\n"
  10210. "text default\r\n"
  10211. "----------\r\n"
  10212. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10213. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10214. "Content-Type: text/plain\r\n"
  10215. "\r\n"
  10216. "Content of a.txt.\r\n"
  10217. "\r\n"
  10218. "----------\r\n"
  10219. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10220. "\"a.html\"\r\n"
  10221. "Content-Type: text/html\r\n"
  10222. "\r\n"
  10223. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10224. "\r\n"
  10225. "------------\r\n";
  10226. ASSERT_TRUE(send_request(1, req));
  10227. }
  10228. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10229. auto handled = false;
  10230. Server svr;
  10231. svr.Post("/test", [&](const Request &req, Response &res) {
  10232. // Case-insensitive "utf-8''" prefix with a long value
  10233. const auto &file = req.form.get_file("file1");
  10234. ASSERT_EQ("file1", file.name);
  10235. // 8000 chars exercises both the Content-Disposition parser and the
  10236. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10237. // Prior to the fix, std::regex_match on this header would cause O(N)
  10238. // stack recursion in libstdc++, leading to SIGSEGV.
  10239. std::string expected_filename(8000, 'A');
  10240. ASSERT_EQ(expected_filename, file.filename);
  10241. res.set_content("ok", "text/plain");
  10242. handled = true;
  10243. });
  10244. thread t = thread([&] { svr.listen(HOST, PORT); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. ASSERT_FALSE(svr.is_running());
  10249. ASSERT_TRUE(handled);
  10250. });
  10251. svr.wait_until_ready();
  10252. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10253. // Regression test for GHSA-qq6v-r583-3h69
  10254. std::string long_filename(8000, 'A');
  10255. std::string body = "----------\r\n"
  10256. "Content-Disposition: form-data; name=\"file1\"; "
  10257. "filename*=\"Utf-8''" +
  10258. long_filename +
  10259. "\"\r\n"
  10260. "\r\n"
  10261. "hello\r\n"
  10262. "------------\r\n";
  10263. auto req = "POST /test HTTP/1.1\r\n"
  10264. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10265. "Content-Length: " +
  10266. std::to_string(body.size()) + "\r\n\r\n" + body;
  10267. ASSERT_TRUE(send_request(1, req));
  10268. }
  10269. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10270. auto handled = false;
  10271. Server svr;
  10272. svr.Post("/test", [&](const Request &req, Response &) {
  10273. ASSERT_EQ(2u, req.form.fields.size());
  10274. const auto &text1 = req.form.get_field("text1");
  10275. ASSERT_EQ("text1", text1);
  10276. const auto &text2 = req.form.get_field("text2");
  10277. ASSERT_EQ("text2", text2);
  10278. handled = true;
  10279. });
  10280. thread t = thread([&] { svr.listen(HOST, PORT); });
  10281. auto se = detail::scope_exit([&] {
  10282. svr.stop();
  10283. t.join();
  10284. ASSERT_FALSE(svr.is_running());
  10285. ASSERT_TRUE(handled);
  10286. });
  10287. svr.wait_until_ready();
  10288. auto req = "POST /test HTTP/1.1\r\n"
  10289. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10290. "Content-Length: 146\r\n"
  10291. "\r\n----------\r\n"
  10292. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10293. "\r\n"
  10294. "text1"
  10295. "\r\n----------\r\n"
  10296. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10297. "\r\n"
  10298. "text2"
  10299. "\r\n------------";
  10300. std::string response;
  10301. ASSERT_TRUE(send_request(1, req, &response));
  10302. ASSERT_EQ("200", response.substr(9, 3));
  10303. }
  10304. TEST(MultipartFormDataTest, ContentLength) {
  10305. auto handled = false;
  10306. Server svr;
  10307. svr.Post("/test", [&](const Request &req, Response &) {
  10308. ASSERT_EQ(2u, req.form.fields.size());
  10309. const auto &text1 = req.form.get_field("text1");
  10310. ASSERT_EQ("text1", text1);
  10311. const auto &text2 = req.form.get_field("text2");
  10312. ASSERT_EQ("text2", text2);
  10313. handled = true;
  10314. });
  10315. thread t = thread([&] { svr.listen(HOST, PORT); });
  10316. auto se = detail::scope_exit([&] {
  10317. svr.stop();
  10318. t.join();
  10319. ASSERT_FALSE(svr.is_running());
  10320. ASSERT_TRUE(handled);
  10321. });
  10322. svr.wait_until_ready();
  10323. auto req = "POST /test HTTP/1.1\r\n"
  10324. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10325. "Content-Length: 167\r\n"
  10326. "\r\n----------\r\n"
  10327. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10328. "Content-Length: 5\r\n"
  10329. "\r\n"
  10330. "text1"
  10331. "\r\n----------\r\n"
  10332. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10333. "\r\n"
  10334. "text2"
  10335. "\r\n------------\r\n";
  10336. std::string response;
  10337. ASSERT_TRUE(send_request(1, req, &response));
  10338. ASSERT_EQ("200", response.substr(9, 3));
  10339. }
  10340. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10341. auto handled = false;
  10342. Server svr;
  10343. svr.Post("/test", [&](const Request &req, Response &) {
  10344. ASSERT_EQ(2u, req.form.fields.size());
  10345. const auto &text1 = req.form.get_field("text1");
  10346. ASSERT_EQ("text1", text1);
  10347. // TODO: Add header access for text fields if needed
  10348. const auto &text2 = req.form.get_field("text2");
  10349. ASSERT_EQ("text2", text2);
  10350. // TODO: Header access for text fields needs to be implemented
  10351. // auto &headers = it->second.headers;
  10352. // ASSERT_EQ(3U, headers.size());
  10353. // auto custom_header = headers.find("x-whatever");
  10354. // ASSERT_TRUE(custom_header != headers.end());
  10355. // ASSERT_NE("customvalue", custom_header->second);
  10356. // ASSERT_EQ("CustomValue", custom_header->second);
  10357. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10358. handled = true;
  10359. });
  10360. thread t = thread([&] { svr.listen(HOST, PORT); });
  10361. auto se = detail::scope_exit([&] {
  10362. svr.stop();
  10363. t.join();
  10364. ASSERT_FALSE(svr.is_running());
  10365. ASSERT_TRUE(handled);
  10366. });
  10367. svr.wait_until_ready();
  10368. auto req = "POST /test HTTP/1.1\r\n"
  10369. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10370. "Content-Length: 232\r\n"
  10371. "\r\n----------\r\n"
  10372. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10373. "Content-Length: 5\r\n"
  10374. "X-Test: 1\r\n"
  10375. "\r\n"
  10376. "text1"
  10377. "\r\n----------\r\n"
  10378. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10379. "Content-Type: text/plain\r\n"
  10380. "X-Whatever: CustomValue\r\n"
  10381. "\r\n"
  10382. "text2"
  10383. "\r\n------------\r\n"
  10384. "That should be disregarded. Not even read";
  10385. std::string response;
  10386. ASSERT_TRUE(send_request(1, req, &response));
  10387. ASSERT_EQ("200", response.substr(9, 3));
  10388. }
  10389. TEST(MultipartFormDataTest, LargeHeader) {
  10390. auto handled = false;
  10391. Server svr;
  10392. svr.Post("/test", [&](const Request &req, Response &) {
  10393. ASSERT_EQ(1u, req.form.fields.size());
  10394. const auto &text = req.form.get_field("name1");
  10395. ASSERT_EQ("text1", text);
  10396. handled = true;
  10397. });
  10398. thread t = thread([&] { svr.listen(HOST, PORT); });
  10399. auto se = detail::scope_exit([&] {
  10400. svr.stop();
  10401. t.join();
  10402. ASSERT_FALSE(svr.is_running());
  10403. ASSERT_TRUE(handled);
  10404. });
  10405. svr.wait_until_ready();
  10406. auto boundary = std::string("cpp-httplib-multipart-data");
  10407. std::string content = "--" + boundary +
  10408. "\r\n"
  10409. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10410. "\r\n"
  10411. "text1\r\n"
  10412. "--" +
  10413. boundary + "--\r\n";
  10414. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10415. "Content-Type: multipart/form-data;boundary=" +
  10416. boundary +
  10417. "\r\n"
  10418. "Content-Length: " +
  10419. std::to_string(content.size()) +
  10420. "\r\n"
  10421. "Dummy-Header: ";
  10422. std::string header_suffix = "\r\n"
  10423. "\r\n";
  10424. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10425. size_t header_dummy_size =
  10426. read_buff_size -
  10427. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10428. auto header_dummy = std::string(header_dummy_size, '@');
  10429. auto req = header_prefix + header_dummy + header_suffix + content;
  10430. std::string response;
  10431. ASSERT_TRUE(send_request(1, req, &response));
  10432. ASSERT_EQ("200", response.substr(9, 3));
  10433. }
  10434. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10435. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10436. // (not chunked Transfer-Encoding) after the streaming refactor.
  10437. auto handled = false;
  10438. Server svr;
  10439. svr.Post("/upload", [&](const Request &req, Response &res) {
  10440. auto cl_it = req.headers.find("Content-Length");
  10441. EXPECT_TRUE(cl_it != req.headers.end());
  10442. auto te_it = req.headers.find("Transfer-Encoding");
  10443. EXPECT_TRUE(te_it == req.headers.end());
  10444. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10445. res.set_content("ok", "text/plain");
  10446. handled = true;
  10447. });
  10448. auto port = svr.bind_to_any_port(HOST);
  10449. auto t = thread([&] { svr.listen_after_bind(); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. ASSERT_FALSE(svr.is_running());
  10454. ASSERT_TRUE(handled);
  10455. });
  10456. svr.wait_until_ready();
  10457. UploadFormDataItems items = {
  10458. {"field1", "hello", "", "text/plain"},
  10459. {"file1", "world", "test.txt", "application/octet-stream"},
  10460. };
  10461. Client cli(HOST, port);
  10462. auto res = cli.Post("/upload", {}, items);
  10463. ASSERT_TRUE(res);
  10464. EXPECT_EQ(StatusCode::OK_200, res->status);
  10465. }
  10466. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10467. // Verify that make_multipart_content_provider coalesces many small segments
  10468. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10469. constexpr size_t kItemCount = 1000;
  10470. UploadFormDataItems items;
  10471. items.reserve(kItemCount);
  10472. for (size_t i = 0; i < kItemCount; i++) {
  10473. items.push_back(
  10474. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10475. }
  10476. const std::string boundary = "----test-boundary";
  10477. auto content_length = detail::get_multipart_content_length(items, boundary);
  10478. auto provider = detail::make_multipart_content_provider(items, boundary);
  10479. // Drive the provider the same way write_content_with_progress does
  10480. size_t write_count = 0;
  10481. size_t total_bytes = 0;
  10482. DataSink sink;
  10483. size_t offset = 0;
  10484. sink.write = [&](const char *d, size_t l) -> bool {
  10485. (void)d;
  10486. write_count++;
  10487. total_bytes += l;
  10488. offset += l;
  10489. return true;
  10490. };
  10491. sink.is_writable = []() -> bool { return true; };
  10492. while (offset < content_length) {
  10493. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10494. }
  10495. EXPECT_EQ(content_length, total_bytes);
  10496. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10497. // With buffering into 64KB blocks, write_count should be much smaller.
  10498. auto segment_count = 3 * kItemCount + 1;
  10499. EXPECT_LT(write_count, segment_count / 10);
  10500. }
  10501. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10502. // Integration test: send many UploadFormDataItems and verify the server
  10503. // receives all of them correctly (#2410).
  10504. constexpr size_t kItemCount = 500;
  10505. auto handled = false;
  10506. Server svr;
  10507. svr.Post("/upload", [&](const Request &req, Response &res) {
  10508. EXPECT_EQ(kItemCount, req.form.fields.size());
  10509. for (size_t i = 0; i < kItemCount; i++) {
  10510. auto key = "field" + std::to_string(i);
  10511. auto val = "value" + std::to_string(i);
  10512. auto it = req.form.fields.find(key);
  10513. if (it != req.form.fields.end()) {
  10514. EXPECT_EQ(val, it->second.content);
  10515. } else {
  10516. ADD_FAILURE() << "Missing field: " << key;
  10517. }
  10518. }
  10519. res.set_content("ok", "text/plain");
  10520. handled = true;
  10521. });
  10522. auto port = svr.bind_to_any_port(HOST);
  10523. auto t = thread([&] { svr.listen_after_bind(); });
  10524. auto se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. t.join();
  10527. ASSERT_FALSE(svr.is_running());
  10528. ASSERT_TRUE(handled);
  10529. });
  10530. svr.wait_until_ready();
  10531. UploadFormDataItems items;
  10532. items.reserve(kItemCount);
  10533. for (size_t i = 0; i < kItemCount; i++) {
  10534. items.push_back(
  10535. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10536. }
  10537. Client cli(HOST, port);
  10538. auto res = cli.Post("/upload", items);
  10539. ASSERT_TRUE(res);
  10540. EXPECT_EQ(StatusCode::OK_200, res->status);
  10541. }
  10542. TEST(MultipartFormDataTest, MakeFileProvider) {
  10543. // Verify make_file_provider sends a file's contents correctly.
  10544. const std::string file_content(4096, 'Z');
  10545. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10546. {
  10547. std::ofstream ofs(tmp_path, std::ios::binary);
  10548. ofs.write(file_content.data(),
  10549. static_cast<std::streamsize>(file_content.size()));
  10550. }
  10551. auto handled = false;
  10552. Server svr;
  10553. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10554. const ContentReader &content_reader) {
  10555. ASSERT_TRUE(req.is_multipart_form_data());
  10556. std::vector<FormData> items;
  10557. content_reader(
  10558. [&](const FormData &file) {
  10559. items.push_back(file);
  10560. return true;
  10561. },
  10562. [&](const char *data, size_t data_length) {
  10563. items.back().content.append(data, data_length);
  10564. return true;
  10565. });
  10566. ASSERT_EQ(1u, items.size());
  10567. EXPECT_EQ("myfile", items[0].name);
  10568. EXPECT_EQ("data.bin", items[0].filename);
  10569. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10570. EXPECT_EQ(file_content, items[0].content);
  10571. handled = true;
  10572. });
  10573. auto port = svr.bind_to_any_port(HOST);
  10574. auto t = thread([&] { svr.listen_after_bind(); });
  10575. auto se = detail::scope_exit([&] {
  10576. svr.stop();
  10577. t.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. ASSERT_TRUE(handled);
  10580. std::remove(tmp_path.c_str());
  10581. });
  10582. svr.wait_until_ready();
  10583. FormDataProviderItems providers;
  10584. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10585. "application/octet-stream"));
  10586. Client cli(HOST, port);
  10587. auto res = cli.Post("/upload", {}, {}, providers);
  10588. ASSERT_TRUE(res);
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. }
  10591. TEST(MakeFileBodyTest, Basic) {
  10592. const std::string file_content(4096, 'Z');
  10593. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10594. {
  10595. std::ofstream ofs(tmp_path, std::ios::binary);
  10596. ofs.write(file_content.data(),
  10597. static_cast<std::streamsize>(file_content.size()));
  10598. }
  10599. auto handled = false;
  10600. Server svr;
  10601. svr.Post("/upload", [&](const Request &req, Response &res) {
  10602. EXPECT_EQ(file_content, req.body);
  10603. handled = true;
  10604. res.status = StatusCode::OK_200;
  10605. });
  10606. auto port = svr.bind_to_any_port(HOST);
  10607. auto t = thread([&] { svr.listen_after_bind(); });
  10608. auto se = detail::scope_exit([&] {
  10609. svr.stop();
  10610. t.join();
  10611. ASSERT_FALSE(svr.is_running());
  10612. ASSERT_TRUE(handled);
  10613. std::remove(tmp_path.c_str());
  10614. });
  10615. svr.wait_until_ready();
  10616. auto fb = make_file_body(tmp_path);
  10617. ASSERT_GT(fb.first, 0u);
  10618. Client cli(HOST, port);
  10619. auto res =
  10620. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10621. ASSERT_TRUE(res);
  10622. EXPECT_EQ(StatusCode::OK_200, res->status);
  10623. }
  10624. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10625. static constexpr unsigned int number_of_tasks{1000000};
  10626. std::atomic_uint count{0};
  10627. std::unique_ptr<TaskQueue> task_queue{
  10628. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10629. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10630. auto queued = task_queue->enqueue(
  10631. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10632. EXPECT_TRUE(queued);
  10633. }
  10634. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10635. task_queue->shutdown();
  10636. #else
  10637. EXPECT_NO_THROW(task_queue->shutdown());
  10638. #endif
  10639. EXPECT_EQ(number_of_tasks, count.load());
  10640. }
  10641. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10642. static constexpr unsigned int number_of_tasks{1000000};
  10643. static constexpr unsigned int qlimit{2};
  10644. unsigned int queued_count{0};
  10645. std::atomic_uint count{0};
  10646. std::unique_ptr<TaskQueue> task_queue{
  10647. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10648. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10649. if (task_queue->enqueue(
  10650. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10651. queued_count++;
  10652. }
  10653. }
  10654. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10655. task_queue->shutdown();
  10656. #else
  10657. EXPECT_NO_THROW(task_queue->shutdown());
  10658. #endif
  10659. EXPECT_EQ(queued_count, count.load());
  10660. EXPECT_TRUE(queued_count <= number_of_tasks);
  10661. EXPECT_TRUE(queued_count >= qlimit);
  10662. }
  10663. TEST(TaskQueueTest, MaxQueuedRequests) {
  10664. static constexpr unsigned int qlimit{3};
  10665. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10666. std::condition_variable sem_cv;
  10667. std::mutex sem_mtx;
  10668. int credits = 0;
  10669. bool queued;
  10670. /* Fill up the queue with tasks that will block until we give them credits to
  10671. * complete. */
  10672. for (unsigned int n = 0; n <= qlimit;) {
  10673. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10674. std::unique_lock<std::mutex> lock(sem_mtx);
  10675. while (credits <= 0) {
  10676. sem_cv.wait(lock);
  10677. }
  10678. /* Consume the credit and signal the test code if they are all gone. */
  10679. if (--credits == 0) { sem_cv.notify_one(); }
  10680. });
  10681. if (n < qlimit) {
  10682. /* The first qlimit enqueues must succeed. */
  10683. EXPECT_TRUE(queued);
  10684. } else {
  10685. /* The last one will succeed only when the worker thread
  10686. * starts and dequeues the first blocking task. Although
  10687. * not necessary for the correctness of this test, we sleep for
  10688. * a short while to avoid busy waiting. */
  10689. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10690. }
  10691. if (queued) { n++; }
  10692. }
  10693. /* Further enqueues must fail since the queue is full. */
  10694. for (auto i = 0; i < 4; i++) {
  10695. queued = task_queue->enqueue([] {});
  10696. EXPECT_FALSE(queued);
  10697. }
  10698. /* Give the credits to allow the previous tasks to complete. */
  10699. {
  10700. std::unique_lock<std::mutex> lock(sem_mtx);
  10701. credits += qlimit + 1;
  10702. }
  10703. sem_cv.notify_all();
  10704. /* Wait for all the credits to be consumed. */
  10705. {
  10706. std::unique_lock<std::mutex> lock(sem_mtx);
  10707. while (credits > 0) {
  10708. sem_cv.wait(lock);
  10709. }
  10710. }
  10711. /* Check that we are able again to enqueue at least qlimit tasks. */
  10712. for (unsigned int i = 0; i < qlimit; i++) {
  10713. queued = task_queue->enqueue([] {});
  10714. EXPECT_TRUE(queued);
  10715. }
  10716. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10717. task_queue->shutdown();
  10718. #else
  10719. EXPECT_NO_THROW(task_queue->shutdown());
  10720. #endif
  10721. }
  10722. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10723. Server svr;
  10724. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10725. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10726. });
  10727. svr.Get("/hello", [](const Request &req, Response &res) {
  10728. res.set_content(req.get_param_value("key"), "text/plain");
  10729. });
  10730. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10731. auto se = detail::scope_exit([&] {
  10732. svr.stop();
  10733. thread.join();
  10734. ASSERT_FALSE(svr.is_running());
  10735. });
  10736. svr.wait_until_ready();
  10737. {
  10738. Client cli(HOST, PORT);
  10739. cli.set_follow_location(true);
  10740. auto res = cli.Get("/");
  10741. ASSERT_TRUE(res);
  10742. EXPECT_EQ(StatusCode::OK_200, res->status);
  10743. EXPECT_EQ("val&key2=val2", res->body);
  10744. }
  10745. }
  10746. #endif
  10747. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10748. Server svr;
  10749. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10750. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10751. });
  10752. svr.Get("/hello", [](const Request &req, Response &res) {
  10753. res.set_content(req.get_param_value("key"), "text/plain");
  10754. });
  10755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. thread.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. });
  10761. svr.wait_until_ready();
  10762. {
  10763. Client cli(HOST, PORT);
  10764. cli.set_follow_location(true);
  10765. auto res = cli.Get("/");
  10766. ASSERT_TRUE(res);
  10767. EXPECT_EQ(StatusCode::OK_200, res->status);
  10768. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10769. }
  10770. }
  10771. TEST(RedirectTest, RedirectWithPlusInPath) {
  10772. Server svr;
  10773. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10774. res.set_redirect("/a+b");
  10775. });
  10776. // Route pattern uses regex; escape + as \\+
  10777. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10778. res.set_content(req.path, "text/plain");
  10779. });
  10780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. thread.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.wait_until_ready();
  10787. {
  10788. Client cli(HOST, PORT);
  10789. cli.set_follow_location(true);
  10790. auto res = cli.Get("/");
  10791. ASSERT_TRUE(res);
  10792. EXPECT_EQ(StatusCode::OK_200, res->status);
  10793. EXPECT_EQ("/a+b", res->body);
  10794. }
  10795. }
  10796. #ifdef CPPHTTPLIB_SSL_ENABLED
  10797. TEST(RedirectTest, Issue2185_Online) {
  10798. SSLClient client("github.com");
  10799. client.set_follow_location(true);
  10800. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10801. "Coollab-Windows.zip");
  10802. ASSERT_TRUE(res);
  10803. EXPECT_EQ(StatusCode::OK_200, res->status);
  10804. EXPECT_EQ(9920427U, res->body.size());
  10805. }
  10806. #endif
  10807. TEST(VulnerabilityTest, CRLFInjection) {
  10808. Server svr;
  10809. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10810. res.set_content("Hello 1", "text/plain");
  10811. });
  10812. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10813. res.set_content("Hello 2", "text/plain");
  10814. });
  10815. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10816. res.set_content("Hello 3", "text/plain");
  10817. });
  10818. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10819. res.set_content("Hello 4", "text/plain");
  10820. });
  10821. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10822. for (const auto &x : req.headers) {
  10823. auto key = x.first;
  10824. EXPECT_STRNE("evil", key.c_str());
  10825. }
  10826. });
  10827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10828. auto se = detail::scope_exit([&] {
  10829. svr.stop();
  10830. thread.join();
  10831. ASSERT_FALSE(svr.is_running());
  10832. });
  10833. svr.wait_until_ready();
  10834. {
  10835. Client cli(HOST, PORT);
  10836. cli.Post("/test1", "A=B",
  10837. "application/x-www-form-urlencoded\r\nevil: hello1");
  10838. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10839. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10840. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10841. }
  10842. }
  10843. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10844. auto server_thread = std::thread([] {
  10845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10846. default_socket_options(srv);
  10847. sockaddr_in addr{};
  10848. addr.sin_family = AF_INET;
  10849. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10851. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10852. ::listen(srv, 1);
  10853. sockaddr_in cli_addr{};
  10854. socklen_t cli_len = sizeof(cli_addr);
  10855. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10856. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10857. std::string buf_all;
  10858. char buf[2048];
  10859. ssize_t n;
  10860. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10861. buf_all.append(buf, static_cast<size_t>(n));
  10862. size_t pos;
  10863. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10864. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10865. auto e = request_block.find("\r\n");
  10866. if (e != std::string::npos) {
  10867. auto request_line = request_block.substr(0, e);
  10868. std::string msg =
  10869. "CRLF injection detected in request line: '" + request_line + "'";
  10870. EXPECT_FALSE(true) << msg;
  10871. }
  10872. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10873. ::send(cli,
  10874. #ifdef _WIN32
  10875. static_cast<const char *>(resp.c_str()),
  10876. static_cast<int>(resp.size()),
  10877. #else
  10878. resp.c_str(), resp.size(),
  10879. #endif
  10880. 0);
  10881. buf_all.erase(0, pos + 4);
  10882. }
  10883. }
  10884. detail::close_socket(cli);
  10885. detail::close_socket(srv);
  10886. });
  10887. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10888. auto cli = Client("127.0.0.1", PORT + 1);
  10889. auto headers = Headers{
  10890. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10891. {"Connection", "keep-alive"}};
  10892. auto res = cli.Get("/hi", headers);
  10893. EXPECT_FALSE(res);
  10894. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10895. server_thread.join();
  10896. }
  10897. TEST(PathParamsTest, StaticMatch) {
  10898. const auto pattern = "/users/all";
  10899. detail::PathParamsMatcher matcher(pattern);
  10900. Request request;
  10901. request.path = "/users/all";
  10902. ASSERT_TRUE(matcher.match(request));
  10903. std::unordered_map<std::string, std::string> expected_params = {};
  10904. EXPECT_EQ(request.path_params, expected_params);
  10905. }
  10906. TEST(PathParamsTest, StaticMismatch) {
  10907. const auto pattern = "/users/all";
  10908. detail::PathParamsMatcher matcher(pattern);
  10909. Request request;
  10910. request.path = "/users/1";
  10911. ASSERT_FALSE(matcher.match(request));
  10912. }
  10913. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10914. const auto pattern = "/users/:id/subscriptions";
  10915. detail::PathParamsMatcher matcher(pattern);
  10916. Request request;
  10917. request.path = "/users/42/subscriptions";
  10918. ASSERT_TRUE(matcher.match(request));
  10919. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10920. EXPECT_EQ(request.path_params, expected_params);
  10921. }
  10922. TEST(PathParamsTest, SingleParamInTheEnd) {
  10923. const auto pattern = "/users/:id";
  10924. detail::PathParamsMatcher matcher(pattern);
  10925. Request request;
  10926. request.path = "/users/24";
  10927. ASSERT_TRUE(matcher.match(request));
  10928. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10929. EXPECT_EQ(request.path_params, expected_params);
  10930. }
  10931. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10932. const auto pattern = "/users/:id/";
  10933. detail::PathParamsMatcher matcher(pattern);
  10934. Request request;
  10935. request.path = "/users/42/";
  10936. ASSERT_TRUE(matcher.match(request));
  10937. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10938. EXPECT_EQ(request.path_params, expected_params);
  10939. }
  10940. TEST(PathParamsTest, EmptyParam) {
  10941. const auto pattern = "/users/:id/";
  10942. detail::PathParamsMatcher matcher(pattern);
  10943. Request request;
  10944. request.path = "/users//";
  10945. ASSERT_TRUE(matcher.match(request));
  10946. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10947. EXPECT_EQ(request.path_params, expected_params);
  10948. }
  10949. TEST(PathParamsTest, FragmentMismatch) {
  10950. const auto pattern = "/users/:id/";
  10951. detail::PathParamsMatcher matcher(pattern);
  10952. Request request;
  10953. request.path = "/admins/24/";
  10954. ASSERT_FALSE(matcher.match(request));
  10955. }
  10956. TEST(PathParamsTest, ExtraFragments) {
  10957. const auto pattern = "/users/:id";
  10958. detail::PathParamsMatcher matcher(pattern);
  10959. Request request;
  10960. request.path = "/users/42/subscriptions";
  10961. ASSERT_FALSE(matcher.match(request));
  10962. }
  10963. TEST(PathParamsTest, MissingTrailingParam) {
  10964. const auto pattern = "/users/:id";
  10965. detail::PathParamsMatcher matcher(pattern);
  10966. Request request;
  10967. request.path = "/users";
  10968. ASSERT_FALSE(matcher.match(request));
  10969. }
  10970. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10971. const auto pattern = "/users/:id/subscriptions";
  10972. detail::PathParamsMatcher matcher(pattern);
  10973. Request request;
  10974. request.path = "/users/subscriptions";
  10975. ASSERT_FALSE(matcher.match(request));
  10976. }
  10977. TEST(PathParamsTest, MultipleParams) {
  10978. const auto pattern = "/users/:userid/subscriptions/:subid";
  10979. detail::PathParamsMatcher matcher(pattern);
  10980. Request request;
  10981. request.path = "/users/42/subscriptions/2";
  10982. ASSERT_TRUE(matcher.match(request));
  10983. std::unordered_map<std::string, std::string> expected_params = {
  10984. {"userid", "42"}, {"subid", "2"}};
  10985. EXPECT_EQ(request.path_params, expected_params);
  10986. }
  10987. TEST(PathParamsTest, SequenceOfParams) {
  10988. const auto pattern = "/values/:x/:y/:z";
  10989. detail::PathParamsMatcher matcher(pattern);
  10990. Request request;
  10991. request.path = "/values/1/2/3";
  10992. ASSERT_TRUE(matcher.match(request));
  10993. std::unordered_map<std::string, std::string> expected_params = {
  10994. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10995. EXPECT_EQ(request.path_params, expected_params);
  10996. }
  10997. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10998. const auto pattern = "/prefix:suffix";
  10999. detail::PathParamsMatcher matcher(pattern);
  11000. Request request;
  11001. request.path = "/prefix:suffix";
  11002. ASSERT_TRUE(matcher.match(request));
  11003. const std::unordered_map<std::string, std::string> expected_params = {};
  11004. EXPECT_EQ(request.path_params, expected_params);
  11005. }
  11006. TEST(ParseUrlTest, VariousPatterns) {
  11007. {
  11008. detail::UrlComponents uc;
  11009. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11010. EXPECT_EQ("http", uc.scheme);
  11011. EXPECT_EQ("example.com", uc.host);
  11012. EXPECT_EQ("8080", uc.port);
  11013. EXPECT_EQ("/path", uc.path);
  11014. EXPECT_EQ("?q=1", uc.query);
  11015. }
  11016. {
  11017. detail::UrlComponents uc;
  11018. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11019. EXPECT_EQ("https", uc.scheme);
  11020. EXPECT_EQ("example.com", uc.host);
  11021. EXPECT_TRUE(uc.port.empty());
  11022. EXPECT_EQ("/path", uc.path);
  11023. }
  11024. {
  11025. detail::UrlComponents uc;
  11026. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11027. EXPECT_EQ("::1", uc.host);
  11028. EXPECT_EQ("8080", uc.port);
  11029. EXPECT_EQ("/path", uc.path);
  11030. }
  11031. {
  11032. detail::UrlComponents uc;
  11033. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11034. }
  11035. {
  11036. detail::UrlComponents uc;
  11037. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11038. EXPECT_TRUE(uc.scheme.empty());
  11039. EXPECT_EQ("example.com", uc.host);
  11040. EXPECT_EQ("/path", uc.path);
  11041. EXPECT_EQ("?q=1", uc.query);
  11042. }
  11043. {
  11044. detail::UrlComponents uc;
  11045. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11046. EXPECT_TRUE(uc.host.empty());
  11047. EXPECT_EQ("/path", uc.path);
  11048. EXPECT_EQ("?q=1", uc.query);
  11049. }
  11050. {
  11051. detail::UrlComponents uc;
  11052. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11053. EXPECT_EQ("example.com", uc.host);
  11054. EXPECT_EQ("8080", uc.port);
  11055. }
  11056. {
  11057. // Unix socket path — must not be parsed as host
  11058. detail::UrlComponents uc;
  11059. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11060. EXPECT_TRUE(uc.host.empty());
  11061. }
  11062. {
  11063. detail::UrlComponents uc;
  11064. ASSERT_TRUE(detail::parse_url("", uc));
  11065. EXPECT_TRUE(uc.host.empty());
  11066. EXPECT_TRUE(uc.path.empty());
  11067. }
  11068. {
  11069. detail::UrlComponents uc;
  11070. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11071. }
  11072. {
  11073. detail::UrlComponents uc;
  11074. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11075. }
  11076. {
  11077. // Accepted by parse_url; callers restrict to http/https
  11078. detail::UrlComponents uc;
  11079. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11080. EXPECT_EQ("ftp", uc.scheme);
  11081. }
  11082. {
  11083. detail::UrlComponents uc;
  11084. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11085. }
  11086. {
  11087. detail::UrlComponents uc;
  11088. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11089. }
  11090. }
  11091. TEST(ParseUrlTest, FragmentHandling) {
  11092. {
  11093. detail::UrlComponents uc;
  11094. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11095. EXPECT_EQ("/path", uc.path);
  11096. EXPECT_TRUE(uc.query.empty());
  11097. }
  11098. {
  11099. detail::UrlComponents uc;
  11100. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11101. EXPECT_TRUE(uc.path.empty());
  11102. EXPECT_TRUE(uc.query.empty());
  11103. }
  11104. }
  11105. TEST(ParseUrlTest, UserinfoHandling) {
  11106. // Userinfo with @ but no colon — host includes @
  11107. detail::UrlComponents uc;
  11108. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11109. EXPECT_EQ("user@host.com", uc.host);
  11110. EXPECT_EQ("/path", uc.path);
  11111. }
  11112. TEST(ParseUrlTest, IPv6EdgeCases) {
  11113. {
  11114. detail::UrlComponents uc;
  11115. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11116. EXPECT_TRUE(uc.scheme.empty());
  11117. EXPECT_EQ("::1", uc.host);
  11118. EXPECT_EQ("8080", uc.port);
  11119. }
  11120. {
  11121. // Zone ID '%25' is not in [a-fA-F0-9:]
  11122. detail::UrlComponents uc;
  11123. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11124. }
  11125. }
  11126. TEST(ParseUrlTest, SchemeEdgeCases) {
  11127. {
  11128. detail::UrlComponents uc;
  11129. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11130. }
  11131. {
  11132. detail::UrlComponents uc;
  11133. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11134. }
  11135. {
  11136. detail::UrlComponents uc;
  11137. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11138. }
  11139. }
  11140. TEST(ParseUrlTest, PortEdgeCases) {
  11141. {
  11142. detail::UrlComponents uc;
  11143. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11144. EXPECT_TRUE(uc.port.empty());
  11145. EXPECT_EQ("/path", uc.path);
  11146. }
  11147. {
  11148. // parse_url accepts any port string; validation is done by parse_port
  11149. detail::UrlComponents uc;
  11150. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11151. EXPECT_EQ("abc", uc.port);
  11152. }
  11153. }
  11154. TEST(ParseUrlTest, WebSocketPatterns) {
  11155. {
  11156. detail::UrlComponents uc;
  11157. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11158. EXPECT_EQ("ws", uc.scheme);
  11159. EXPECT_EQ("echo.example.com", uc.host);
  11160. EXPECT_EQ("8080", uc.port);
  11161. EXPECT_EQ("/ws", uc.path);
  11162. }
  11163. {
  11164. detail::UrlComponents uc;
  11165. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11166. EXPECT_EQ("wss", uc.scheme);
  11167. EXPECT_EQ("echo.example.com", uc.host);
  11168. EXPECT_TRUE(uc.port.empty());
  11169. EXPECT_EQ("/ws", uc.path);
  11170. }
  11171. }
  11172. TEST(ParseUrlTest, QueryOnly) {
  11173. detail::UrlComponents uc;
  11174. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11175. EXPECT_TRUE(uc.host.empty());
  11176. EXPECT_TRUE(uc.path.empty());
  11177. EXPECT_EQ("?q=1&r=2", uc.query);
  11178. }
  11179. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11180. detail::UrlComponents uc;
  11181. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11182. EXPECT_TRUE(uc.scheme.empty());
  11183. EXPECT_EQ("example.com", uc.host);
  11184. EXPECT_EQ("443", uc.port);
  11185. EXPECT_EQ("/path", uc.path);
  11186. }
  11187. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11188. // If ipv6 regex working, regex match codepath is taken.
  11189. // else port will default to 80 in Client impl
  11190. int clientImplMagicPort = 80;
  11191. int port = 4321;
  11192. // above ports must be different to avoid false negative
  11193. EXPECT_NE(clientImplMagicPort, port);
  11194. std::string ipV6TestURL = "http://[ff06::c3]";
  11195. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11196. CLIENT_PRIVATE_KEY_FILE);
  11197. EXPECT_EQ(cli.port(), port);
  11198. }
  11199. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11200. auto file_path = "./www/dir/index.html";
  11201. auto dir_path = "./www/dir";
  11202. detail::FileStat stat_file(file_path);
  11203. EXPECT_TRUE(stat_file.is_file());
  11204. EXPECT_FALSE(stat_file.is_dir());
  11205. detail::FileStat stat_dir(dir_path);
  11206. EXPECT_FALSE(stat_dir.is_file());
  11207. EXPECT_TRUE(stat_dir.is_dir());
  11208. }
  11209. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11210. // IPv4 with default HTTP port (80)
  11211. EXPECT_EQ("example.com",
  11212. detail::make_host_and_port_string("example.com", 80, false));
  11213. // IPv4 with default HTTPS port (443)
  11214. EXPECT_EQ("example.com",
  11215. detail::make_host_and_port_string("example.com", 443, true));
  11216. // IPv4 with non-default HTTP port
  11217. EXPECT_EQ("example.com:8080",
  11218. detail::make_host_and_port_string("example.com", 8080, false));
  11219. // IPv4 with non-default HTTPS port
  11220. EXPECT_EQ("example.com:8443",
  11221. detail::make_host_and_port_string("example.com", 8443, true));
  11222. // IPv6 with default HTTP port (80)
  11223. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11224. // IPv6 with default HTTPS port (443)
  11225. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11226. // IPv6 with non-default HTTP port
  11227. EXPECT_EQ("[::1]:8080",
  11228. detail::make_host_and_port_string("::1", 8080, false));
  11229. // IPv6 with non-default HTTPS port
  11230. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11231. // IPv6 full address with default port
  11232. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11233. detail::make_host_and_port_string(
  11234. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11235. // IPv6 full address with non-default port
  11236. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11237. detail::make_host_and_port_string(
  11238. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11239. // IPv6 localhost with non-default port
  11240. EXPECT_EQ("[::1]:3000",
  11241. detail::make_host_and_port_string("::1", 3000, false));
  11242. // IPv6 with zone ID (link-local address) with default port
  11243. EXPECT_EQ("[fe80::1%eth0]",
  11244. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11245. // IPv6 with zone ID (link-local address) with non-default port
  11246. EXPECT_EQ("[fe80::1%eth0]:8080",
  11247. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11248. // Edge case: Port 443 with is_ssl=false (should add port)
  11249. EXPECT_EQ("example.com:443",
  11250. detail::make_host_and_port_string("example.com", 443, false));
  11251. // Edge case: Port 80 with is_ssl=true (should add port)
  11252. EXPECT_EQ("example.com:80",
  11253. detail::make_host_and_port_string("example.com", 80, true));
  11254. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11255. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11256. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11257. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11258. // Security fix: Already bracketed IPv6 should not get double brackets
  11259. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11260. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11261. EXPECT_EQ("[::1]:8080",
  11262. detail::make_host_and_port_string("[::1]", 8080, false));
  11263. EXPECT_EQ("[2001:db8::1]:8080",
  11264. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11265. EXPECT_EQ("[fe80::1%eth0]",
  11266. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11267. EXPECT_EQ("[fe80::1%eth0]:8080",
  11268. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11269. // Edge case: Empty host (should return as-is)
  11270. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11271. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11272. // This is a known limitation but shouldn't crash
  11273. EXPECT_EQ("[host:name]",
  11274. detail::make_host_and_port_string("host:name", 80, false));
  11275. // Port number edge cases (no validation, but should not crash)
  11276. EXPECT_EQ("example.com:0",
  11277. detail::make_host_and_port_string("example.com", 0, false));
  11278. EXPECT_EQ("example.com:-1",
  11279. detail::make_host_and_port_string("example.com", -1, false));
  11280. EXPECT_EQ("example.com:65535",
  11281. detail::make_host_and_port_string("example.com", 65535, false));
  11282. EXPECT_EQ("example.com:65536",
  11283. detail::make_host_and_port_string("example.com", 65536, false));
  11284. }
  11285. #ifdef CPPHTTPLIB_SSL_ENABLED
  11286. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11287. httplib::SSLClient cli("roblox.com", 443);
  11288. cli.set_follow_location(true);
  11289. auto res = cli.Get("/");
  11290. ASSERT_TRUE(res);
  11291. EXPECT_EQ(StatusCode::OK_200, res->status);
  11292. }
  11293. #endif
  11294. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11295. Server svr;
  11296. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11297. EXPECT_EQ(res.status, 400);
  11298. });
  11299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11300. auto se = detail::scope_exit([&] {
  11301. svr.stop();
  11302. thread.join();
  11303. ASSERT_FALSE(svr.is_running());
  11304. });
  11305. svr.wait_until_ready();
  11306. Client cli(HOST, PORT);
  11307. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11308. }
  11309. TEST(InvalidHeaderCharsTest, is_field_name) {
  11310. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11311. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11312. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11313. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11314. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11315. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11316. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11317. EXPECT_FALSE(detail::fields::is_field_name(""));
  11318. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11319. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11320. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11321. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11322. }
  11323. TEST(InvalidHeaderCharsTest, is_field_value) {
  11324. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11325. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11326. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11327. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11328. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11329. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11330. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11331. EXPECT_TRUE(detail::fields::is_field_value(""));
  11332. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11333. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11334. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11335. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11336. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11337. }
  11338. TEST(InvalidHeaderCharsTest, OnServer) {
  11339. Server svr;
  11340. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11341. std::string header = "Not Set";
  11342. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11343. res.set_header(header, "value");
  11344. res.set_content("Page Content Page Content", "text/plain");
  11345. });
  11346. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11347. std::string header = "Not Set";
  11348. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11349. res.set_header("X-Test", header);
  11350. res.set_content("Page Content Page Content", "text/plain");
  11351. });
  11352. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. thread.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, PORT);
  11360. {
  11361. auto res = cli.Get(
  11362. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11363. ASSERT_TRUE(res);
  11364. EXPECT_EQ("Page Content Page Content", res->body);
  11365. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11366. }
  11367. {
  11368. auto res = cli.Get(
  11369. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11370. ASSERT_TRUE(res);
  11371. EXPECT_EQ("Page Content Page Content", res->body);
  11372. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11373. }
  11374. }
  11375. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11376. auto handled = false;
  11377. Server svr;
  11378. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11379. thread t = thread([&] { svr.listen(HOST, PORT); });
  11380. auto se = detail::scope_exit([&] {
  11381. svr.stop();
  11382. t.join();
  11383. ASSERT_FALSE(svr.is_running());
  11384. ASSERT_FALSE(handled);
  11385. });
  11386. svr.wait_until_ready();
  11387. auto req = "POST /test HTTP/1.1\r\n"
  11388. "Content-Length: x\r\n"
  11389. "\r\n";
  11390. std::string response;
  11391. ASSERT_TRUE(send_request(1, req, &response));
  11392. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11393. response.substr(0, response.find("\r\n")));
  11394. }
  11395. #ifndef _WIN32
  11396. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11397. static constexpr char reject[] = "Unauthorized";
  11398. static constexpr char accept[] = "Upload accepted";
  11399. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11400. Server svr;
  11401. svr.set_expect_100_continue_handler(
  11402. [](const Request & /*req*/, Response &res) {
  11403. res.status = StatusCode::Unauthorized_401;
  11404. res.set_content(reject, "text/plain");
  11405. return res.status;
  11406. });
  11407. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11408. res.set_content(accept, "text/plain");
  11409. });
  11410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. thread.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. {
  11418. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11419. curl_easy_init(), &curl_easy_cleanup};
  11420. ASSERT_NE(curl, nullptr);
  11421. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11422. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11423. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11424. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11425. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11426. &curl_slist_free_all};
  11427. ASSERT_NE(list, nullptr);
  11428. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11429. struct read_data {
  11430. size_t read_size;
  11431. size_t total_size;
  11432. } data = {0, total_size};
  11433. using read_callback_t =
  11434. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11435. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11436. void *userdata) -> size_t {
  11437. read_data *d = (read_data *)userdata;
  11438. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11439. std::fill_n(ptr, size * nmemb, 'A');
  11440. d->read_size += size * nmemb;
  11441. return size * nmemb;
  11442. };
  11443. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11444. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11445. std::vector<char> buffer;
  11446. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11447. using write_callback_t =
  11448. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11449. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11450. void *userdata) -> size_t {
  11451. std::vector<char> *buf = (std::vector<char> *)userdata;
  11452. buf->reserve(buf->size() + size * nmemb + 1);
  11453. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11454. return size * nmemb;
  11455. };
  11456. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11457. {
  11458. const auto res = curl_easy_perform(curl.get());
  11459. ASSERT_EQ(res, CURLE_OK);
  11460. }
  11461. {
  11462. auto response_code = long{};
  11463. const auto res =
  11464. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11465. ASSERT_EQ(res, CURLE_OK);
  11466. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11467. }
  11468. {
  11469. auto dl = curl_off_t{};
  11470. const auto res =
  11471. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11472. ASSERT_EQ(res, CURLE_OK);
  11473. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11474. }
  11475. {
  11476. buffer.push_back('\0');
  11477. ASSERT_STRCASEEQ(buffer.data(), reject);
  11478. }
  11479. }
  11480. }
  11481. #endif
  11482. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11483. // Regression test for #2458.
  11484. //
  11485. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11486. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11487. // ticket can make the client socket spuriously readable during the
  11488. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11489. // the client withholds the body and then blocks reading a response that never
  11490. // comes, failing with `Failed to read connection`.
  11491. //
  11492. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11493. // within the timeout. This raw OpenSSL server deliberately never sends
  11494. // `100 Continue`; the client must still deliver the body and receive 200.
  11495. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11496. signal(SIGPIPE, SIG_IGN);
  11497. const auto port = PORT + 4;
  11498. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11499. ASSERT_NE(srv, INVALID_SOCKET);
  11500. int opt = 1;
  11501. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11502. sockaddr_in addr{};
  11503. addr.sin_family = AF_INET;
  11504. addr.sin_port = htons(static_cast<uint16_t>(port));
  11505. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11506. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11507. ASSERT_EQ(0, ::listen(srv, 1));
  11508. std::atomic<size_t> server_body_bytes{0};
  11509. auto server_thread = std::thread([&] {
  11510. sockaddr_in cli_addr{};
  11511. socklen_t cli_len = sizeof(cli_addr);
  11512. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11513. if (cli == INVALID_SOCKET) { return; }
  11514. // Bound the lifetime of the server side so a buggy client (which never
  11515. // sends the body) cannot make this thread block forever on join.
  11516. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11517. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11518. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11519. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11520. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11521. SSL *ssl = SSL_new(ctx);
  11522. SSL_set_fd(ssl, static_cast<int>(cli));
  11523. if (SSL_accept(ssl) > 0) {
  11524. // Read the request headers. Reading here also flushes the TLS 1.3
  11525. // session tickets to the client. Deliberately do NOT send
  11526. // `100 Continue`.
  11527. std::string buf;
  11528. char tmp[1024];
  11529. while (buf.find("\r\n\r\n") == std::string::npos) {
  11530. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11531. if (n <= 0) { break; }
  11532. buf.append(tmp, static_cast<size_t>(n));
  11533. }
  11534. // A correct client sends the body now; count what arrives.
  11535. auto pos = buf.find("\r\n\r\n");
  11536. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11537. while (body < 4096) {
  11538. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11539. if (n <= 0) { break; }
  11540. body += static_cast<size_t>(n);
  11541. }
  11542. server_body_bytes = body;
  11543. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11544. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11545. SSL_shutdown(ssl);
  11546. }
  11547. SSL_free(ssl);
  11548. detail::close_socket(cli);
  11549. SSL_CTX_free(ctx);
  11550. });
  11551. auto se = detail::scope_exit([&] {
  11552. server_thread.join();
  11553. detail::close_socket(srv);
  11554. });
  11555. SSLClient cli("127.0.0.1", port);
  11556. cli.enable_server_certificate_verification(false);
  11557. cli.set_connection_timeout(5, 0);
  11558. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11559. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11560. std::string body(4096, 'A');
  11561. auto res = cli.Put("/api/test", body, "application/json");
  11562. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11563. EXPECT_EQ(StatusCode::OK_200, res->status);
  11564. EXPECT_EQ(body.size(), server_body_bytes.load());
  11565. }
  11566. #endif
  11567. template <typename S, typename C>
  11568. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11569. svr.Get("/stream", [&](const Request &, Response &res) {
  11570. auto data = new std::string("01234567890123456789");
  11571. res.set_content_provider(
  11572. data->size(), "text/plain",
  11573. [&, data](size_t offset, size_t length, DataSink &sink) {
  11574. const size_t DATA_CHUNK_SIZE = 4;
  11575. const auto &d = *data;
  11576. std::this_thread::sleep_for(std::chrono::seconds(1));
  11577. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11578. return true;
  11579. },
  11580. [data](bool success) {
  11581. EXPECT_FALSE(success);
  11582. delete data;
  11583. });
  11584. });
  11585. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11586. auto i = new size_t(0);
  11587. res.set_content_provider(
  11588. "text/plain",
  11589. [i](size_t, DataSink &sink) {
  11590. if (*i < 5) {
  11591. std::this_thread::sleep_for(std::chrono::seconds(1));
  11592. sink.write("abcd", 4);
  11593. (*i)++;
  11594. } else {
  11595. sink.done();
  11596. }
  11597. return true;
  11598. },
  11599. [i](bool success) {
  11600. EXPECT_FALSE(success);
  11601. delete i;
  11602. });
  11603. });
  11604. svr.Get("/chunked", [&](const Request &, Response &res) {
  11605. auto i = new size_t(0);
  11606. res.set_chunked_content_provider(
  11607. "text/plain",
  11608. [i](size_t, DataSink &sink) {
  11609. if (*i < 5) {
  11610. std::this_thread::sleep_for(std::chrono::seconds(1));
  11611. sink.os << "abcd";
  11612. (*i)++;
  11613. } else {
  11614. sink.done();
  11615. }
  11616. return true;
  11617. },
  11618. [i](bool success) {
  11619. EXPECT_FALSE(success);
  11620. delete i;
  11621. });
  11622. });
  11623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11624. auto se = detail::scope_exit([&] {
  11625. svr.stop();
  11626. listen_thread.join();
  11627. ASSERT_FALSE(svr.is_running());
  11628. });
  11629. svr.wait_until_ready();
  11630. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11631. {
  11632. auto start = std::chrono::steady_clock::now();
  11633. auto res = cli.Get("/stream");
  11634. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11635. std::chrono::steady_clock::now() - start)
  11636. .count();
  11637. ASSERT_FALSE(res);
  11638. EXPECT_EQ(Error::Read, res.error());
  11639. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11640. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11641. }
  11642. {
  11643. auto start = std::chrono::steady_clock::now();
  11644. auto res = cli.Get("/stream_without_length");
  11645. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11646. std::chrono::steady_clock::now() - start)
  11647. .count();
  11648. ASSERT_FALSE(res);
  11649. EXPECT_EQ(Error::Read, res.error());
  11650. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11651. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11652. }
  11653. {
  11654. auto start = std::chrono::steady_clock::now();
  11655. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11656. EXPECT_EQ("abcd", string(data, data_length));
  11657. return true;
  11658. });
  11659. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11660. std::chrono::steady_clock::now() - start)
  11661. .count();
  11662. ASSERT_FALSE(res);
  11663. EXPECT_EQ(Error::Read, res.error());
  11664. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11665. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11666. }
  11667. }
  11668. TEST(MaxTimeoutTest, ContentStream) {
  11669. time_t timeout = 2000;
  11670. time_t threshold = 200;
  11671. Server svr;
  11672. Client cli("localhost", PORT);
  11673. max_timeout_test(svr, cli, timeout, threshold);
  11674. }
  11675. #ifdef CPPHTTPLIB_SSL_ENABLED
  11676. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11677. time_t timeout = 2000;
  11678. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11680. SSLClient cli("localhost", PORT);
  11681. cli.enable_server_certificate_verification(false);
  11682. max_timeout_test(svr, cli, timeout, threshold);
  11683. }
  11684. #endif
  11685. class EventDispatcher {
  11686. public:
  11687. EventDispatcher() {}
  11688. bool wait_event(DataSink *sink) {
  11689. unique_lock<mutex> lk(m_);
  11690. int id = id_;
  11691. // Wait with timeout to prevent hanging if client disconnects
  11692. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11693. [&] { return cid_ == id; })) {
  11694. return false; // Timeout occurred
  11695. }
  11696. sink->write(message_.data(), message_.size());
  11697. return true;
  11698. }
  11699. void send_event(const string &message) {
  11700. lock_guard<mutex> lk(m_);
  11701. cid_ = id_++;
  11702. message_ = message;
  11703. cv_.notify_all();
  11704. }
  11705. private:
  11706. mutex m_;
  11707. condition_variable cv_;
  11708. atomic_int id_{0};
  11709. atomic_int cid_{-1};
  11710. string message_;
  11711. };
  11712. TEST(ClientInThreadTest, Issue2068) {
  11713. EventDispatcher ed;
  11714. Server svr;
  11715. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11716. res.set_chunked_content_provider("text/event-stream",
  11717. [&](size_t /*offset*/, DataSink &sink) {
  11718. return ed.wait_event(&sink);
  11719. });
  11720. });
  11721. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11722. svr.wait_until_ready();
  11723. thread event_thread([&] {
  11724. int id = 0;
  11725. while (svr.is_running()) {
  11726. this_thread::sleep_for(chrono::milliseconds(500));
  11727. std::stringstream ss;
  11728. ss << "data: " << id << "\n\n";
  11729. ed.send_event(ss.str());
  11730. id++;
  11731. }
  11732. });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. listen_thread.join();
  11736. event_thread.join();
  11737. ASSERT_FALSE(svr.is_running());
  11738. });
  11739. {
  11740. auto client = detail::make_unique<Client>(HOST, PORT);
  11741. client->set_read_timeout(std::chrono::minutes(10));
  11742. std::atomic<bool> stop{false};
  11743. std::thread t([&] {
  11744. client->Get("/event1",
  11745. [&](const char *, size_t) -> bool { return !stop; });
  11746. });
  11747. std::this_thread::sleep_for(std::chrono::seconds(2));
  11748. stop = true;
  11749. client->stop();
  11750. t.join();
  11751. // Reset client after thread has finished
  11752. client.reset();
  11753. }
  11754. }
  11755. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11756. auto handled = false;
  11757. Server svr;
  11758. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11759. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11760. auto se = detail::scope_exit([&] {
  11761. svr.stop();
  11762. t.join();
  11763. ASSERT_FALSE(svr.is_running());
  11764. ASSERT_FALSE(handled);
  11765. });
  11766. svr.wait_until_ready();
  11767. // Two Content-Length headers with different values — must be rejected
  11768. auto req = "POST /test HTTP/1.1\r\n"
  11769. "Content-Length: 5\r\n"
  11770. "Content-Length: 10\r\n"
  11771. "\r\n"
  11772. "hello";
  11773. std::string response;
  11774. ASSERT_TRUE(send_request(1, req, &response));
  11775. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11776. response.substr(0, response.find("\r\n")));
  11777. }
  11778. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11779. auto handled = false;
  11780. Server svr;
  11781. svr.Post("/test", [&](const Request &, Response &res) {
  11782. handled = true;
  11783. res.set_content("ok", "text/plain");
  11784. });
  11785. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11786. auto se = detail::scope_exit([&] {
  11787. svr.stop();
  11788. t.join();
  11789. ASSERT_FALSE(svr.is_running());
  11790. ASSERT_TRUE(handled);
  11791. });
  11792. svr.wait_until_ready();
  11793. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11794. auto req = "POST /test HTTP/1.1\r\n"
  11795. "Content-Length: 5\r\n"
  11796. "Content-Length: 5\r\n"
  11797. "\r\n"
  11798. "hello";
  11799. std::string response;
  11800. ASSERT_TRUE(send_request(1, req, &response));
  11801. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11802. }
  11803. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11804. Server svr;
  11805. svr.Get("/", [](const Request &req, Response &res) {
  11806. EXPECT_EQ(2U, req.trailers.size());
  11807. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11808. // Denied
  11809. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11810. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11811. // Accepted
  11812. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11813. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11814. EXPECT_TRUE(req.has_trailer("X-World"));
  11815. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11816. res.set_content("ok", "text/plain");
  11817. });
  11818. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11819. auto se = detail::scope_exit([&] {
  11820. svr.stop();
  11821. t.join();
  11822. ASSERT_FALSE(svr.is_running());
  11823. });
  11824. svr.wait_until_ready();
  11825. const std::string req = "GET / HTTP/1.1\r\n"
  11826. "Transfer-Encoding: chunked\r\n"
  11827. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11828. "\r\n"
  11829. "0\r\n"
  11830. "Content-Length: 10\r\n"
  11831. "Host: internal.local\r\n"
  11832. "Content-Type: malicious/content\r\n"
  11833. "Cookie: any\r\n"
  11834. "Set-Cookie: any\r\n"
  11835. "X-Forwarded-For: attacker.com\r\n"
  11836. "X-Real-Ip: 1.1.1.1\r\n"
  11837. "X-Hello: hello\r\n"
  11838. "X-World: world\r\n"
  11839. "\r\n";
  11840. std::string res;
  11841. ASSERT_TRUE(send_request(1, req, &res));
  11842. }
  11843. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11844. Server svr;
  11845. std::string observed_remote_addr;
  11846. std::string observed_xff;
  11847. svr.Get("/ip", [&](const Request &req, Response &res) {
  11848. observed_remote_addr = req.remote_addr;
  11849. observed_xff = req.get_header_value("X-Forwarded-For");
  11850. res.set_content("ok", "text/plain");
  11851. });
  11852. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11853. auto se = detail::scope_exit([&] {
  11854. svr.stop();
  11855. t.join();
  11856. ASSERT_FALSE(svr.is_running());
  11857. });
  11858. svr.wait_until_ready();
  11859. Client cli(HOST, PORT);
  11860. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11861. ASSERT_TRUE(res);
  11862. EXPECT_EQ(StatusCode::OK_200, res->status);
  11863. EXPECT_EQ(observed_xff, "203.0.113.66");
  11864. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11865. observed_remote_addr == "127.0.0.1");
  11866. }
  11867. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11868. Server svr;
  11869. svr.set_trusted_proxies({"203.0.113.66"});
  11870. std::string observed_remote_addr;
  11871. std::string observed_xff;
  11872. svr.Get("/ip", [&](const Request &req, Response &res) {
  11873. observed_remote_addr = req.remote_addr;
  11874. observed_xff = req.get_header_value("X-Forwarded-For");
  11875. res.set_content("ok", "text/plain");
  11876. });
  11877. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. t.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli(HOST, PORT);
  11885. auto res = cli.Get("/ip");
  11886. ASSERT_TRUE(res);
  11887. EXPECT_EQ(StatusCode::OK_200, res->status);
  11888. EXPECT_EQ(observed_xff, "");
  11889. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11890. observed_remote_addr == "127.0.0.1");
  11891. }
  11892. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11893. Server svr;
  11894. svr.set_trusted_proxies({"203.0.113.66"});
  11895. std::string observed_remote_addr;
  11896. std::string observed_xff;
  11897. svr.Get("/ip", [&](const Request &req, Response &res) {
  11898. observed_remote_addr = req.remote_addr;
  11899. observed_xff = req.get_header_value("X-Forwarded-For");
  11900. res.set_content("ok", "text/plain");
  11901. });
  11902. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11903. auto se = detail::scope_exit([&] {
  11904. svr.stop();
  11905. t.join();
  11906. ASSERT_FALSE(svr.is_running());
  11907. });
  11908. svr.wait_until_ready();
  11909. Client cli(HOST, PORT);
  11910. auto res =
  11911. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11912. ASSERT_TRUE(res);
  11913. EXPECT_EQ(StatusCode::OK_200, res->status);
  11914. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11915. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11916. }
  11917. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11918. Server svr;
  11919. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11920. std::string observed_remote_addr;
  11921. std::string observed_xff;
  11922. svr.Get("/ip", [&](const Request &req, Response &res) {
  11923. observed_remote_addr = req.remote_addr;
  11924. observed_xff = req.get_header_value("X-Forwarded-For");
  11925. res.set_content("ok", "text/plain");
  11926. });
  11927. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. t.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. Client cli(HOST, PORT);
  11935. auto res = cli.Get(
  11936. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11937. ASSERT_TRUE(res);
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11940. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11941. }
  11942. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11943. Server svr;
  11944. svr.set_trusted_proxies({"192.0.2.45"});
  11945. std::string observed_remote_addr;
  11946. std::string observed_xff;
  11947. svr.Get("/ip", [&](const Request &req, Response &res) {
  11948. observed_remote_addr = req.remote_addr;
  11949. observed_xff = req.get_header_value("X-Forwarded-For");
  11950. res.set_content("ok", "text/plain");
  11951. });
  11952. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. t.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. Client cli(HOST, PORT);
  11960. auto res =
  11961. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11962. ASSERT_TRUE(res);
  11963. EXPECT_EQ(StatusCode::OK_200, res->status);
  11964. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11965. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11966. }
  11967. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11968. Server svr;
  11969. svr.set_trusted_proxies({"192.0.2.45"});
  11970. std::string observed_remote_addr;
  11971. std::string observed_xff;
  11972. svr.Get("/ip", [&](const Request &req, Response &res) {
  11973. observed_remote_addr = req.remote_addr;
  11974. observed_xff = req.get_header_value("X-Forwarded-For");
  11975. res.set_content("ok", "text/plain");
  11976. });
  11977. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11978. auto se = detail::scope_exit([&] {
  11979. svr.stop();
  11980. t.join();
  11981. ASSERT_FALSE(svr.is_running());
  11982. });
  11983. svr.wait_until_ready();
  11984. Client cli(HOST, PORT);
  11985. auto res = cli.Get(
  11986. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11987. ASSERT_TRUE(res);
  11988. EXPECT_EQ(StatusCode::OK_200, res->status);
  11989. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11990. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11991. }
  11992. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11993. Server svr;
  11994. svr.set_trusted_proxies({"192.0.2.45"});
  11995. std::string observed_remote_addr;
  11996. std::string observed_xff;
  11997. svr.Get("/ip", [&](const Request &req, Response &res) {
  11998. observed_remote_addr = req.remote_addr;
  11999. observed_xff = req.get_header_value("X-Forwarded-For");
  12000. res.set_content("ok", "text/plain");
  12001. });
  12002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12003. auto se = detail::scope_exit([&] {
  12004. svr.stop();
  12005. t.join();
  12006. ASSERT_FALSE(svr.is_running());
  12007. });
  12008. svr.wait_until_ready();
  12009. std::string raw_req =
  12010. "GET /ip HTTP/1.1\r\n"
  12011. "Host: localhost\r\n"
  12012. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12013. "Connection: close\r\n"
  12014. "\r\n";
  12015. std::string out;
  12016. ASSERT_TRUE(send_request(5, raw_req, &out));
  12017. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12018. // Header parser trims surrounding whitespace of the header value
  12019. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12020. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12021. }
  12022. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12023. // crash the server (it used to call front() on an empty vector inside
  12024. // get_client_ip). The connection-level remote address must be retained instead.
  12025. static void run_malformed_xff_test(const std::string &xff_value) {
  12026. Server svr;
  12027. svr.set_trusted_proxies({"192.0.2.45"});
  12028. std::string observed_remote_addr;
  12029. svr.Get("/ip", [&](const Request &req, Response &res) {
  12030. observed_remote_addr = req.remote_addr;
  12031. res.set_content("ok", "text/plain");
  12032. });
  12033. int port = 0;
  12034. thread t = thread([&]() {
  12035. port = svr.bind_to_any_port(HOST);
  12036. svr.listen_after_bind();
  12037. });
  12038. auto se = detail::scope_exit([&] {
  12039. svr.stop();
  12040. t.join();
  12041. ASSERT_FALSE(svr.is_running());
  12042. });
  12043. svr.wait_until_ready();
  12044. Client cli(HOST, port);
  12045. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12046. ASSERT_TRUE(res);
  12047. EXPECT_EQ(StatusCode::OK_200, res->status);
  12048. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12049. observed_remote_addr == "127.0.0.1");
  12050. }
  12051. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12052. run_malformed_xff_test("");
  12053. }
  12054. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12055. run_malformed_xff_test(",");
  12056. }
  12057. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12058. run_malformed_xff_test(", , ,");
  12059. }
  12060. #ifndef _WIN32
  12061. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12062. Server svr;
  12063. svr.Post("/post", [&](const Request &req, Response &res) {
  12064. res.set_content(req.body, "text/plain");
  12065. });
  12066. svr.Put("/put", [&](const Request &req, Response &res) {
  12067. res.set_content(req.body, "text/plain");
  12068. });
  12069. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12070. res.set_content(req.body, "text/plain");
  12071. });
  12072. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12073. res.set_content(req.body, "text/plain");
  12074. });
  12075. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12076. auto se = detail::scope_exit([&] {
  12077. svr.stop();
  12078. t.join();
  12079. ASSERT_FALSE(svr.is_running());
  12080. });
  12081. svr.wait_until_ready();
  12082. std::string resp;
  12083. // POST without Content-Length
  12084. ASSERT_TRUE(send_request(5,
  12085. "POST /post HTTP/1.1\r\n"
  12086. "Host: localhost\r\n"
  12087. "Connection: close\r\n"
  12088. "\r\n",
  12089. &resp));
  12090. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12091. // PUT without Content-Length
  12092. resp.clear();
  12093. ASSERT_TRUE(send_request(5,
  12094. "PUT /put HTTP/1.1\r\n"
  12095. "Host: localhost\r\n"
  12096. "Connection: close\r\n"
  12097. "\r\n",
  12098. &resp));
  12099. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12100. // PATCH without Content-Length
  12101. resp.clear();
  12102. ASSERT_TRUE(send_request(5,
  12103. "PATCH /patch HTTP/1.1\r\n"
  12104. "Host: localhost\r\n"
  12105. "Connection: close\r\n"
  12106. "\r\n",
  12107. &resp));
  12108. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12109. // DELETE without Content-Length
  12110. resp.clear();
  12111. ASSERT_TRUE(send_request(5,
  12112. "DELETE /delete HTTP/1.1\r\n"
  12113. "Host: localhost\r\n"
  12114. "Connection: close\r\n"
  12115. "\r\n",
  12116. &resp));
  12117. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12118. }
  12119. #endif
  12120. //==============================================================================
  12121. // open_stream() Tests
  12122. //==============================================================================
  12123. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12124. std::string result;
  12125. char buf[8192];
  12126. ssize_t n;
  12127. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12128. result.append(buf, static_cast<size_t>(n));
  12129. }
  12130. return result;
  12131. }
  12132. // Mock stream for unit tests
  12133. class MockStream : public Stream {
  12134. public:
  12135. std::string data;
  12136. size_t pos = 0;
  12137. ssize_t error_after = -1; // -1 = no error
  12138. explicit MockStream(const std::string &d, ssize_t err = -1)
  12139. : data(d), error_after(err) {}
  12140. bool is_readable() const override { return true; }
  12141. bool wait_readable() const override { return true; }
  12142. bool wait_writable() const override { return true; }
  12143. ssize_t read(char *ptr, size_t size) override {
  12144. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12145. if (pos >= data.size()) return 0;
  12146. size_t limit =
  12147. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12148. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12149. std::memcpy(ptr, data.data() + pos, to_read);
  12150. pos += to_read;
  12151. return static_cast<ssize_t>(to_read);
  12152. }
  12153. ssize_t write(const char *, size_t) override { return -1; }
  12154. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12155. ip = "127.0.0.1";
  12156. port = 0;
  12157. }
  12158. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12159. ip = "127.0.0.1";
  12160. port = 0;
  12161. }
  12162. socket_t socket() const override { return INVALID_SOCKET; }
  12163. time_t duration() const override { return 0; }
  12164. };
  12165. TEST(StreamHandleTest, Basic) {
  12166. ClientImpl::StreamHandle handle;
  12167. EXPECT_FALSE(handle.is_valid());
  12168. handle.response = detail::make_unique<Response>();
  12169. handle.error = Error::Connection;
  12170. EXPECT_FALSE(handle.is_valid());
  12171. handle.error = Error::Success;
  12172. EXPECT_TRUE(handle.is_valid());
  12173. }
  12174. TEST(BodyReaderTest, Basic) {
  12175. MockStream stream("Hello, World!");
  12176. detail::BodyReader reader;
  12177. reader.stream = &stream;
  12178. reader.content_length = 13;
  12179. char buf[32];
  12180. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12181. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12182. EXPECT_TRUE(reader.eof);
  12183. }
  12184. TEST(BodyReaderTest, NoStream) {
  12185. detail::BodyReader reader;
  12186. char buf[32];
  12187. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12188. EXPECT_EQ(Error::Connection, reader.last_error);
  12189. }
  12190. TEST(BodyReaderTest, Error) {
  12191. MockStream stream("Hello, World!", 5);
  12192. detail::BodyReader reader;
  12193. reader.stream = &stream;
  12194. reader.content_length = 13;
  12195. char buf[32];
  12196. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12197. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12198. EXPECT_EQ(Error::Read, reader.last_error);
  12199. }
  12200. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12201. // Mock-based StreamHandle tests relying on private internals are removed.
  12202. class OpenStreamTest : public ::testing::Test {
  12203. protected:
  12204. void SetUp() override {
  12205. svr_.Get("/hello", [](const Request &, Response &res) {
  12206. res.set_content("Hello World!", "text/plain");
  12207. });
  12208. svr_.Get("/large", [](const Request &, Response &res) {
  12209. res.set_content(std::string(10000, 'X'), "text/plain");
  12210. });
  12211. svr_.Get("/chunked", [](const Request &, Response &res) {
  12212. res.set_chunked_content_provider("text/plain",
  12213. [](size_t offset, DataSink &sink) {
  12214. if (offset < 15) {
  12215. sink.write("chunk", 5);
  12216. return true;
  12217. }
  12218. sink.done();
  12219. return true;
  12220. });
  12221. });
  12222. svr_.Get("/compressible", [](const Request &, Response &res) {
  12223. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12224. DataSink &sink) {
  12225. if (offset < 100 * 1024) {
  12226. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12227. sink.write(chunk.data(), chunk.size());
  12228. return true;
  12229. }
  12230. sink.done();
  12231. return true;
  12232. });
  12233. });
  12234. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12235. [](const Request & /*req*/, Response &res) {
  12236. auto i = new int(0);
  12237. res.set_header("Trailer", "Content-Length, X-Allowed");
  12238. res.set_chunked_content_provider(
  12239. "text/plain",
  12240. [i](size_t /*offset*/, DataSink &sink) {
  12241. switch (*i) {
  12242. case 0: sink.os << "123"; break;
  12243. case 1: sink.os << "456"; break;
  12244. case 2: sink.os << "789"; break;
  12245. case 3: {
  12246. sink.done_with_trailer(
  12247. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12248. } break;
  12249. }
  12250. (*i)++;
  12251. return true;
  12252. },
  12253. [i](bool success) {
  12254. EXPECT_TRUE(success);
  12255. delete i;
  12256. });
  12257. });
  12258. // Echo headers endpoint for header-related tests
  12259. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12260. std::string body;
  12261. for (const auto &h : req.headers) {
  12262. body.append(h.first);
  12263. body.push_back(':');
  12264. body.append(h.second);
  12265. body.push_back('\n');
  12266. }
  12267. res.set_content(body, "text/plain");
  12268. });
  12269. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12270. std::string body;
  12271. for (const auto &h : req.headers) {
  12272. body.append(h.first);
  12273. body.push_back(':');
  12274. body.append(h.second);
  12275. body.push_back('\n');
  12276. }
  12277. res.set_content(body, "text/plain");
  12278. });
  12279. port_ = svr_.bind_to_any_port("127.0.0.1");
  12280. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12281. svr_.wait_until_ready();
  12282. }
  12283. void TearDown() override {
  12284. svr_.stop();
  12285. if (thread_.joinable()) thread_.join();
  12286. }
  12287. Server svr_;
  12288. std::thread thread_;
  12289. int port_ = 0;
  12290. };
  12291. TEST_F(OpenStreamTest, Basic) {
  12292. Client cli("127.0.0.1", port_);
  12293. auto handle = cli.open_stream("GET", "/hello");
  12294. EXPECT_TRUE(handle.is_valid());
  12295. EXPECT_EQ("Hello World!", read_all(handle));
  12296. }
  12297. TEST_F(OpenStreamTest, SmallBuffer) {
  12298. Client cli("127.0.0.1", port_);
  12299. auto handle = cli.open_stream("GET", "/hello");
  12300. std::string result;
  12301. char buf[4];
  12302. ssize_t n;
  12303. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12304. result.append(buf, static_cast<size_t>(n));
  12305. EXPECT_EQ("Hello World!", result);
  12306. }
  12307. TEST_F(OpenStreamTest, DefaultHeaders) {
  12308. Client cli("127.0.0.1", port_);
  12309. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12310. {
  12311. auto handle = cli.open_stream("GET", "/echo-headers");
  12312. ASSERT_TRUE(handle.is_valid());
  12313. auto body = read_all(handle);
  12314. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12315. std::string::npos);
  12316. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12317. std::string::npos);
  12318. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12319. }
  12320. // open_stream POST with body and no explicit content_type should NOT add
  12321. // text/plain Content-Type (behavior differs from non-streaming path), but
  12322. // should include Content-Length
  12323. {
  12324. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12325. ASSERT_TRUE(handle.is_valid());
  12326. auto body = read_all(handle);
  12327. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12328. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12329. }
  12330. // open_stream POST with explicit Content-Type should preserve it
  12331. {
  12332. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12333. {{"Content-Type", "application/custom"}},
  12334. "{}", "application/custom");
  12335. ASSERT_TRUE(handle.is_valid());
  12336. auto body = read_all(handle);
  12337. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12338. }
  12339. // User-specified User-Agent must not be overwritten for stream API
  12340. {
  12341. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12342. {{"User-Agent", "MyAgent/1.2"}});
  12343. ASSERT_TRUE(handle.is_valid());
  12344. auto body = read_all(handle);
  12345. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12346. }
  12347. }
  12348. TEST_F(OpenStreamTest, Large) {
  12349. Client cli("127.0.0.1", port_);
  12350. auto handle = cli.open_stream("GET", "/large");
  12351. EXPECT_EQ(10000u, read_all(handle).size());
  12352. }
  12353. TEST_F(OpenStreamTest, ConnectionError) {
  12354. Client cli("127.0.0.1", 9999);
  12355. auto handle = cli.open_stream("GET", "/hello");
  12356. EXPECT_FALSE(handle.is_valid());
  12357. }
  12358. TEST_F(OpenStreamTest, Chunked) {
  12359. Client cli("127.0.0.1", port_);
  12360. auto handle = cli.open_stream("GET", "/chunked");
  12361. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12362. "Transfer-Encoding") == "chunked");
  12363. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12364. }
  12365. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12366. Client cli("127.0.0.1", port_);
  12367. auto handle =
  12368. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12369. ASSERT_TRUE(handle.is_valid());
  12370. // Consume body to allow trailers to be received/parsed
  12371. auto body = read_all(handle);
  12372. // Explicitly parse trailers (ensure trailers are available for assertion)
  12373. handle.parse_trailers_if_needed();
  12374. EXPECT_EQ(std::string("123456789"), body);
  12375. // The response should include a Trailer header declaring both names
  12376. ASSERT_TRUE(handle.response);
  12377. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12378. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12379. handle.response->get_header_value("Trailer"));
  12380. // Prohibited trailer must not be present
  12381. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12382. // Allowed trailer should be present
  12383. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12384. EXPECT_EQ(std::string("yes"),
  12385. handle.response->get_trailer_value("X-Allowed"));
  12386. // Verify trailers are NOT present as regular headers
  12387. EXPECT_EQ(std::string(""),
  12388. handle.response->get_header_value("Content-Length"));
  12389. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12390. }
  12391. static std::thread serve_single_response(std::promise<int> &port_promise,
  12392. const std::string &response) {
  12393. return std::thread([&port_promise, response] {
  12394. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12395. default_socket_options(srv);
  12396. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12397. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12398. sockaddr_in addr{};
  12399. addr.sin_family = AF_INET;
  12400. addr.sin_port = htons(0); // Let OS assign a free port
  12401. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12402. int opt = 1;
  12403. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12404. #ifdef _WIN32
  12405. reinterpret_cast<const char *>(&opt),
  12406. #else
  12407. &opt,
  12408. #endif
  12409. sizeof(opt));
  12410. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12411. ::listen(srv, 1) != 0) {
  12412. port_promise.set_value(-1);
  12413. detail::close_socket(srv);
  12414. return;
  12415. }
  12416. socklen_t addr_len = sizeof(addr);
  12417. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12418. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12419. sockaddr_in cli_addr{};
  12420. socklen_t cli_len = sizeof(cli_addr);
  12421. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12422. if (cli != INVALID_SOCKET) {
  12423. // Read the complete HTTP request (until the blank line that terminates
  12424. // headers) before sending the response. If the server closes the socket
  12425. // while the client's request data is still unread in the kernel receive
  12426. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12427. // connection on both sides: it discards the client's receive buffer
  12428. // (which already holds our response) and causes any in-progress write on
  12429. // the client to fail with ECONNRESET. Reading all request data first
  12430. // ensures close() emits a graceful FIN.
  12431. {
  12432. char rbuf[256];
  12433. std::string req;
  12434. while (req.find("\r\n\r\n") == std::string::npos) {
  12435. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12436. if (n <= 0) { break; }
  12437. req.append(rbuf, static_cast<size_t>(n));
  12438. }
  12439. }
  12440. ::send(cli,
  12441. #ifdef _WIN32
  12442. static_cast<const char *>(response.c_str()),
  12443. static_cast<int>(response.size()),
  12444. #else
  12445. response.c_str(), response.size(),
  12446. #endif
  12447. 0);
  12448. detail::close_socket(cli);
  12449. }
  12450. detail::close_socket(srv);
  12451. });
  12452. }
  12453. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12454. #ifndef _WIN32
  12455. signal(SIGPIPE, SIG_IGN);
  12456. #endif
  12457. std::promise<int> port_promise;
  12458. auto port_future = port_promise.get_future();
  12459. auto server_thread =
  12460. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12461. "Content-Type: text/plain\r\n"
  12462. "Content-Length: not-a-number\r\n"
  12463. "Connection: close\r\n"
  12464. "\r\n"
  12465. "hello");
  12466. auto port = port_future.get();
  12467. ASSERT_GT(port, 0);
  12468. Client cli("127.0.0.1", port);
  12469. auto handle = cli.open_stream("GET", "/");
  12470. EXPECT_FALSE(handle.is_valid());
  12471. server_thread.join();
  12472. }
  12473. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12474. #ifndef _WIN32
  12475. signal(SIGPIPE, SIG_IGN);
  12476. #endif
  12477. std::promise<int> port_promise;
  12478. auto port_future = port_promise.get_future();
  12479. auto server_thread = serve_single_response(
  12480. port_promise, "HTTP/1.1 200 OK\r\n"
  12481. "Content-Type: text/plain\r\n"
  12482. "Content-Length: 99999999999999999999999999\r\n"
  12483. "Connection: close\r\n"
  12484. "\r\n"
  12485. "hello");
  12486. auto port = port_future.get();
  12487. ASSERT_GT(port, 0);
  12488. // Before the fix, std::stoull would throw std::out_of_range here and
  12489. // crash the process. After the fix, strtoull silently clamps to
  12490. // ULLONG_MAX so the stream opens without crashing. The important thing
  12491. // is that the process does NOT terminate.
  12492. Client cli("127.0.0.1", port);
  12493. auto handle = cli.open_stream("GET", "/");
  12494. EXPECT_TRUE(handle.is_valid());
  12495. server_thread.join();
  12496. }
  12497. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12498. TEST_F(OpenStreamTest, Gzip) {
  12499. Client cli("127.0.0.1", port_);
  12500. auto handle = cli.open_stream("GET", "/compressible", {},
  12501. {{"Accept-Encoding", "gzip"}});
  12502. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12503. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12504. }
  12505. #endif
  12506. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12507. TEST_F(OpenStreamTest, Brotli) {
  12508. Client cli("127.0.0.1", port_);
  12509. auto handle =
  12510. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12511. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12512. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12513. }
  12514. #endif
  12515. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12516. TEST_F(OpenStreamTest, Zstd) {
  12517. Client cli("127.0.0.1", port_);
  12518. auto handle = cli.open_stream("GET", "/compressible", {},
  12519. {{"Accept-Encoding", "zstd"}});
  12520. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12521. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12522. }
  12523. #endif
  12524. #ifdef CPPHTTPLIB_SSL_ENABLED
  12525. class SSLOpenStreamTest : public ::testing::Test {
  12526. protected:
  12527. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12528. void SetUp() override {
  12529. svr_.Get("/hello", [](const Request &, Response &res) {
  12530. res.set_content("Hello SSL World!", "text/plain");
  12531. });
  12532. svr_.Get("/chunked", [](const Request &, Response &res) {
  12533. res.set_chunked_content_provider("text/plain",
  12534. [](size_t offset, DataSink &sink) {
  12535. if (offset < 15) {
  12536. sink.write("chunk", 5);
  12537. return true;
  12538. }
  12539. sink.done();
  12540. return true;
  12541. });
  12542. });
  12543. svr_.Post("/echo", [](const Request &req, Response &res) {
  12544. res.set_content(req.body, req.get_header_value("Content-Type"));
  12545. });
  12546. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12547. std::string body = req.body;
  12548. res.set_chunked_content_provider(
  12549. "text/plain", [body](size_t offset, DataSink &sink) {
  12550. if (offset < body.size()) {
  12551. sink.write(body.data() + offset, body.size() - offset);
  12552. }
  12553. sink.done();
  12554. return true;
  12555. });
  12556. });
  12557. port_ = svr_.bind_to_any_port("127.0.0.1");
  12558. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12559. svr_.wait_until_ready();
  12560. }
  12561. void TearDown() override {
  12562. svr_.stop();
  12563. if (thread_.joinable()) thread_.join();
  12564. }
  12565. SSLServer svr_;
  12566. std::thread thread_;
  12567. int port_ = 0;
  12568. };
  12569. TEST_F(SSLOpenStreamTest, Basic) {
  12570. SSLClient cli("127.0.0.1", port_);
  12571. cli.enable_server_certificate_verification(false);
  12572. auto handle = cli.open_stream("GET", "/hello");
  12573. ASSERT_TRUE(handle.is_valid());
  12574. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12575. }
  12576. TEST_F(SSLOpenStreamTest, Chunked) {
  12577. SSLClient cli("127.0.0.1", port_);
  12578. cli.enable_server_certificate_verification(false);
  12579. auto handle = cli.open_stream("GET", "/chunked");
  12580. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12581. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12582. "Transfer-Encoding") == "chunked");
  12583. auto body = read_all(handle);
  12584. EXPECT_EQ("chunkchunkchunk", body);
  12585. }
  12586. TEST_F(SSLOpenStreamTest, Post) {
  12587. SSLClient cli("127.0.0.1", port_);
  12588. cli.enable_server_certificate_verification(false);
  12589. auto handle =
  12590. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12591. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12592. EXPECT_EQ(200, handle.response->status);
  12593. auto body = read_all(handle);
  12594. EXPECT_EQ("Hello SSL POST", body);
  12595. }
  12596. TEST_F(SSLOpenStreamTest, PostChunked) {
  12597. SSLClient cli("127.0.0.1", port_);
  12598. cli.enable_server_certificate_verification(false);
  12599. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12600. "Chunked SSL Data", "text/plain");
  12601. ASSERT_TRUE(handle.is_valid());
  12602. EXPECT_EQ(200, handle.response->status);
  12603. auto body = read_all(handle);
  12604. EXPECT_EQ("Chunked SSL Data", body);
  12605. }
  12606. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12607. // Content-Length is terminated by the server closing the connection. When the
  12608. // SSL peer sends a close_notify after the body, the client must treat it as a
  12609. // clean EOF and return a successful response rather than an error.
  12610. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12612. ASSERT_TRUE(svr.is_valid());
  12613. svr.set_keep_alive_max_count(1);
  12614. const std::string expected_body = "Hello from connection-close response!";
  12615. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12616. res.set_content_provider("text/plain",
  12617. [&](size_t offset, DataSink &sink) -> bool {
  12618. if (offset < expected_body.size()) {
  12619. sink.write(expected_body.data() + offset,
  12620. expected_body.size() - offset);
  12621. }
  12622. sink.done();
  12623. return true;
  12624. });
  12625. });
  12626. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12627. auto se = detail::scope_exit([&] {
  12628. svr.stop();
  12629. listen_thread.join();
  12630. ASSERT_FALSE(svr.is_running());
  12631. });
  12632. svr.wait_until_ready();
  12633. SSLClient cli(HOST, PORT);
  12634. cli.enable_server_certificate_verification(false);
  12635. auto res = cli.Get("/no-content-length");
  12636. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12637. EXPECT_EQ(StatusCode::OK_200, res->status);
  12638. EXPECT_EQ(expected_body, res->body);
  12639. }
  12640. #endif // CPPHTTPLIB_SSL_ENABLED
  12641. //==============================================================================
  12642. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12643. // results for various scenarios.
  12644. //==============================================================================
  12645. TEST(ParityTest, GetVsOpenStream) {
  12646. Server svr;
  12647. const std::string path = "/parity";
  12648. const std::string content = "Parity test content: hello world";
  12649. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12650. res.set_content(content, "text/plain");
  12651. });
  12652. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12653. auto se = detail::scope_exit([&] {
  12654. svr.stop();
  12655. t.join();
  12656. ASSERT_FALSE(svr.is_running());
  12657. });
  12658. svr.wait_until_ready();
  12659. Client cli(HOST, PORT);
  12660. // Non-stream path
  12661. auto r1 = cli.Get(path);
  12662. ASSERT_TRUE(r1);
  12663. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12664. // Stream path
  12665. auto h = cli.open_stream("GET", path);
  12666. ASSERT_TRUE(h.is_valid());
  12667. EXPECT_EQ(r1->body, read_all(h));
  12668. }
  12669. // Helper to compress data with provided compressor type T
  12670. template <typename Compressor>
  12671. static std::string compress_payload_for_parity(const std::string &in) {
  12672. std::string out;
  12673. Compressor compressor;
  12674. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12675. [&](const char *data, size_t n) {
  12676. out.append(data, n);
  12677. return true;
  12678. });
  12679. EXPECT_TRUE(ok);
  12680. return out;
  12681. }
  12682. // Helper function for compression parity tests
  12683. template <typename Compressor>
  12684. static void test_compression_parity(const std::string &original,
  12685. const std::string &path,
  12686. const std::string &encoding) {
  12687. const std::string compressed =
  12688. compress_payload_for_parity<Compressor>(original);
  12689. Server svr;
  12690. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12691. res.set_content(compressed, "application/octet-stream");
  12692. res.set_header("Content-Encoding", encoding);
  12693. });
  12694. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. t.join();
  12698. ASSERT_FALSE(svr.is_running());
  12699. });
  12700. svr.wait_until_ready();
  12701. Client cli(HOST, PORT);
  12702. // Non-streaming
  12703. {
  12704. auto res = cli.Get(path);
  12705. ASSERT_TRUE(res);
  12706. EXPECT_EQ(StatusCode::OK_200, res->status);
  12707. EXPECT_EQ(original, res->body);
  12708. }
  12709. // Streaming
  12710. {
  12711. auto h = cli.open_stream("GET", path);
  12712. ASSERT_TRUE(h.is_valid());
  12713. EXPECT_EQ(original, read_all(h));
  12714. }
  12715. }
  12716. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12717. TEST(ParityTest, Gzip) {
  12718. test_compression_parity<detail::gzip_compressor>(
  12719. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12720. }
  12721. #endif
  12722. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12723. TEST(ParityTest, Brotli) {
  12724. test_compression_parity<detail::brotli_compressor>(
  12725. "Hello, brotli parity test payload", "/parity-br", "br");
  12726. }
  12727. #endif
  12728. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12729. TEST(ParityTest, Zstd) {
  12730. test_compression_parity<detail::zstd_compressor>(
  12731. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12732. }
  12733. #endif
  12734. //==============================================================================
  12735. // New Stream API Tests
  12736. //==============================================================================
  12737. inline std::string read_body(httplib::stream::Result &result) {
  12738. std::string body;
  12739. while (result.next()) {
  12740. body.append(result.data(), result.size());
  12741. }
  12742. return body;
  12743. }
  12744. TEST(ClientConnectionTest, Basic) {
  12745. httplib::ClientConnection conn;
  12746. EXPECT_FALSE(conn.is_open());
  12747. conn.sock = 1;
  12748. EXPECT_TRUE(conn.is_open());
  12749. httplib::ClientConnection conn2(std::move(conn));
  12750. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12751. conn2.sock = INVALID_SOCKET;
  12752. }
  12753. // Unified test server for all stream::* tests
  12754. class StreamApiTest : public ::testing::Test {
  12755. protected:
  12756. void SetUp() override {
  12757. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12758. res.set_content("Hello World!", "text/plain");
  12759. });
  12760. svr_.Get("/echo-params",
  12761. [](const httplib::Request &req, httplib::Response &res) {
  12762. std::string r;
  12763. for (const auto &p : req.params) {
  12764. if (!r.empty()) r += "&";
  12765. r += p.first + "=" + p.second;
  12766. }
  12767. res.set_content(r, "text/plain");
  12768. });
  12769. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12770. res.set_content(req.body, req.get_header_value("Content-Type"));
  12771. });
  12772. svr_.Post("/echo-headers",
  12773. [](const httplib::Request &req, httplib::Response &res) {
  12774. std::string r;
  12775. for (const auto &h : req.headers)
  12776. r += h.first + ": " + h.second + "\n";
  12777. res.set_content(r, "text/plain");
  12778. });
  12779. svr_.Post("/echo-params",
  12780. [](const httplib::Request &req, httplib::Response &res) {
  12781. std::string r = "params:";
  12782. for (const auto &p : req.params)
  12783. r += p.first + "=" + p.second + ";";
  12784. res.set_content(r + " body:" + req.body, "text/plain");
  12785. });
  12786. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12787. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12788. });
  12789. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12790. res.set_content("PUT:" + req.body, "text/plain");
  12791. });
  12792. svr_.Patch("/echo",
  12793. [](const httplib::Request &req, httplib::Response &res) {
  12794. res.set_content("PATCH:" + req.body, "text/plain");
  12795. });
  12796. svr_.Delete(
  12797. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12798. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12799. "text/plain");
  12800. });
  12801. svr_.Get("/head-test",
  12802. [](const httplib::Request &, httplib::Response &res) {
  12803. res.set_content("body for HEAD", "text/plain");
  12804. });
  12805. svr_.Options("/options",
  12806. [](const httplib::Request &, httplib::Response &res) {
  12807. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12808. });
  12809. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12810. svr_.wait_until_ready();
  12811. }
  12812. void TearDown() override {
  12813. svr_.stop();
  12814. if (thread_.joinable()) thread_.join();
  12815. }
  12816. httplib::Server svr_;
  12817. std::thread thread_;
  12818. };
  12819. // stream::Get tests
  12820. TEST_F(StreamApiTest, GetBasic) {
  12821. httplib::Client cli(HOST, PORT);
  12822. auto result = httplib::stream::Get(cli, "/hello");
  12823. ASSERT_TRUE(result.is_valid());
  12824. EXPECT_EQ(200, result.status());
  12825. EXPECT_EQ("Hello World!", read_body(result));
  12826. }
  12827. TEST_F(StreamApiTest, GetWithParams) {
  12828. httplib::Client cli(HOST, PORT);
  12829. httplib::Params params{{"foo", "bar"}};
  12830. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12831. ASSERT_TRUE(result.is_valid());
  12832. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12833. }
  12834. TEST_F(StreamApiTest, GetConnectionError) {
  12835. httplib::Client cli(HOST, 9999);
  12836. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12837. }
  12838. TEST_F(StreamApiTest, Get404) {
  12839. httplib::Client cli(HOST, PORT);
  12840. auto result = httplib::stream::Get(cli, "/nonexistent");
  12841. EXPECT_TRUE(result.is_valid());
  12842. EXPECT_EQ(404, result.status());
  12843. }
  12844. // stream::Post tests
  12845. TEST_F(StreamApiTest, PostBasic) {
  12846. httplib::Client cli(HOST, PORT);
  12847. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12848. "application/json");
  12849. ASSERT_TRUE(result.is_valid());
  12850. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12851. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12852. }
  12853. TEST_F(StreamApiTest, PostWithHeaders) {
  12854. httplib::Client cli(HOST, PORT);
  12855. httplib::Headers headers{{"X-Custom", "value"}};
  12856. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12857. "text/plain");
  12858. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12859. }
  12860. TEST_F(StreamApiTest, PostWithParams) {
  12861. httplib::Client cli(HOST, PORT);
  12862. httplib::Params params{{"k", "v"}};
  12863. auto result =
  12864. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12865. auto body = read_body(result);
  12866. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12867. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12868. }
  12869. TEST_F(StreamApiTest, PostLarge) {
  12870. httplib::Client cli(HOST, PORT);
  12871. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12872. size_t total = 0;
  12873. while (result.next()) {
  12874. total += result.size();
  12875. }
  12876. EXPECT_EQ(100u * 1024u, total);
  12877. }
  12878. // stream::Put/Patch tests
  12879. TEST_F(StreamApiTest, PutAndPatch) {
  12880. httplib::Client cli(HOST, PORT);
  12881. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12882. EXPECT_EQ("PUT:test", read_body(put));
  12883. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12884. EXPECT_EQ("PATCH:test", read_body(patch));
  12885. }
  12886. // stream::Delete tests
  12887. TEST_F(StreamApiTest, Delete) {
  12888. httplib::Client cli(HOST, PORT);
  12889. auto del1 = httplib::stream::Delete(cli, "/resource");
  12890. EXPECT_EQ("Deleted", read_body(del1));
  12891. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12892. EXPECT_EQ("Deleted:data", read_body(del2));
  12893. }
  12894. // stream::Head/Options tests
  12895. TEST_F(StreamApiTest, HeadAndOptions) {
  12896. httplib::Client cli(HOST, PORT);
  12897. auto head = httplib::stream::Head(cli, "/head-test");
  12898. EXPECT_TRUE(head.is_valid());
  12899. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12900. auto opts = httplib::stream::Options(cli, "/options");
  12901. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12902. }
  12903. // SSL stream::* tests
  12904. #ifdef CPPHTTPLIB_SSL_ENABLED
  12905. class SSLStreamApiTest : public ::testing::Test {
  12906. protected:
  12907. void SetUp() override {
  12908. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12909. res.set_content("Hello SSL!", "text/plain");
  12910. });
  12911. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12912. res.set_content(req.body, "text/plain");
  12913. });
  12914. port_ = svr_.bind_to_any_port("127.0.0.1");
  12915. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12916. svr_.wait_until_ready();
  12917. }
  12918. void TearDown() override {
  12919. svr_.stop();
  12920. if (thread_.joinable()) thread_.join();
  12921. }
  12922. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12923. std::thread thread_;
  12924. int port_ = 0;
  12925. };
  12926. TEST_F(SSLStreamApiTest, GetAndPost) {
  12927. httplib::SSLClient cli("127.0.0.1", port_);
  12928. cli.enable_server_certificate_verification(false);
  12929. auto get = httplib::stream::Get(cli, "/hello");
  12930. EXPECT_EQ("Hello SSL!", read_body(get));
  12931. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12932. EXPECT_EQ("test", read_body(post));
  12933. }
  12934. #endif
  12935. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12936. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12937. // BodyReader
  12938. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12939. // Test that read timeout during streaming is detected
  12940. // Use a large content-length response where server delays mid-stream
  12941. Server svr;
  12942. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12943. // Send a large response with delay in the middle
  12944. res.set_content_provider(
  12945. 1000, // content_length
  12946. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12947. if (offset < 100) {
  12948. // Send first 100 bytes immediately
  12949. std::string data(100, 'A');
  12950. sink.write(data.c_str(), data.size());
  12951. return true;
  12952. }
  12953. // Then delay longer than client timeout
  12954. std::this_thread::sleep_for(std::chrono::seconds(3));
  12955. std::string data(900, 'B');
  12956. sink.write(data.c_str(), data.size());
  12957. return true;
  12958. });
  12959. });
  12960. auto port = 8091;
  12961. std::thread t([&]() { svr.listen("localhost", port); });
  12962. svr.wait_until_ready();
  12963. Client cli("localhost", port);
  12964. cli.set_read_timeout(1, 0); // 1 second timeout
  12965. auto handle = cli.open_stream("GET", "/slow-stream");
  12966. ASSERT_TRUE(handle.is_valid());
  12967. char buf[256];
  12968. ssize_t total = 0;
  12969. ssize_t n;
  12970. bool got_error = false;
  12971. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12972. total += n;
  12973. }
  12974. if (n < 0) {
  12975. got_error = true;
  12976. // Should be timeout or read error
  12977. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12978. handle.get_read_error() == Error::Read)
  12979. << "Actual error: " << to_string(handle.get_read_error());
  12980. }
  12981. // Either we got an error, or we got less data than expected
  12982. EXPECT_TRUE(got_error || total < 1000)
  12983. << "Expected timeout but got all " << total << " bytes";
  12984. svr.stop();
  12985. t.join();
  12986. }
  12987. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12988. // Test connection closed detection via BodyReader
  12989. Server svr;
  12990. std::atomic<bool> close_now{false};
  12991. svr.Get("/will-close", [&](const Request &, Response &res) {
  12992. res.set_content_provider(
  12993. 10000, // Large content_length that we won't fully send
  12994. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12995. if (offset < 100) {
  12996. std::string data(100, 'X');
  12997. sink.write(data.c_str(), data.size());
  12998. return true;
  12999. }
  13000. // Wait for signal then abort
  13001. while (!close_now) {
  13002. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13003. }
  13004. return false; // Abort - server will close connection
  13005. });
  13006. });
  13007. auto port = 8092;
  13008. std::thread t([&]() { svr.listen("localhost", port); });
  13009. svr.wait_until_ready();
  13010. Client cli("localhost", port);
  13011. auto handle = cli.open_stream("GET", "/will-close");
  13012. ASSERT_TRUE(handle.is_valid());
  13013. char buf[256];
  13014. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13015. EXPECT_GT(n, 0) << "First read should succeed";
  13016. // Signal server to close
  13017. close_now = true;
  13018. // Keep reading until error or EOF
  13019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13020. // Keep reading
  13021. }
  13022. // Should get an error since content_length wasn't satisfied
  13023. if (n < 0) {
  13024. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13025. handle.get_read_error() == Error::Read)
  13026. << "Actual error: " << to_string(handle.get_read_error());
  13027. }
  13028. svr.stop();
  13029. t.join();
  13030. }
  13031. #ifdef CPPHTTPLIB_SSL_ENABLED
  13032. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13033. // Test that read timeout during SSL streaming is detected
  13034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13035. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13036. res.set_content_provider(
  13037. 1000, "text/plain",
  13038. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13039. if (offset < 100) {
  13040. std::string data(100, 'A');
  13041. sink.write(data.c_str(), data.size());
  13042. return true;
  13043. }
  13044. std::this_thread::sleep_for(std::chrono::seconds(3));
  13045. std::string data(900, 'B');
  13046. sink.write(data.c_str(), data.size());
  13047. return true;
  13048. });
  13049. });
  13050. auto port = 8093;
  13051. std::thread t([&]() { svr.listen("localhost", port); });
  13052. svr.wait_until_ready();
  13053. SSLClient cli("localhost", port);
  13054. cli.enable_server_certificate_verification(false);
  13055. cli.set_read_timeout(1, 0); // 1 second timeout
  13056. auto handle = cli.open_stream("GET", "/slow-stream");
  13057. ASSERT_TRUE(handle.is_valid());
  13058. char buf[256];
  13059. ssize_t total = 0;
  13060. ssize_t n;
  13061. bool got_error = false;
  13062. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13063. total += n;
  13064. }
  13065. if (n < 0) {
  13066. got_error = true;
  13067. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13068. handle.get_read_error() == Error::Read)
  13069. << "Actual error: " << to_string(handle.get_read_error());
  13070. }
  13071. EXPECT_TRUE(got_error || total < 1000)
  13072. << "Expected timeout but got all " << total << " bytes";
  13073. svr.stop();
  13074. t.join();
  13075. }
  13076. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13077. // Test SSL connection closed detection
  13078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13079. std::atomic<bool> close_now{false};
  13080. svr.Get("/will-close", [&](const Request &, Response &res) {
  13081. res.set_content_provider(
  13082. 10000, "text/plain",
  13083. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13084. if (offset < 100) {
  13085. std::string data(100, 'X');
  13086. sink.write(data.c_str(), data.size());
  13087. return true;
  13088. }
  13089. while (!close_now) {
  13090. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13091. }
  13092. return false;
  13093. });
  13094. });
  13095. auto port = 8094;
  13096. std::thread t([&]() { svr.listen("localhost", port); });
  13097. svr.wait_until_ready();
  13098. SSLClient cli("localhost", port);
  13099. cli.enable_server_certificate_verification(false);
  13100. auto handle = cli.open_stream("GET", "/will-close");
  13101. ASSERT_TRUE(handle.is_valid());
  13102. char buf[256];
  13103. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13104. EXPECT_GT(n, 0);
  13105. // Signal server to close
  13106. close_now = true;
  13107. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13108. // Keep reading
  13109. }
  13110. if (n < 0) {
  13111. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13112. handle.get_read_error() == Error::Read)
  13113. << "Actual error: " << to_string(handle.get_read_error());
  13114. }
  13115. svr.stop();
  13116. t.join();
  13117. }
  13118. #endif
  13119. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13120. using namespace httplib;
  13121. // Create a test file
  13122. const char *fname = "etag_testfile.txt";
  13123. const char *content = "etag-content";
  13124. {
  13125. std::ofstream ofs(fname);
  13126. ofs << content;
  13127. ASSERT_TRUE(ofs.good());
  13128. }
  13129. Server svr;
  13130. svr.set_mount_point("/static", ".");
  13131. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13132. svr.wait_until_ready();
  13133. Client cli(HOST, PORT);
  13134. // First request: should get 200 with ETag header
  13135. auto res1 = cli.Get("/static/etag_testfile.txt");
  13136. ASSERT_TRUE(res1);
  13137. ASSERT_EQ(200, res1->status);
  13138. ASSERT_TRUE(res1->has_header("ETag"));
  13139. std::string etag = res1->get_header_value("ETag");
  13140. EXPECT_FALSE(etag.empty());
  13141. // Verify ETag format: W/"hex-hex"
  13142. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13143. EXPECT_EQ('W', etag[0]);
  13144. EXPECT_EQ('/', etag[1]);
  13145. EXPECT_EQ('"', etag[2]);
  13146. EXPECT_EQ('"', etag.back());
  13147. // Exact match: expect 304 Not Modified
  13148. Headers h2 = {{"If-None-Match", etag}};
  13149. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13150. ASSERT_TRUE(res2);
  13151. EXPECT_EQ(304, res2->status);
  13152. // Wildcard match: expect 304 Not Modified
  13153. Headers h3 = {{"If-None-Match", "*"}};
  13154. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13155. ASSERT_TRUE(res3);
  13156. EXPECT_EQ(304, res3->status);
  13157. // Non-matching ETag: expect 200
  13158. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13159. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13160. ASSERT_TRUE(res4);
  13161. EXPECT_EQ(200, res4->status);
  13162. // Multiple ETags with one matching: expect 304
  13163. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13164. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13165. ASSERT_TRUE(res5);
  13166. EXPECT_EQ(304, res5->status);
  13167. svr.stop();
  13168. t.join();
  13169. std::remove(fname);
  13170. }
  13171. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13172. using namespace httplib;
  13173. Server svr;
  13174. svr.set_mount_point("/static", ".");
  13175. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13176. svr.wait_until_ready();
  13177. Client cli(HOST, PORT);
  13178. // Send If-None-Match: * to a non-existent file
  13179. Headers h = {{"If-None-Match", "*"}};
  13180. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13181. ASSERT_TRUE(res);
  13182. EXPECT_EQ(404, res->status);
  13183. svr.stop();
  13184. t.join();
  13185. }
  13186. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13187. using namespace httplib;
  13188. // Create a test file
  13189. const char *fname = "etag_boundary_testfile.txt";
  13190. const char *content = "boundary-test";
  13191. {
  13192. std::ofstream ofs(fname);
  13193. ofs << content;
  13194. ASSERT_TRUE(ofs.good());
  13195. }
  13196. Server svr;
  13197. svr.set_mount_point("/static", ".");
  13198. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13199. svr.wait_until_ready();
  13200. Client cli(HOST, PORT);
  13201. // Get the actual ETag
  13202. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13203. ASSERT_TRUE(res1);
  13204. ASSERT_EQ(200, res1->status);
  13205. ASSERT_TRUE(res1->has_header("ETag"));
  13206. std::string etag = res1->get_header_value("ETag");
  13207. // Test 1: Very long ETag value (longer than actual ETag)
  13208. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13209. Headers h1 = {{"If-None-Match", "W/"
  13210. "\"very-long-etag-value-that-is-much-longer-"
  13211. "than-the-actual-etag-value\""}};
  13212. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13213. ASSERT_TRUE(res2);
  13214. EXPECT_EQ(200, res2->status); // Should not match
  13215. // Test 2: Long string followed by wildcard
  13216. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13217. // string)
  13218. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13219. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13220. ASSERT_TRUE(res3);
  13221. EXPECT_EQ(304, res3->status); // Should match on "*"
  13222. // Test 3: Wildcard followed by long string
  13223. // Should match on "*" immediately and return 304
  13224. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13225. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13226. ASSERT_TRUE(res4);
  13227. EXPECT_EQ(304, res4->status); // Should match on "*"
  13228. // Test 4: Multiple long non-matching values
  13229. // Should NOT match and return 200 (test that all comparisons are safe)
  13230. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13231. "W/\"second-long-non-matching-value\", "
  13232. "W/\"third-long-non-matching-value\""}};
  13233. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13234. ASSERT_TRUE(res5);
  13235. EXPECT_EQ(200, res5->status); // Should not match
  13236. // Test 5: Single character that is not "*" (edge case)
  13237. Headers h5 = {{"If-None-Match", "X"}};
  13238. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13239. ASSERT_TRUE(res6);
  13240. EXPECT_EQ(200, res6->status); // Should not match
  13241. svr.stop();
  13242. t.join();
  13243. std::remove(fname);
  13244. }
  13245. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13246. using namespace httplib;
  13247. // Create a test file
  13248. const char *fname = "ims_testfile.txt";
  13249. const char *content = "if-modified-since-test";
  13250. {
  13251. std::ofstream ofs(fname);
  13252. ofs << content;
  13253. ASSERT_TRUE(ofs.good());
  13254. }
  13255. Server svr;
  13256. svr.set_mount_point("/static", ".");
  13257. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13258. svr.wait_until_ready();
  13259. Client cli(HOST, PORT);
  13260. // First request: should get 200 with Last-Modified header
  13261. auto res1 = cli.Get("/static/ims_testfile.txt");
  13262. ASSERT_TRUE(res1);
  13263. ASSERT_EQ(200, res1->status);
  13264. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13265. std::string last_modified = res1->get_header_value("Last-Modified");
  13266. EXPECT_FALSE(last_modified.empty());
  13267. // If-Modified-Since with same time: expect 304
  13268. Headers h2 = {{"If-Modified-Since", last_modified}};
  13269. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13270. ASSERT_TRUE(res2);
  13271. EXPECT_EQ(304, res2->status);
  13272. // If-Modified-Since with future time: expect 304
  13273. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13274. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13275. ASSERT_TRUE(res3);
  13276. EXPECT_EQ(304, res3->status);
  13277. // If-Modified-Since with past time: expect 200
  13278. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13279. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13280. ASSERT_TRUE(res4);
  13281. EXPECT_EQ(200, res4->status);
  13282. // If-None-Match takes precedence over If-Modified-Since
  13283. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13284. ASSERT_TRUE(res1->has_header("ETag"));
  13285. std::string etag = res1->get_header_value("ETag");
  13286. Headers h5 = {{"If-None-Match", etag},
  13287. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13288. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13289. ASSERT_TRUE(res5);
  13290. EXPECT_EQ(304, res5->status);
  13291. svr.stop();
  13292. t.join();
  13293. std::remove(fname);
  13294. }
  13295. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13296. using namespace httplib;
  13297. Server svr;
  13298. // Endpoint that returns compressible content
  13299. svr.Get("/compressible", [](const Request &, Response &res) {
  13300. // Return a large enough body to trigger compression
  13301. std::string body(1000, 'a');
  13302. res.set_content(body, "text/plain");
  13303. });
  13304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13305. svr.wait_until_ready();
  13306. Client cli(HOST, PORT);
  13307. // Request with gzip support: should get Vary header when compressed
  13308. cli.set_compress(true);
  13309. auto res1 = cli.Get("/compressible");
  13310. ASSERT_TRUE(res1);
  13311. EXPECT_EQ(200, res1->status);
  13312. // If Content-Encoding is set, Vary should also be set
  13313. if (res1->has_header("Content-Encoding")) {
  13314. EXPECT_TRUE(res1->has_header("Vary"));
  13315. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13316. }
  13317. // Request without Accept-Encoding header: should not have compression
  13318. Headers h_no_compress;
  13319. auto res2 = cli.Get("/compressible", h_no_compress);
  13320. ASSERT_TRUE(res2);
  13321. EXPECT_EQ(200, res2->status);
  13322. // Verify Vary header is present when compression is applied
  13323. // (the exact behavior depends on server configuration)
  13324. svr.stop();
  13325. t.join();
  13326. }
  13327. TEST(ETagTest, IfRangeWithETag) {
  13328. using namespace httplib;
  13329. // Create a test file with known content
  13330. const char *fname = "if_range_testfile.txt";
  13331. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13332. {
  13333. std::ofstream ofs(fname);
  13334. ofs << content;
  13335. ASSERT_TRUE(ofs.good());
  13336. }
  13337. Server svr;
  13338. svr.set_mount_point("/static", ".");
  13339. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13340. svr.wait_until_ready();
  13341. Client cli(HOST, PORT);
  13342. // First request: get ETag
  13343. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13344. ASSERT_TRUE(res1);
  13345. ASSERT_EQ(200, res1->status);
  13346. ASSERT_TRUE(res1->has_header("ETag"));
  13347. std::string etag = res1->get_header_value("ETag");
  13348. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13349. // Since our server generates weak ETags (W/"..."), If-Range with our
  13350. // ETag should NOT result in partial content - it should return full content.
  13351. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13352. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13353. ASSERT_TRUE(res2);
  13354. // Weak ETag in If-Range -> full content (200), not partial (206)
  13355. EXPECT_EQ(200, res2->status);
  13356. EXPECT_EQ(content, res2->body);
  13357. EXPECT_FALSE(res2->has_header("Content-Range"));
  13358. // Range request with non-matching If-Range (ETag): should get 200 (full
  13359. // content)
  13360. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13361. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13362. ASSERT_TRUE(res3);
  13363. EXPECT_EQ(200, res3->status);
  13364. EXPECT_EQ(content, res3->body);
  13365. EXPECT_FALSE(res3->has_header("Content-Range"));
  13366. // Range request with strong ETag (hypothetical - our server doesn't generate
  13367. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13368. // should return full content)
  13369. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13370. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13371. ASSERT_TRUE(res4);
  13372. EXPECT_EQ(200, res4->status);
  13373. EXPECT_EQ(content, res4->body);
  13374. EXPECT_FALSE(res4->has_header("Content-Range"));
  13375. svr.stop();
  13376. t.join();
  13377. std::remove(fname);
  13378. }
  13379. TEST(ETagTest, IfRangeWithDate) {
  13380. using namespace httplib;
  13381. // Create a test file
  13382. const char *fname = "if_range_date_testfile.txt";
  13383. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13384. {
  13385. std::ofstream ofs(fname);
  13386. ofs << content;
  13387. ASSERT_TRUE(ofs.good());
  13388. }
  13389. Server svr;
  13390. svr.set_mount_point("/static", ".");
  13391. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13392. svr.wait_until_ready();
  13393. Client cli(HOST, PORT);
  13394. // First request: get Last-Modified
  13395. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13396. ASSERT_TRUE(res1);
  13397. ASSERT_EQ(200, res1->status);
  13398. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13399. std::string last_modified = res1->get_header_value("Last-Modified");
  13400. // Range request with matching If-Range (date): should get 206
  13401. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13402. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13403. ASSERT_TRUE(res2);
  13404. EXPECT_EQ(206, res2->status);
  13405. EXPECT_EQ("FGHIJ", res2->body);
  13406. // Range request with old If-Range date: should get 200 (full content)
  13407. Headers h3 = {{"Range", "bytes=5-9"},
  13408. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13409. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13410. ASSERT_TRUE(res3);
  13411. EXPECT_EQ(200, res3->status);
  13412. EXPECT_EQ(content, res3->body);
  13413. // Range request with future If-Range date: should get 206
  13414. Headers h4 = {{"Range", "bytes=0-4"},
  13415. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13416. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13417. ASSERT_TRUE(res4);
  13418. EXPECT_EQ(206, res4->status);
  13419. EXPECT_EQ("ABCDE", res4->body);
  13420. svr.stop();
  13421. t.join();
  13422. std::remove(fname);
  13423. }
  13424. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13425. using namespace httplib;
  13426. const char *fname = "etag_malformed.txt";
  13427. const char *content = "malformed-etag";
  13428. {
  13429. std::ofstream ofs(fname);
  13430. ofs << content;
  13431. ASSERT_TRUE(ofs.good());
  13432. }
  13433. Server svr;
  13434. svr.set_mount_point("/static", ".");
  13435. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13436. svr.wait_until_ready();
  13437. Client cli(HOST, PORT);
  13438. // baseline: should get 200 and an ETag
  13439. auto res1 = cli.Get("/static/etag_malformed.txt");
  13440. ASSERT_TRUE(res1);
  13441. ASSERT_EQ(200, res1->status);
  13442. ASSERT_TRUE(res1->has_header("ETag"));
  13443. // Malformed ETag value (missing quotes) should be treated as non-matching
  13444. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13445. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13446. ASSERT_TRUE(res_bad);
  13447. EXPECT_EQ(200, res_bad->status);
  13448. // Whitespace-only header value should be considered invalid / non-matching
  13449. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13450. "Host: localhost\r\n"
  13451. "If-None-Match: \r\n"
  13452. "Connection: close\r\n"
  13453. "\r\n";
  13454. std::string out;
  13455. ASSERT_TRUE(send_request(5, raw_req, &out));
  13456. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13457. svr.stop();
  13458. t.join();
  13459. std::remove(fname);
  13460. }
  13461. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13462. using namespace httplib;
  13463. const char *fname = "ims_invalid_format.txt";
  13464. const char *content = "ims-bad-format";
  13465. {
  13466. std::ofstream ofs(fname);
  13467. ofs << content;
  13468. ASSERT_TRUE(ofs.good());
  13469. }
  13470. Server svr;
  13471. svr.set_mount_point("/static", ".");
  13472. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13473. svr.wait_until_ready();
  13474. Client cli(HOST, PORT);
  13475. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13476. ASSERT_TRUE(res1);
  13477. ASSERT_EQ(200, res1->status);
  13478. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13479. // If-Modified-Since with invalid format should not result in 304
  13480. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13481. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13482. ASSERT_TRUE(res_bad);
  13483. EXPECT_EQ(200, res_bad->status);
  13484. // If-Range with invalid date format should be treated as mismatch -> full
  13485. // content (200)
  13486. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13487. {"If-Range", "invalid-date"}};
  13488. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13489. ASSERT_TRUE(res_ifrange);
  13490. EXPECT_EQ(200, res_ifrange->status);
  13491. svr.stop();
  13492. t.join();
  13493. std::remove(fname);
  13494. }
  13495. TEST(ETagTest, IfRangeWithMalformedETag) {
  13496. using namespace httplib;
  13497. const char *fname = "ifrange_malformed.txt";
  13498. const std::string content = "0123456789";
  13499. {
  13500. std::ofstream ofs(fname);
  13501. ofs << content;
  13502. ASSERT_TRUE(ofs.good());
  13503. }
  13504. Server svr;
  13505. svr.set_mount_point("/static", ".");
  13506. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13507. svr.wait_until_ready();
  13508. Client cli(HOST, PORT);
  13509. // First request: get ETag
  13510. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13511. ASSERT_TRUE(res1);
  13512. ASSERT_EQ(200, res1->status);
  13513. ASSERT_TRUE(res1->has_header("ETag"));
  13514. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13515. // full content (200)
  13516. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13517. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13518. ASSERT_TRUE(res2);
  13519. EXPECT_EQ(200, res2->status);
  13520. EXPECT_EQ(content, res2->body);
  13521. svr.stop();
  13522. t.join();
  13523. std::remove(fname);
  13524. }
  13525. TEST(ETagTest, ExtremeLargeDateValues) {
  13526. using namespace httplib;
  13527. const char *fname = "ims_extreme_date.txt";
  13528. const char *content = "ims-extreme-date";
  13529. {
  13530. std::ofstream ofs(fname);
  13531. ofs << content;
  13532. ASSERT_TRUE(ofs.good());
  13533. }
  13534. Server svr;
  13535. svr.set_mount_point("/static", ".");
  13536. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13537. svr.wait_until_ready();
  13538. Client cli(HOST, PORT);
  13539. auto res1 = cli.Get(std::string("/static/") + fname);
  13540. ASSERT_TRUE(res1);
  13541. ASSERT_EQ(200, res1->status);
  13542. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13543. // Extremely large year that may overflow date parsing routines.
  13544. Headers h_large_date = {
  13545. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13546. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13547. ASSERT_TRUE(res_bad);
  13548. // Expect server to treat this as invalid/mismatch and return full content
  13549. EXPECT_EQ(200, res_bad->status);
  13550. // If-Range with extremely large date should be treated as mismatch -> full
  13551. // content (200)
  13552. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13553. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13554. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13555. ASSERT_TRUE(res_ifrange);
  13556. EXPECT_EQ(200, res_ifrange->status);
  13557. svr.stop();
  13558. t.join();
  13559. std::remove(fname);
  13560. }
  13561. TEST(ETagTest, NegativeFileModificationTime) {
  13562. using namespace httplib;
  13563. const char *fname = "ims_negative_mtime.txt";
  13564. const std::string content = "negative-mtime";
  13565. {
  13566. std::ofstream ofs(fname);
  13567. ofs << content;
  13568. ASSERT_TRUE(ofs.good());
  13569. }
  13570. // Try to set file mtime to a negative value. This may fail on some
  13571. // platforms/filesystems; if it fails, the test will still verify server
  13572. // behaves safely by performing a regular conditional request.
  13573. #if defined(__APPLE__) || defined(__linux__)
  13574. bool set_negative = false;
  13575. do {
  13576. struct timeval times[2];
  13577. // access time: now
  13578. times[0].tv_sec = time(nullptr);
  13579. times[0].tv_usec = 0;
  13580. // modification time: negative (e.g., -1)
  13581. times[1].tv_sec = -1;
  13582. times[1].tv_usec = 0;
  13583. if (utimes(fname, times) == 0) { set_negative = true; }
  13584. } while (0);
  13585. #else
  13586. bool set_negative = false;
  13587. #endif
  13588. Server svr;
  13589. svr.set_mount_point("/static", ".");
  13590. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13591. svr.wait_until_ready();
  13592. Client cli(HOST, PORT);
  13593. auto res1 = cli.Get(std::string("/static/") + fname);
  13594. ASSERT_TRUE(res1);
  13595. ASSERT_EQ(200, res1->status);
  13596. bool has_last_modified = res1->has_header("Last-Modified");
  13597. std::string last_modified;
  13598. if (has_last_modified) {
  13599. last_modified = res1->get_header_value("Last-Modified");
  13600. }
  13601. if (set_negative) {
  13602. // If we successfully set a negative mtime, ensure server returns a
  13603. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13604. // with an old date and ensure server handles it without crash.
  13605. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13606. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13607. ASSERT_TRUE(res2);
  13608. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13609. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13610. } else {
  13611. // Could not set negative mtime on this platform; fall back to verifying
  13612. // that normal invalid/malformed dates are treated safely (non-304).
  13613. Headers h_bad_date = {
  13614. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13615. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13616. ASSERT_TRUE(res_bad);
  13617. EXPECT_EQ(200, res_bad->status);
  13618. }
  13619. svr.stop();
  13620. t.join();
  13621. std::remove(fname);
  13622. }
  13623. //==============================================================================
  13624. // SSE Parsing Tests
  13625. //==============================================================================
  13626. class SSEParsingTest : public ::testing::Test {
  13627. protected:
  13628. // Test helper that mimics SSE parsing behavior
  13629. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13630. int &retry_ms) {
  13631. // Blank line signals end of event
  13632. if (line.empty() || line == "\r") { return true; }
  13633. // Lines starting with ':' are comments (ignored)
  13634. if (!line.empty() && line[0] == ':') { return false; }
  13635. // Find the colon separator
  13636. auto colon_pos = line.find(':');
  13637. if (colon_pos == std::string::npos) {
  13638. // Line with no colon is treated as field name with empty value
  13639. return false;
  13640. }
  13641. std::string field = line.substr(0, colon_pos);
  13642. std::string value;
  13643. // Value starts after colon, skip optional single space
  13644. if (colon_pos + 1 < line.size()) {
  13645. size_t value_start = colon_pos + 1;
  13646. if (line[value_start] == ' ') { value_start++; }
  13647. value = line.substr(value_start);
  13648. // Remove trailing \r if present
  13649. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13650. }
  13651. // Handle known fields
  13652. if (field == "event") {
  13653. msg.event = value;
  13654. } else if (field == "data") {
  13655. // Multiple data lines are concatenated with newlines
  13656. if (!msg.data.empty()) { msg.data += "\n"; }
  13657. msg.data += value;
  13658. } else if (field == "id") {
  13659. // Empty id is valid (clears the last event ID)
  13660. msg.id = value;
  13661. } else if (field == "retry") {
  13662. // Parse retry interval in milliseconds
  13663. {
  13664. int v = 0;
  13665. auto res =
  13666. detail::from_chars(value.data(), value.data() + value.size(), v);
  13667. if (res.ec == std::errc{}) { retry_ms = v; }
  13668. }
  13669. }
  13670. // Unknown fields are ignored per SSE spec
  13671. return false;
  13672. }
  13673. };
  13674. // Test: Single-line data
  13675. TEST_F(SSEParsingTest, SingleLineData) {
  13676. sse::SSEMessage msg;
  13677. int retry_ms = 3000;
  13678. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13679. EXPECT_EQ(msg.data, "hello");
  13680. EXPECT_EQ(msg.event, "message");
  13681. // Blank line ends event
  13682. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13683. }
  13684. // Test: Multi-line data
  13685. TEST_F(SSEParsingTest, MultiLineData) {
  13686. sse::SSEMessage msg;
  13687. int retry_ms = 3000;
  13688. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13689. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13690. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13691. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13692. }
  13693. // Test: Custom event types
  13694. TEST_F(SSEParsingTest, CustomEventType) {
  13695. sse::SSEMessage msg;
  13696. int retry_ms = 3000;
  13697. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13698. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13699. EXPECT_EQ(msg.event, "update");
  13700. EXPECT_EQ(msg.data, "payload");
  13701. }
  13702. // Test: Event ID handling
  13703. TEST_F(SSEParsingTest, EventIdHandling) {
  13704. sse::SSEMessage msg;
  13705. int retry_ms = 3000;
  13706. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13707. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13708. EXPECT_EQ(msg.id, "12345");
  13709. }
  13710. // Test: Empty event ID (clears last event ID)
  13711. TEST_F(SSEParsingTest, EmptyEventId) {
  13712. sse::SSEMessage msg;
  13713. msg.id = "previous";
  13714. int retry_ms = 3000;
  13715. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13716. EXPECT_EQ(msg.id, "");
  13717. }
  13718. // Test: Retry field parsing
  13719. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13720. sse::SSEMessage msg;
  13721. int retry_ms = 3000;
  13722. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13723. EXPECT_EQ(retry_ms, 5000);
  13724. }
  13725. // Test: Invalid retry value
  13726. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13727. sse::SSEMessage msg;
  13728. int retry_ms = 3000;
  13729. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13730. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13731. }
  13732. // Test: Comments (lines starting with :)
  13733. TEST_F(SSEParsingTest, CommentsIgnored) {
  13734. sse::SSEMessage msg;
  13735. int retry_ms = 3000;
  13736. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13737. EXPECT_EQ(msg.data, "");
  13738. EXPECT_EQ(msg.event, "message");
  13739. }
  13740. // Test: Colon in value
  13741. TEST_F(SSEParsingTest, ColonInValue) {
  13742. sse::SSEMessage msg;
  13743. int retry_ms = 3000;
  13744. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13745. EXPECT_EQ(msg.data, "hello:world:test");
  13746. }
  13747. // Test: Line with no colon (field name only)
  13748. TEST_F(SSEParsingTest, FieldNameOnly) {
  13749. sse::SSEMessage msg;
  13750. int retry_ms = 3000;
  13751. // According to SSE spec, this is treated as field name with empty value
  13752. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13753. // Since we don't recognize "data" without colon, data should be empty
  13754. EXPECT_EQ(msg.data, "");
  13755. }
  13756. // Test: Trailing \r handling
  13757. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13758. sse::SSEMessage msg;
  13759. int retry_ms = 3000;
  13760. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13761. EXPECT_EQ(msg.data, "hello");
  13762. }
  13763. // Test: Unknown fields ignored
  13764. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13765. sse::SSEMessage msg;
  13766. int retry_ms = 3000;
  13767. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13768. EXPECT_EQ(msg.data, "");
  13769. EXPECT_EQ(msg.event, "message");
  13770. }
  13771. // Test: Space after colon is optional
  13772. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13773. sse::SSEMessage msg1, msg2;
  13774. int retry_ms = 3000;
  13775. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13776. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13777. EXPECT_EQ(msg1.data, "hello");
  13778. EXPECT_EQ(msg2.data, "hello");
  13779. }
  13780. // Test: SSEMessage clear
  13781. TEST_F(SSEParsingTest, MessageClear) {
  13782. sse::SSEMessage msg;
  13783. msg.event = "custom";
  13784. msg.data = "some data";
  13785. msg.id = "123";
  13786. msg.clear();
  13787. EXPECT_EQ(msg.event, "message");
  13788. EXPECT_EQ(msg.data, "");
  13789. EXPECT_EQ(msg.id, "");
  13790. }
  13791. // Test: Complete event parsing
  13792. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13793. sse::SSEMessage msg;
  13794. int retry_ms = 3000;
  13795. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13796. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13797. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13798. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13799. // Blank line ends event
  13800. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13801. EXPECT_EQ(msg.event, "notification");
  13802. EXPECT_EQ(msg.id, "evt-42");
  13803. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13804. EXPECT_EQ(retry_ms, 1000);
  13805. }
  13806. //==============================================================================
  13807. // Integration Tests with Server
  13808. //==============================================================================
  13809. class SSEIntegrationTest : public ::testing::Test {
  13810. protected:
  13811. void SetUp() override {
  13812. stop_server_.store(false);
  13813. events_.clear();
  13814. server_ = httplib::detail::make_unique<Server>();
  13815. setup_server();
  13816. start_server();
  13817. }
  13818. void TearDown() override {
  13819. stop_server_.store(true);
  13820. event_cv_.notify_all();
  13821. server_->stop();
  13822. if (server_thread_.joinable()) { server_thread_.join(); }
  13823. }
  13824. void setup_server() {
  13825. // Simple SSE endpoint
  13826. server_->Get("/events", [this](const Request &req, Response &res) {
  13827. auto last_id = req.get_header_value("Last-Event-ID");
  13828. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13829. res.set_chunked_content_provider(
  13830. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13831. std::unique_lock<std::mutex> lock(event_mutex_);
  13832. if (event_cv_.wait_for(
  13833. lock, std::chrono::milliseconds(200), [this] {
  13834. return !events_.empty() || stop_server_.load();
  13835. })) {
  13836. if (stop_server_.load()) { return false; }
  13837. if (!events_.empty()) {
  13838. std::string event = events_.front();
  13839. events_.erase(events_.begin());
  13840. sink.write(event.data(), event.size());
  13841. return true;
  13842. }
  13843. }
  13844. return !stop_server_.load();
  13845. });
  13846. });
  13847. // Endpoint that returns error
  13848. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13849. res.status = 500;
  13850. res.set_content("Internal Server Error", "text/plain");
  13851. });
  13852. // Endpoint for custom event types
  13853. server_->Get("/custom-events", [](const Request &, Response &res) {
  13854. res.set_chunked_content_provider(
  13855. "text/event-stream", [](size_t offset, DataSink &sink) {
  13856. if (offset == 0) {
  13857. std::string event = "event: update\ndata: updated\n\n"
  13858. "event: delete\ndata: deleted\n\n";
  13859. sink.write(event.data(), event.size());
  13860. }
  13861. return false; // End stream after sending
  13862. });
  13863. });
  13864. }
  13865. void start_server() {
  13866. port_ = server_->bind_to_any_port(HOST);
  13867. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13868. // Wait for server to start
  13869. while (!server_->is_running()) {
  13870. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13871. }
  13872. }
  13873. int get_port() const { return port_; }
  13874. void send_event(const std::string &event) {
  13875. std::lock_guard<std::mutex> lock(event_mutex_);
  13876. events_.push_back(event);
  13877. event_cv_.notify_all();
  13878. }
  13879. std::unique_ptr<Server> server_;
  13880. std::thread server_thread_;
  13881. std::mutex event_mutex_;
  13882. std::condition_variable event_cv_;
  13883. std::vector<std::string> events_;
  13884. std::atomic<bool> stop_server_{false};
  13885. std::string last_received_event_id_;
  13886. int port_ = 0;
  13887. };
  13888. // Test: Successful connection and on_open callback
  13889. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13890. // Add a simple endpoint that sends one event and closes
  13891. server_->Get("/simple-event", [](const Request &, Response &res) {
  13892. res.set_chunked_content_provider(
  13893. "text/event-stream", [](size_t offset, DataSink &sink) {
  13894. if (offset == 0) {
  13895. std::string event = "data: hello\n\n";
  13896. sink.write(event.data(), event.size());
  13897. }
  13898. return false; // Close stream after sending
  13899. });
  13900. });
  13901. Client client("localhost", get_port());
  13902. sse::SSEClient sse(client, "/simple-event");
  13903. std::atomic<bool> open_called{false};
  13904. std::atomic<bool> message_received{false};
  13905. sse.on_open([&open_called]() { open_called.store(true); });
  13906. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13907. if (msg.data == "hello") { message_received.store(true); }
  13908. });
  13909. sse.set_reconnect_interval(100);
  13910. sse.set_max_reconnect_attempts(1);
  13911. // Start async
  13912. sse.start_async();
  13913. // Wait for message to be processed
  13914. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13915. sse.stop();
  13916. EXPECT_TRUE(open_called.load());
  13917. EXPECT_TRUE(message_received.load());
  13918. }
  13919. // Test: on_message callback
  13920. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13921. // Endpoint that sends multiple events then closes
  13922. server_->Get("/multi-event", [](const Request &, Response &res) {
  13923. res.set_chunked_content_provider(
  13924. "text/event-stream", [](size_t offset, DataSink &sink) {
  13925. if (offset == 0) {
  13926. std::string events = "data: message1\n\ndata: message2\n\n";
  13927. sink.write(events.data(), events.size());
  13928. }
  13929. return false;
  13930. });
  13931. });
  13932. Client client("localhost", get_port());
  13933. sse::SSEClient sse(client, "/multi-event");
  13934. std::vector<std::string> received_messages;
  13935. std::mutex messages_mutex;
  13936. sse.on_message([&](const sse::SSEMessage &msg) {
  13937. std::lock_guard<std::mutex> lock(messages_mutex);
  13938. received_messages.push_back(msg.data);
  13939. });
  13940. sse.set_reconnect_interval(100);
  13941. sse.set_max_reconnect_attempts(1);
  13942. sse.start_async();
  13943. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13944. sse.stop();
  13945. std::lock_guard<std::mutex> lock(messages_mutex);
  13946. EXPECT_GE(received_messages.size(), 2u);
  13947. if (received_messages.size() >= 2) {
  13948. EXPECT_EQ(received_messages[0], "message1");
  13949. EXPECT_EQ(received_messages[1], "message2");
  13950. }
  13951. }
  13952. // Test: on_event for specific types
  13953. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13954. Client client("localhost", get_port());
  13955. sse::SSEClient sse(client, "/custom-events");
  13956. std::atomic<bool> update_received{false};
  13957. std::atomic<bool> delete_received{false};
  13958. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13959. if (msg.data == "updated") { update_received.store(true); }
  13960. });
  13961. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13962. if (msg.data == "deleted") { delete_received.store(true); }
  13963. });
  13964. sse.set_max_reconnect_attempts(1);
  13965. sse.start_async();
  13966. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13967. sse.stop();
  13968. EXPECT_TRUE(update_received.load());
  13969. EXPECT_TRUE(delete_received.load());
  13970. }
  13971. // Test: on_error callback on connection failure
  13972. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13973. // Connect to a non-existent port
  13974. Client client("localhost", 59999);
  13975. sse::SSEClient sse(client, "/events");
  13976. std::atomic<bool> error_called{false};
  13977. Error received_error = Error::Success;
  13978. sse.on_error([&](Error err) {
  13979. error_called.store(true);
  13980. received_error = err;
  13981. });
  13982. sse.set_reconnect_interval(50);
  13983. sse.set_max_reconnect_attempts(1);
  13984. sse.start_async();
  13985. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13986. sse.stop();
  13987. EXPECT_TRUE(error_called.load());
  13988. EXPECT_NE(received_error, Error::Success);
  13989. }
  13990. // Test: Last-Event-ID header sent on reconnect
  13991. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13992. // Endpoint that sends event with ID
  13993. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13994. res.set_chunked_content_provider(
  13995. "text/event-stream", [](size_t offset, DataSink &sink) {
  13996. if (offset == 0) {
  13997. std::string event = "id: evt-123\ndata: test\n\n";
  13998. sink.write(event.data(), event.size());
  13999. }
  14000. return false;
  14001. });
  14002. });
  14003. Client client("localhost", get_port());
  14004. sse::SSEClient sse(client, "/event-with-id");
  14005. std::atomic<bool> id_received{false};
  14006. sse.on_message([&](const sse::SSEMessage &msg) {
  14007. if (!msg.id.empty()) { id_received.store(true); }
  14008. });
  14009. sse.set_reconnect_interval(100);
  14010. sse.set_max_reconnect_attempts(1);
  14011. sse.start_async();
  14012. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14013. sse.stop();
  14014. EXPECT_TRUE(id_received.load());
  14015. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14016. }
  14017. // Test: Manual stop
  14018. TEST_F(SSEIntegrationTest, ManualStop) {
  14019. // Endpoint that sends one event and stays open briefly
  14020. std::atomic<bool> handler_running{true};
  14021. server_->Get("/stay-open", [&handler_running](const Request &,
  14022. Response &res) {
  14023. res.set_chunked_content_provider(
  14024. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14025. if (offset == 0) {
  14026. std::string event = "data: connected\n\n";
  14027. sink.write(event.data(), event.size());
  14028. }
  14029. // Keep connection open while handler_running is true
  14030. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14031. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14032. }
  14033. return false;
  14034. });
  14035. });
  14036. Client client("localhost", get_port());
  14037. sse::SSEClient sse(client, "/stay-open");
  14038. std::atomic<bool> connected{false};
  14039. sse.on_open([&connected]() { connected.store(true); });
  14040. sse.set_reconnect_interval(100);
  14041. sse.set_max_reconnect_attempts(1);
  14042. sse.start_async();
  14043. // Wait for connection to establish
  14044. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14045. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14046. }
  14047. EXPECT_TRUE(connected.load());
  14048. EXPECT_TRUE(sse.is_connected());
  14049. // Signal handler to stop
  14050. handler_running.store(false);
  14051. // Stop SSE client
  14052. sse.stop();
  14053. EXPECT_FALSE(sse.is_connected());
  14054. }
  14055. // Test: SSEClient with custom headers
  14056. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14057. // Setup a server endpoint that checks for custom header
  14058. std::atomic<bool> header_received{false};
  14059. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14060. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14061. header_received.store(true);
  14062. }
  14063. res.set_chunked_content_provider("text/event-stream",
  14064. [](size_t, DataSink &) { return false; });
  14065. });
  14066. Client client("localhost", get_port());
  14067. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14068. sse::SSEClient sse(client, "/header-check", headers);
  14069. sse.set_max_reconnect_attempts(1);
  14070. sse.start_async();
  14071. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14072. sse.stop();
  14073. EXPECT_TRUE(header_received.load());
  14074. }
  14075. // Test: Reconnect interval configuration
  14076. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14077. Client client("localhost", get_port());
  14078. sse::SSEClient sse(client, "/events");
  14079. auto &result = sse.set_reconnect_interval(500);
  14080. // Builder pattern should return reference to self
  14081. EXPECT_EQ(&result, &sse);
  14082. }
  14083. // Test: Max reconnect attempts
  14084. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14085. // Connect to non-existent port to force reconnects
  14086. Client client("localhost", 59998);
  14087. sse::SSEClient sse(client, "/events");
  14088. std::atomic<int> error_count{0};
  14089. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14090. sse.set_reconnect_interval(50);
  14091. sse.set_max_reconnect_attempts(2);
  14092. auto start = std::chrono::steady_clock::now();
  14093. sse.start(); // Blocking call
  14094. auto end = std::chrono::steady_clock::now();
  14095. // Should have stopped after 2 failed attempts
  14096. EXPECT_GE(error_count.load(), 2);
  14097. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14098. auto duration =
  14099. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14100. #ifdef _WIN32
  14101. // Windows is much slower for socket connection failures
  14102. EXPECT_LT(duration.count(), 7000);
  14103. #else
  14104. EXPECT_LT(duration.count(), 1000);
  14105. #endif
  14106. }
  14107. // Test: Multi-line data in integration
  14108. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14109. // Endpoint with multi-line data
  14110. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14111. res.set_chunked_content_provider(
  14112. "text/event-stream", [](size_t offset, DataSink &sink) {
  14113. if (offset == 0) {
  14114. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14115. sink.write(event.data(), event.size());
  14116. }
  14117. return false;
  14118. });
  14119. });
  14120. Client client("localhost", get_port());
  14121. sse::SSEClient sse(client, "/multiline-data");
  14122. std::string received_data;
  14123. std::mutex data_mutex;
  14124. sse.on_message([&](const sse::SSEMessage &msg) {
  14125. std::lock_guard<std::mutex> lock(data_mutex);
  14126. received_data = msg.data;
  14127. });
  14128. sse.set_reconnect_interval(100);
  14129. sse.set_max_reconnect_attempts(1);
  14130. sse.start_async();
  14131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14132. sse.stop();
  14133. std::lock_guard<std::mutex> lock(data_mutex);
  14134. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14135. }
  14136. // Test: Auto-reconnect after server disconnection
  14137. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14138. std::atomic<int> connection_count{0};
  14139. std::atomic<int> message_count{0};
  14140. // Endpoint that sends one event and closes, forcing reconnect
  14141. server_->Get("/reconnect-test",
  14142. [&connection_count](const Request &, Response &res) {
  14143. connection_count.fetch_add(1);
  14144. res.set_chunked_content_provider(
  14145. "text/event-stream", [](size_t offset, DataSink &sink) {
  14146. if (offset == 0) {
  14147. std::string event = "data: hello\n\n";
  14148. sink.write(event.data(), event.size());
  14149. }
  14150. return false; // Close connection after sending
  14151. });
  14152. });
  14153. Client client("localhost", get_port());
  14154. sse::SSEClient sse(client, "/reconnect-test");
  14155. sse.on_message([&message_count](const sse::SSEMessage &) {
  14156. message_count.fetch_add(1);
  14157. });
  14158. sse.set_reconnect_interval(100);
  14159. sse.set_max_reconnect_attempts(3);
  14160. sse.start_async();
  14161. // Wait long enough for multiple reconnects
  14162. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14163. sse.stop();
  14164. // Should have connected multiple times (initial + reconnects)
  14165. EXPECT_GE(connection_count.load(), 2);
  14166. // Should have received messages from multiple connections
  14167. EXPECT_GE(message_count.load(), 2);
  14168. }
  14169. // Test: Last-Event-ID sent on reconnect
  14170. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14171. std::atomic<int> connection_count{0};
  14172. std::vector<std::string> received_last_event_ids;
  14173. std::mutex id_mutex;
  14174. // Endpoint that checks Last-Event-ID header and sends event with ID
  14175. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14176. int conn = connection_count.fetch_add(1);
  14177. // Capture the Last-Event-ID header from each connection
  14178. {
  14179. std::lock_guard<std::mutex> lock(id_mutex);
  14180. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14181. }
  14182. res.set_chunked_content_provider(
  14183. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14184. if (offset == 0) {
  14185. std::string event =
  14186. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14187. sink.write(event.data(), event.size());
  14188. }
  14189. return false;
  14190. });
  14191. });
  14192. Client client("localhost", get_port());
  14193. sse::SSEClient sse(client, "/reconnect-with-id");
  14194. sse.set_reconnect_interval(100);
  14195. sse.set_max_reconnect_attempts(3);
  14196. sse.start_async();
  14197. // Wait for at least 2 connections
  14198. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14199. sse.stop();
  14200. // Verify behavior
  14201. std::lock_guard<std::mutex> lock(id_mutex);
  14202. EXPECT_GE(received_last_event_ids.size(), 2u);
  14203. // First connection should have no Last-Event-ID
  14204. if (!received_last_event_ids.empty()) {
  14205. EXPECT_EQ(received_last_event_ids[0], "");
  14206. }
  14207. // Second connection should have Last-Event-ID from first connection
  14208. if (received_last_event_ids.size() >= 2) {
  14209. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14210. }
  14211. }
  14212. // Test: set_headers updates headers used on reconnect
  14213. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14214. std::vector<std::string> received_tokens;
  14215. std::mutex token_mutex;
  14216. // Endpoint that captures Authorization header
  14217. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14218. {
  14219. std::lock_guard<std::mutex> lock(token_mutex);
  14220. received_tokens.push_back(req.get_header_value("Authorization"));
  14221. }
  14222. res.set_chunked_content_provider(
  14223. "text/event-stream", [](size_t offset, DataSink &sink) {
  14224. if (offset == 0) {
  14225. std::string event = "data: hello\n\n";
  14226. sink.write(event.data(), event.size());
  14227. }
  14228. return false; // Close connection to trigger reconnect
  14229. });
  14230. });
  14231. Client client("localhost", get_port());
  14232. Headers headers = {{"Authorization", "Bearer old-token"}};
  14233. sse::SSEClient sse(client, "/auth-check", headers);
  14234. // Update headers on each successful connection
  14235. sse.on_open(
  14236. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14237. sse.set_reconnect_interval(100);
  14238. sse.set_max_reconnect_attempts(3);
  14239. sse.start_async();
  14240. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14241. sse.stop();
  14242. std::lock_guard<std::mutex> lock(token_mutex);
  14243. ASSERT_GE(received_tokens.size(), 2u);
  14244. // First connection uses original header
  14245. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14246. // Second connection uses updated header from set_headers
  14247. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14248. }
  14249. // Test: 401 allows reconnection (so on_error can refresh headers)
  14250. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14251. std::atomic<int> connection_count{0};
  14252. // Endpoint: returns 401 on first attempt, 200 on second
  14253. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14254. int conn = connection_count.fetch_add(1);
  14255. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14256. res.status = StatusCode::Unauthorized_401;
  14257. res.set_content("Unauthorized", "text/plain");
  14258. return;
  14259. }
  14260. res.set_chunked_content_provider(
  14261. "text/event-stream", [](size_t offset, DataSink &sink) {
  14262. if (offset == 0) {
  14263. std::string event = "data: authenticated\n\n";
  14264. sink.write(event.data(), event.size());
  14265. }
  14266. return false;
  14267. });
  14268. });
  14269. Client client("localhost", get_port());
  14270. Headers headers = {{"Authorization", "Bearer expired"}};
  14271. sse::SSEClient sse(client, "/auth-retry", headers);
  14272. std::atomic<bool> message_received{false};
  14273. // Refresh token on error
  14274. sse.on_error(
  14275. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14276. sse.on_message([&](const sse::SSEMessage &msg) {
  14277. if (msg.data == "authenticated") { message_received.store(true); }
  14278. });
  14279. sse.set_reconnect_interval(100);
  14280. sse.set_max_reconnect_attempts(3);
  14281. sse.start_async();
  14282. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14283. sse.stop();
  14284. // Should have reconnected after 401 and succeeded with new token
  14285. EXPECT_GE(connection_count.load(), 2);
  14286. EXPECT_TRUE(message_received.load());
  14287. }
  14288. TEST(Issue2318Test, EmptyHostString) {
  14289. {
  14290. httplib::Client cli_empty("", PORT);
  14291. auto res = cli_empty.Get("/");
  14292. ASSERT_FALSE(res);
  14293. EXPECT_EQ(httplib::Error::Connection, res.error());
  14294. }
  14295. {
  14296. httplib::Client cli(" ", PORT);
  14297. auto res = cli.Get("/");
  14298. ASSERT_FALSE(res);
  14299. EXPECT_EQ(httplib::Error::Connection, res.error());
  14300. }
  14301. }
  14302. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14303. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14304. Server svr;
  14305. // Set a small payload limit (1KB)
  14306. svr.set_payload_max_length(1024);
  14307. svr.Post("/test", [&](const Request &req, Response &res) {
  14308. res.set_content("Body size: " + std::to_string(req.body.size()),
  14309. "text/plain");
  14310. });
  14311. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14312. auto se = detail::scope_exit([&] {
  14313. svr.stop();
  14314. listen_thread.join();
  14315. });
  14316. svr.wait_until_ready();
  14317. // Create data that compresses well but exceeds limit when decompressed
  14318. // 8KB of repeated null bytes compresses to a very small size
  14319. std::string original_data(8 * 1024, '\0');
  14320. // Compress the data using gzip
  14321. std::string compressed_data;
  14322. detail::gzip_compressor compressor;
  14323. compressor.compress(original_data.data(), original_data.size(), true,
  14324. [&](const char *data, size_t size) {
  14325. compressed_data.append(data, size);
  14326. return true;
  14327. });
  14328. // Verify compression worked (compressed should be much smaller)
  14329. ASSERT_LT(compressed_data.size(), original_data.size());
  14330. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14331. // Send compressed data with Content-Encoding: gzip
  14332. Client cli(HOST, PORT);
  14333. Headers headers = {{"Content-Encoding", "gzip"}};
  14334. auto res =
  14335. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14336. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14337. ASSERT_TRUE(res);
  14338. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14339. }
  14340. #endif
  14341. // ============================================================================
  14342. // OpenSSL-Specific Tests
  14343. // ============================================================================
  14344. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14345. X509 *readCertificate(const std::string &strFileName) {
  14346. std::ifstream inStream(strFileName);
  14347. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14348. std::istreambuf_iterator<char>());
  14349. if (strCertPEM.empty()) return (nullptr);
  14350. BIO *pbCert = BIO_new(BIO_s_mem());
  14351. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14352. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14353. BIO_free(pbCert);
  14354. return (pCert);
  14355. }
  14356. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14357. std::ifstream inStream(strFileName);
  14358. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14359. std::istreambuf_iterator<char>());
  14360. if (strPrivateKeyPEM.empty()) return (nullptr);
  14361. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14362. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14363. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14364. BIO_free(pbPrivKey);
  14365. return (pPrivateKey);
  14366. }
  14367. TEST(BindServerTest, UpdateCerts) {
  14368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14369. int port = svr.bind_to_any_port("0.0.0.0");
  14370. ASSERT_TRUE(svr.is_valid());
  14371. ASSERT_TRUE(port > 0);
  14372. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14373. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14374. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14375. ASSERT_TRUE(cert != nullptr);
  14376. ASSERT_TRUE(ca_cert != nullptr);
  14377. ASSERT_TRUE(key != nullptr);
  14378. X509_STORE *cert_store = X509_STORE_new();
  14379. X509_STORE_add_cert(cert_store, ca_cert);
  14380. // svr.update_certs(cert, key, cert_store); // deprecated
  14381. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14382. CLIENT_CA_CERT_FILE);
  14383. ASSERT_TRUE(svr.is_valid());
  14384. svr.stop();
  14385. X509_STORE_free(cert_store);
  14386. X509_free(cert);
  14387. X509_free(ca_cert);
  14388. EVP_PKEY_free(key);
  14389. }
  14390. // Test that update_certs() updates client CA list correctly
  14391. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14392. // Start with file-based constructor
  14393. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14394. ASSERT_TRUE(svr.is_valid());
  14395. // Initially no client CA list should be set
  14396. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14397. ASSERT_TRUE(ssl_ctx != nullptr);
  14398. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14399. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14400. EXPECT_EQ(0, count_before);
  14401. // Now update with client CA (PEM string)
  14402. std::string cert_pem, key_pem, ca_pem;
  14403. read_file(SERVER_CERT_FILE, cert_pem);
  14404. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14405. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14406. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14407. ASSERT_TRUE(svr.is_valid());
  14408. // Now client CA list should be set
  14409. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14410. ASSERT_TRUE(ca_list_after != nullptr);
  14411. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14412. }
  14413. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14414. // Test that the file-path SSLServer constructor properly sets the client CA
  14415. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14417. ASSERT_TRUE(svr.is_valid());
  14418. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14419. ASSERT_TRUE(ssl_ctx != nullptr);
  14420. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14421. ASSERT_TRUE(ca_list != nullptr);
  14422. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14423. }
  14424. #endif
  14425. // ============================================================================
  14426. // MbedTLS-Specific Tests
  14427. // ============================================================================
  14428. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14429. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14430. using namespace httplib::tls;
  14431. // Track if callback was invoked
  14432. bool callback_invoked = false;
  14433. // The callback receives void* ctx which is actually MbedTlsContext*
  14434. // We can access the mbedtls_ssl_config via the context
  14435. auto setup_callback = [&callback_invoked](void *ctx) {
  14436. callback_invoked = true;
  14437. // Cast to MbedTlsContext* to access the ssl config
  14438. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14439. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14440. // Use static variables to hold certificate data (simplified for test)
  14441. static mbedtls_x509_crt own_cert;
  14442. static mbedtls_pk_context own_key;
  14443. static mbedtls_x509_crt ca_chain;
  14444. static bool initialized = false;
  14445. if (!initialized) {
  14446. mbedtls_x509_crt_init(&own_cert);
  14447. mbedtls_pk_init(&own_key);
  14448. mbedtls_x509_crt_init(&ca_chain);
  14449. // Load server certificate
  14450. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14451. return false;
  14452. }
  14453. // Load server private key
  14454. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14455. #if MBEDTLS_VERSION_MAJOR >= 3
  14456. ,
  14457. mbedtls_ctr_drbg_random, nullptr
  14458. #endif
  14459. ) != 0) {
  14460. return false;
  14461. }
  14462. // Load CA chain for client verification
  14463. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14464. return false;
  14465. }
  14466. initialized = true;
  14467. }
  14468. // Configure the SSL config
  14469. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14470. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14471. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14472. // Set minimum TLS version using mbedTLS native API
  14473. #if MBEDTLS_VERSION_MAJOR >= 3
  14474. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14475. #else
  14476. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14477. MBEDTLS_SSL_MINOR_VERSION_3);
  14478. #endif
  14479. return true;
  14480. };
  14481. SSLServer svr(setup_callback);
  14482. ASSERT_TRUE(svr.is_valid());
  14483. ASSERT_TRUE(callback_invoked);
  14484. svr.Get("/test", [&](const Request &req, Response &res) {
  14485. res.set_content("test", "text/plain");
  14486. auto cert = req.peer_cert();
  14487. ASSERT_TRUE(static_cast<bool>(cert));
  14488. auto common_name = cert.subject_cn();
  14489. EXPECT_EQ("Common Name", common_name);
  14490. });
  14491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14492. auto se = detail::scope_exit([&] {
  14493. svr.stop();
  14494. t.join();
  14495. ASSERT_FALSE(svr.is_running());
  14496. });
  14497. svr.wait_until_ready();
  14498. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14499. cli.enable_server_certificate_verification(false);
  14500. cli.set_connection_timeout(30);
  14501. auto res = cli.Get("/test");
  14502. ASSERT_TRUE(res);
  14503. ASSERT_EQ(StatusCode::OK_200, res->status);
  14504. }
  14505. #endif
  14506. // WebSocket Tests
  14507. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14508. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14509. // defining the meaning of these bits has been negotiated.
  14510. auto make_frame = [](uint8_t first_byte) {
  14511. std::string frame;
  14512. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14513. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14514. frame += "Hello";
  14515. return frame;
  14516. };
  14517. // RSV1 set (0x40)
  14518. {
  14519. detail::BufferStream strm;
  14520. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14521. ws::Opcode opcode;
  14522. std::string payload;
  14523. bool fin;
  14524. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14525. false, 1024));
  14526. }
  14527. // RSV2 set (0x20)
  14528. {
  14529. detail::BufferStream strm;
  14530. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14531. ws::Opcode opcode;
  14532. std::string payload;
  14533. bool fin;
  14534. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14535. false, 1024));
  14536. }
  14537. // RSV3 set (0x10)
  14538. {
  14539. detail::BufferStream strm;
  14540. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14541. ws::Opcode opcode;
  14542. std::string payload;
  14543. bool fin;
  14544. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14545. false, 1024));
  14546. }
  14547. // No RSV bits set - should succeed
  14548. {
  14549. detail::BufferStream strm;
  14550. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14551. ws::Opcode opcode;
  14552. std::string payload;
  14553. bool fin;
  14554. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14555. false, 1024));
  14556. EXPECT_EQ(ws::Opcode::Text, opcode);
  14557. EXPECT_EQ("Hello", payload);
  14558. EXPECT_TRUE(fin);
  14559. }
  14560. }
  14561. TEST(WebSocketTest, ControlFrameValidation) {
  14562. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14563. // payload length <= 125.
  14564. // Ping with FIN=0 - must be rejected
  14565. {
  14566. detail::BufferStream strm;
  14567. std::string frame;
  14568. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14569. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14570. strm.write(frame.data(), frame.size());
  14571. ws::Opcode opcode;
  14572. std::string payload;
  14573. bool fin;
  14574. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14575. false, 1024));
  14576. }
  14577. // Close with FIN=0 - must be rejected
  14578. {
  14579. detail::BufferStream strm;
  14580. std::string frame;
  14581. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14582. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14583. strm.write(frame.data(), frame.size());
  14584. ws::Opcode opcode;
  14585. std::string payload;
  14586. bool fin;
  14587. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14588. false, 1024));
  14589. }
  14590. // Ping with payload_len=126 (extended length) - must be rejected
  14591. {
  14592. detail::BufferStream strm;
  14593. std::string frame;
  14594. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14595. frame += static_cast<char>(126); // payload_len=126 (>125)
  14596. frame += static_cast<char>(0x00); // extended length high byte
  14597. frame += static_cast<char>(126); // extended length low byte
  14598. frame += std::string(126, 'x');
  14599. strm.write(frame.data(), frame.size());
  14600. ws::Opcode opcode;
  14601. std::string payload;
  14602. bool fin;
  14603. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14604. false, 1024));
  14605. }
  14606. // Ping with FIN=1 and payload_len=125 - should succeed
  14607. {
  14608. detail::BufferStream strm;
  14609. std::string frame;
  14610. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14611. frame += static_cast<char>(125); // payload_len=125
  14612. frame += std::string(125, 'x');
  14613. strm.write(frame.data(), frame.size());
  14614. ws::Opcode opcode;
  14615. std::string payload;
  14616. bool fin;
  14617. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14618. false, 1024));
  14619. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14620. EXPECT_EQ(125u, payload.size());
  14621. EXPECT_TRUE(fin);
  14622. }
  14623. }
  14624. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14625. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14626. // length MUST be 0.
  14627. // MSB set - must be rejected
  14628. {
  14629. detail::BufferStream strm;
  14630. std::string frame;
  14631. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14632. frame += static_cast<char>(127); // 64-bit extended length
  14633. frame += static_cast<char>(0x80); // MSB set (invalid)
  14634. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14635. strm.write(frame.data(), frame.size());
  14636. ws::Opcode opcode;
  14637. std::string payload;
  14638. bool fin;
  14639. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14640. false, 1024));
  14641. }
  14642. // MSB clear - should pass length parsing (will be rejected by max_len,
  14643. // but that's a different check; use a small length to verify)
  14644. {
  14645. detail::BufferStream strm;
  14646. std::string frame;
  14647. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14648. frame += static_cast<char>(127); // 64-bit extended length
  14649. frame += std::string(7, '\0'); // high bytes = 0
  14650. frame += static_cast<char>(0x03); // length = 3
  14651. frame += "abc";
  14652. strm.write(frame.data(), frame.size());
  14653. ws::Opcode opcode;
  14654. std::string payload;
  14655. bool fin;
  14656. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14657. false, 1024));
  14658. EXPECT_EQ(ws::Opcode::Text, opcode);
  14659. EXPECT_EQ("abc", payload);
  14660. }
  14661. }
  14662. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14663. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14664. // Valid UTF-8
  14665. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14666. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14667. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14668. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14669. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14670. // Invalid UTF-8
  14671. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14672. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14673. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14674. EXPECT_FALSE(
  14675. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14676. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14677. }
  14678. TEST(WebSocketTest, ConnectAndDisconnect) {
  14679. Server svr;
  14680. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14681. std::string msg;
  14682. while (ws.read(msg)) {}
  14683. });
  14684. auto port = svr.bind_to_any_port(HOST);
  14685. std::thread t([&]() { svr.listen_after_bind(); });
  14686. svr.wait_until_ready();
  14687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14688. ASSERT_TRUE(client.connect());
  14689. EXPECT_TRUE(client.is_open());
  14690. client.close();
  14691. EXPECT_FALSE(client.is_open());
  14692. svr.stop();
  14693. t.join();
  14694. }
  14695. TEST(WebSocketTest, ValidURL) {
  14696. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14697. EXPECT_TRUE(ws1.is_valid());
  14698. ws::WebSocketClient ws2("ws://example.com/path");
  14699. EXPECT_TRUE(ws2.is_valid());
  14700. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14701. EXPECT_TRUE(ws3.is_valid());
  14702. #ifdef CPPHTTPLIB_SSL_ENABLED
  14703. ws::WebSocketClient wss1("wss://example.com/path");
  14704. EXPECT_TRUE(wss1.is_valid());
  14705. ws::WebSocketClient wss2("wss://example.com:443/path");
  14706. EXPECT_TRUE(wss2.is_valid());
  14707. #endif
  14708. }
  14709. TEST(WebSocketTest, InvalidURL) {
  14710. // No scheme
  14711. ws::WebSocketClient ws1("localhost:8080/path");
  14712. EXPECT_FALSE(ws1.is_valid());
  14713. // No path
  14714. ws::WebSocketClient ws2("ws://localhost:8080");
  14715. EXPECT_FALSE(ws2.is_valid());
  14716. // Empty string
  14717. ws::WebSocketClient ws3("");
  14718. EXPECT_FALSE(ws3.is_valid());
  14719. // Missing host
  14720. ws::WebSocketClient ws4("ws://:8080/path");
  14721. EXPECT_FALSE(ws4.is_valid());
  14722. // Port number overflow — should not crash
  14723. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14724. EXPECT_FALSE(ws5.is_valid());
  14725. // Port out of range
  14726. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14727. EXPECT_FALSE(ws6.is_valid());
  14728. }
  14729. TEST(WebSocketTest, UnsupportedScheme) {
  14730. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14731. ws::WebSocketClient ws1("http://localhost:8080/path");
  14732. EXPECT_FALSE(ws1.is_valid());
  14733. ws::WebSocketClient ws2("https://localhost:8080/path");
  14734. EXPECT_FALSE(ws2.is_valid());
  14735. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14736. EXPECT_FALSE(ws3.is_valid());
  14737. #else
  14738. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14739. std::invalid_argument);
  14740. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14741. std::invalid_argument);
  14742. #endif
  14743. }
  14744. TEST(WebSocketTest, ConnectWhenInvalid) {
  14745. ws::WebSocketClient ws("not a valid url");
  14746. EXPECT_FALSE(ws.is_valid());
  14747. EXPECT_FALSE(ws.connect());
  14748. }
  14749. TEST(WebSocketTest, DefaultPort) {
  14750. ws::WebSocketClient ws1("ws://example.com/path");
  14751. EXPECT_TRUE(ws1.is_valid());
  14752. // ws:// defaults to port 80 (verified by successful parse)
  14753. #ifdef CPPHTTPLIB_SSL_ENABLED
  14754. ws::WebSocketClient ws2("wss://example.com/path");
  14755. EXPECT_TRUE(ws2.is_valid());
  14756. // wss:// defaults to port 443 (verified by successful parse)
  14757. #endif
  14758. }
  14759. TEST(WebSocketTest, IPv6LiteralAddress) {
  14760. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14761. EXPECT_TRUE(ws1.is_valid());
  14762. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14763. EXPECT_TRUE(ws2.is_valid());
  14764. }
  14765. TEST(WebSocketTest, ComplexPath) {
  14766. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14767. EXPECT_TRUE(ws1.is_valid());
  14768. ws::WebSocketClient ws2("ws://localhost:8080/");
  14769. EXPECT_TRUE(ws2.is_valid());
  14770. }
  14771. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  14772. Server svr;
  14773. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14774. std::string msg;
  14775. while (ws.read(msg)) {}
  14776. });
  14777. auto port = svr.bind_to_any_port(HOST);
  14778. std::thread t([&]() { svr.listen_after_bind(); });
  14779. svr.wait_until_ready();
  14780. auto another_host = "example.com";
  14781. auto wrong_ip = "192.0.2.1";
  14782. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14783. client.set_hostname_addr_map({{another_host, wrong_ip}});
  14784. ASSERT_TRUE(client.connect());
  14785. EXPECT_TRUE(client.is_open());
  14786. client.close();
  14787. svr.stop();
  14788. t.join();
  14789. }
  14790. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  14791. Server svr;
  14792. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14793. std::string msg;
  14794. while (ws.read(msg)) {}
  14795. });
  14796. auto port = svr.bind_to_any_port(HOST);
  14797. std::thread t([&]() { svr.listen_after_bind(); });
  14798. svr.wait_until_ready();
  14799. auto wrong_ip = "192.0.2.1";
  14800. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14801. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  14802. client.set_connection_timeout(1);
  14803. client.set_read_timeout(1);
  14804. client.set_write_timeout(1);
  14805. EXPECT_FALSE(client.connect());
  14806. EXPECT_FALSE(client.is_open());
  14807. svr.stop();
  14808. t.join();
  14809. }
  14810. class WebSocketIntegrationTest : public ::testing::Test {
  14811. protected:
  14812. void SetUp() override {
  14813. server_ = httplib::detail::make_unique<Server>();
  14814. setup_server();
  14815. start_server();
  14816. }
  14817. void TearDown() override {
  14818. server_->stop();
  14819. if (server_thread_.joinable()) { server_thread_.join(); }
  14820. }
  14821. void setup_server() {
  14822. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14823. std::string msg;
  14824. ws::ReadResult ret;
  14825. while ((ret = ws.read(msg))) {
  14826. if (ret == ws::Binary) {
  14827. ws.send(msg.data(), msg.size());
  14828. } else {
  14829. ws.send(msg);
  14830. }
  14831. }
  14832. });
  14833. server_->WebSocket("/ws-echo-string",
  14834. [](const Request &, ws::WebSocket &ws) {
  14835. std::string msg;
  14836. while (ws.read(msg)) {
  14837. ws.send("echo: " + msg);
  14838. }
  14839. });
  14840. server_->WebSocket(
  14841. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14842. // Echo back request metadata
  14843. ws.send("path:" + req.path);
  14844. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14845. std::string msg;
  14846. while (ws.read(msg)) {}
  14847. });
  14848. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14849. std::string msg;
  14850. ws.read(msg); // wait for a message
  14851. ws.close();
  14852. });
  14853. server_->WebSocket("/ws-close-status",
  14854. [](const Request &, ws::WebSocket &ws) {
  14855. std::string msg;
  14856. ws.read(msg); // wait for a message
  14857. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14858. });
  14859. server_->WebSocket(
  14860. "/ws-subprotocol",
  14861. [](const Request &, ws::WebSocket &ws) {
  14862. std::string msg;
  14863. while (ws.read(msg)) {
  14864. ws.send(msg);
  14865. }
  14866. },
  14867. [](const std::vector<std::string> &protocols) -> std::string {
  14868. for (const auto &p : protocols) {
  14869. if (p == "graphql-ws") { return p; }
  14870. }
  14871. return "";
  14872. });
  14873. }
  14874. void start_server() {
  14875. port_ = server_->bind_to_any_port(HOST);
  14876. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14877. server_->wait_until_ready();
  14878. }
  14879. std::unique_ptr<Server> server_;
  14880. std::thread server_thread_;
  14881. int port_ = 0;
  14882. };
  14883. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14884. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14885. "/ws-echo");
  14886. ASSERT_TRUE(client.connect());
  14887. ASSERT_TRUE(client.is_open());
  14888. ASSERT_TRUE(client.send("Hello WebSocket"));
  14889. std::string msg;
  14890. EXPECT_EQ(ws::Text, client.read(msg));
  14891. EXPECT_EQ("Hello WebSocket", msg);
  14892. client.close();
  14893. }
  14894. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14896. "/ws-echo");
  14897. ASSERT_TRUE(client.connect());
  14898. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14899. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14900. std::string msg;
  14901. EXPECT_EQ(ws::Binary, client.read(msg));
  14902. EXPECT_EQ(binary_data, msg);
  14903. client.close();
  14904. }
  14905. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14907. "/ws-echo");
  14908. ASSERT_TRUE(client.connect());
  14909. for (int i = 0; i < 10; i++) {
  14910. auto text = "message " + std::to_string(i);
  14911. ASSERT_TRUE(client.send(text));
  14912. std::string msg;
  14913. ASSERT_TRUE(client.read(msg));
  14914. EXPECT_EQ(text, msg);
  14915. }
  14916. client.close();
  14917. }
  14918. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14920. "/ws-close");
  14921. ASSERT_TRUE(client.connect());
  14922. // Send a message to trigger the server to close
  14923. ASSERT_TRUE(client.send("trigger close"));
  14924. // The server will close, so read should return false
  14925. std::string msg;
  14926. EXPECT_FALSE(client.read(msg));
  14927. EXPECT_FALSE(client.is_open());
  14928. }
  14929. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14931. "/ws-echo");
  14932. ASSERT_TRUE(client.connect());
  14933. // 128KB message
  14934. std::string large_data(128 * 1024, 'X');
  14935. ASSERT_TRUE(client.send(large_data));
  14936. std::string msg;
  14937. ASSERT_TRUE(client.read(msg));
  14938. EXPECT_EQ(large_data, msg);
  14939. client.close();
  14940. }
  14941. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14943. "/ws-echo");
  14944. ASSERT_TRUE(client.connect());
  14945. const int num_threads = 4;
  14946. std::vector<std::thread> threads;
  14947. std::atomic<int> send_count{0};
  14948. for (int t = 0; t < num_threads; t++) {
  14949. threads.emplace_back([&client, &send_count, t]() {
  14950. for (int i = 0; i < 5; i++) {
  14951. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14952. if (client.send(text)) { send_count++; }
  14953. }
  14954. });
  14955. }
  14956. for (auto &th : threads) {
  14957. th.join();
  14958. }
  14959. int received = 0;
  14960. std::string msg;
  14961. while (received < send_count.load()) {
  14962. if (!client.read(msg)) { break; }
  14963. received++;
  14964. }
  14965. EXPECT_EQ(send_count.load(), received);
  14966. client.close();
  14967. }
  14968. TEST_F(WebSocketIntegrationTest, ReadString) {
  14969. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14970. "/ws-echo-string");
  14971. ASSERT_TRUE(client.connect());
  14972. ASSERT_TRUE(client.send("hello"));
  14973. std::string msg;
  14974. ASSERT_TRUE(client.read(msg));
  14975. EXPECT_EQ("echo: hello", msg);
  14976. ASSERT_TRUE(client.send("world"));
  14977. ASSERT_TRUE(client.read(msg));
  14978. EXPECT_EQ("echo: world", msg);
  14979. client.close();
  14980. }
  14981. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14982. Headers headers = {{"X-Test-Header", "test-value"}};
  14983. ws::WebSocketClient client(
  14984. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14985. ASSERT_TRUE(client.connect());
  14986. std::string msg;
  14987. ASSERT_TRUE(client.read(msg));
  14988. EXPECT_EQ("path:/ws-request-info", msg);
  14989. ASSERT_TRUE(client.read(msg));
  14990. EXPECT_EQ("header:test-value", msg);
  14991. client.close();
  14992. }
  14993. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14995. "/ws-echo");
  14996. client.set_read_timeout(1, 0); // 1 second
  14997. ASSERT_TRUE(client.connect());
  14998. // Don't send anything — server echo handler waits for a message,
  14999. // so read() should time out and return false.
  15000. std::string msg;
  15001. EXPECT_FALSE(client.read(msg));
  15002. }
  15003. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15005. "/ws-echo");
  15006. client.set_read_timeout(5, 0);
  15007. ASSERT_TRUE(client.connect());
  15008. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15009. // The server should reject it and close the connection.
  15010. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15011. client.send(oversized);
  15012. // The server's read() should have failed due to payload limit,
  15013. // so our read() should return false (connection closed).
  15014. std::string msg;
  15015. EXPECT_FALSE(client.read(msg));
  15016. }
  15017. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15019. "/ws-echo");
  15020. client.set_read_timeout(10, 0);
  15021. ASSERT_TRUE(client.connect());
  15022. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15023. // This should succeed.
  15024. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15025. ASSERT_TRUE(client.send(at_limit));
  15026. std::string msg;
  15027. ASSERT_TRUE(client.read(msg));
  15028. EXPECT_EQ(at_limit.size(), msg.size());
  15029. client.close();
  15030. }
  15031. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15033. "/nonexistent");
  15034. EXPECT_FALSE(client.connect());
  15035. EXPECT_FALSE(client.is_open());
  15036. }
  15037. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15039. "/ws-echo");
  15040. ASSERT_TRUE(client.connect());
  15041. ASSERT_TRUE(client.send(""));
  15042. std::string msg;
  15043. EXPECT_EQ(ws::Text, client.read(msg));
  15044. EXPECT_EQ("", msg);
  15045. client.close();
  15046. }
  15047. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15048. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15049. "/ws-echo");
  15050. // First connection
  15051. ASSERT_TRUE(client.connect());
  15052. ASSERT_TRUE(client.send("first"));
  15053. std::string msg;
  15054. ASSERT_TRUE(client.read(msg));
  15055. EXPECT_EQ("first", msg);
  15056. client.close();
  15057. EXPECT_FALSE(client.is_open());
  15058. // Reconnect using the same client object
  15059. ASSERT_TRUE(client.connect());
  15060. ASSERT_TRUE(client.is_open());
  15061. ASSERT_TRUE(client.send("second"));
  15062. ASSERT_TRUE(client.read(msg));
  15063. EXPECT_EQ("second", msg);
  15064. client.close();
  15065. }
  15066. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15068. "/ws-close-status");
  15069. ASSERT_TRUE(client.connect());
  15070. // Trigger the server to close with GoingAway status
  15071. ASSERT_TRUE(client.send("trigger"));
  15072. // read() should return false after receiving the close frame
  15073. std::string msg;
  15074. EXPECT_FALSE(client.read(msg));
  15075. EXPECT_FALSE(client.is_open());
  15076. }
  15077. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15078. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15079. "/ws-echo");
  15080. ASSERT_TRUE(client.connect());
  15081. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15082. EXPECT_FALSE(client.is_open());
  15083. }
  15084. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15085. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15086. ws::WebSocketClient client(
  15087. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15088. ASSERT_TRUE(client.connect());
  15089. // Server should have selected graphql-ws
  15090. EXPECT_EQ("graphql-ws", client.subprotocol());
  15091. client.close();
  15092. }
  15093. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15094. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15095. ws::WebSocketClient client(
  15096. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15097. ASSERT_TRUE(client.connect());
  15098. // Server should not have selected any subprotocol
  15099. EXPECT_TRUE(client.subprotocol().empty());
  15100. client.close();
  15101. }
  15102. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15103. // Connect without requesting any subprotocol
  15104. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15105. "/ws-subprotocol");
  15106. ASSERT_TRUE(client.connect());
  15107. EXPECT_TRUE(client.subprotocol().empty());
  15108. client.close();
  15109. }
  15110. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15112. "/ws-echo");
  15113. client.set_tcp_nodelay(true);
  15114. client.set_connection_timeout(3, 0);
  15115. bool socket_options_called = false;
  15116. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15117. ASSERT_TRUE(client.connect());
  15118. ASSERT_TRUE(client.is_open());
  15119. EXPECT_TRUE(socket_options_called);
  15120. ASSERT_TRUE(client.send("hello"));
  15121. std::string msg;
  15122. auto result = client.read(msg);
  15123. EXPECT_EQ(result, ws::ReadResult::Text);
  15124. EXPECT_EQ(msg, "hello");
  15125. client.close();
  15126. }
  15127. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15128. Server svr;
  15129. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15130. if (!req.has_header("Authorization")) {
  15131. res.status = StatusCode::Unauthorized_401;
  15132. res.set_content("Unauthorized", "text/plain");
  15133. return Server::HandlerResponse::Handled;
  15134. }
  15135. return Server::HandlerResponse::Unhandled;
  15136. });
  15137. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15138. std::string msg;
  15139. while (ws.read(msg)) {
  15140. ws.send(msg);
  15141. }
  15142. });
  15143. auto port = svr.bind_to_any_port("localhost");
  15144. std::thread t([&]() { svr.listen_after_bind(); });
  15145. svr.wait_until_ready();
  15146. // Without Authorization header - should be rejected before upgrade
  15147. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15148. EXPECT_FALSE(client1.connect());
  15149. // With Authorization header - should succeed
  15150. Headers headers = {{"Authorization", "Bearer token123"}};
  15151. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15152. headers);
  15153. ASSERT_TRUE(client2.connect());
  15154. ASSERT_TRUE(client2.send("hello"));
  15155. std::string msg;
  15156. ASSERT_TRUE(client2.read(msg));
  15157. EXPECT_EQ("hello", msg);
  15158. client2.close();
  15159. svr.stop();
  15160. t.join();
  15161. }
  15162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15163. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15164. protected:
  15165. void SetUp() override {
  15166. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15167. SERVER_PRIVATE_KEY_FILE);
  15168. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15169. std::string msg;
  15170. ws::ReadResult ret;
  15171. while ((ret = ws.read(msg))) {
  15172. if (ret == ws::Binary) {
  15173. ws.send(msg.data(), msg.size());
  15174. } else {
  15175. ws.send(msg);
  15176. }
  15177. }
  15178. });
  15179. port_ = server_->bind_to_any_port(HOST);
  15180. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15181. server_->wait_until_ready();
  15182. }
  15183. void TearDown() override {
  15184. server_->stop();
  15185. if (server_thread_.joinable()) { server_thread_.join(); }
  15186. }
  15187. std::unique_ptr<SSLServer> server_;
  15188. std::thread server_thread_;
  15189. int port_ = 0;
  15190. };
  15191. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15192. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15193. "/ws-echo");
  15194. client.enable_server_certificate_verification(false);
  15195. ASSERT_TRUE(client.connect());
  15196. ASSERT_TRUE(client.is_open());
  15197. ASSERT_TRUE(client.send("Hello WSS"));
  15198. std::string msg;
  15199. EXPECT_EQ(ws::Text, client.read(msg));
  15200. EXPECT_EQ("Hello WSS", msg);
  15201. client.close();
  15202. }
  15203. #endif
  15204. #if !defined(_WIN32)
  15205. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15206. auto secret_dir = std::string("./symlink_test_secret");
  15207. auto served_dir = std::string("./symlink_test_served");
  15208. auto secret_file = secret_dir + "/secret.txt";
  15209. auto symlink_path = served_dir + "/escape";
  15210. // Setup: create directories and files
  15211. mkdir(secret_dir.c_str(), 0755);
  15212. mkdir(served_dir.c_str(), 0755);
  15213. {
  15214. std::ofstream ofs(secret_file);
  15215. ofs << "SECRET_DATA";
  15216. }
  15217. // Create symlink using absolute path so it resolves correctly
  15218. #ifdef PATH_MAX
  15219. char abs_secret[PATH_MAX];
  15220. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15221. #else
  15222. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15223. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15224. ASSERT_NE(nullptr, abs_secret);
  15225. #endif
  15226. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15227. auto se = detail::scope_exit([&] {
  15228. unlink(symlink_path.c_str());
  15229. unlink(secret_file.c_str());
  15230. rmdir(served_dir.c_str());
  15231. rmdir(secret_dir.c_str());
  15232. });
  15233. Server svr;
  15234. svr.set_mount_point("/", served_dir);
  15235. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15236. auto se2 = detail::scope_exit([&] {
  15237. svr.stop();
  15238. listen_thread.join();
  15239. });
  15240. svr.wait_until_ready();
  15241. Client cli("localhost", PORT);
  15242. // Symlink pointing outside base dir should be blocked
  15243. auto res = cli.Get("/escape/secret.txt");
  15244. ASSERT_TRUE(res);
  15245. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15246. }
  15247. #endif
  15248. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15249. // A GET request with Content-Length to a static file handler must have its
  15250. // body drained before the keep-alive connection is reused. Otherwise the
  15251. // unread body bytes are interpreted as the next HTTP request.
  15252. //
  15253. // The body is sent AFTER receiving the first response (as in the original
  15254. // PoC) so that the stream_line_reader cannot buffer it together with the
  15255. // headers of the first request.
  15256. Server svr;
  15257. svr.set_mount_point("/", "./www");
  15258. std::atomic<int> smuggled_count(0);
  15259. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15260. smuggled_count++;
  15261. res.set_content("oops", "text/plain");
  15262. });
  15263. auto port = svr.bind_to_any_port("localhost");
  15264. thread t = thread([&] { svr.listen_after_bind(); });
  15265. auto se = detail::scope_exit([&] {
  15266. svr.stop();
  15267. t.join();
  15268. });
  15269. svr.wait_until_ready();
  15270. auto error = Error::Success;
  15271. auto sock = detail::create_client_socket(
  15272. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15273. /*connection_timeout_sec=*/2, 0,
  15274. /*read_timeout_sec=*/2, 0,
  15275. /*write_timeout_sec=*/2, 0, std::string(), error);
  15276. ASSERT_NE(INVALID_SOCKET, sock);
  15277. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15278. // The "smuggled" request will be sent as the body of the outer GET
  15279. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15280. "Host: localhost\r\n"
  15281. "Connection: close\r\n"
  15282. "\r\n";
  15283. // Step 1: Send only the outer request headers (no body yet)
  15284. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15285. "Host: localhost\r\n"
  15286. "Content-Length: " +
  15287. std::to_string(smuggled.size()) +
  15288. "\r\n"
  15289. "\r\n";
  15290. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15291. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15292. // Step 2: Read the first response (server serves file without reading body)
  15293. std::string first_response;
  15294. char buf[4096];
  15295. for (;;) {
  15296. auto n = recv(sock, buf, sizeof(buf), 0);
  15297. if (n <= 0) break;
  15298. first_response.append(buf, static_cast<size_t>(n));
  15299. // Stop once we have a complete response (headers + body)
  15300. auto hdr_end = first_response.find("\r\n\r\n");
  15301. if (hdr_end != std::string::npos) {
  15302. // Check for Content-Length to know when the body is complete
  15303. auto cl_pos = first_response.find("Content-Length:");
  15304. if (cl_pos != std::string::npos) {
  15305. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15306. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15307. auto cl = std::stoul(
  15308. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15309. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15310. } else {
  15311. break; // No Content-Length, assume headers-only response
  15312. }
  15313. }
  15314. }
  15315. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15316. // Step 3: Now send the body, which looks like a new HTTP request.
  15317. // On a vulnerable server the keep-alive loop reads this as a second request.
  15318. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15319. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15320. // Step 4: Try to read a second response (should NOT exist after fix)
  15321. std::string second_response;
  15322. for (;;) {
  15323. auto n = recv(sock, buf, sizeof(buf), 0);
  15324. if (n <= 0) break;
  15325. second_response.append(buf, static_cast<size_t>(n));
  15326. }
  15327. // The smuggled request must NOT have been processed
  15328. EXPECT_EQ(0, smuggled_count.load());
  15329. }
  15330. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15331. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15332. // must be rejected with 400 Bad Request.
  15333. Server svr;
  15334. svr.Post("/test", [&](const Request &, Response &res) {
  15335. res.set_content("ok", "text/plain");
  15336. });
  15337. thread t = thread([&] { svr.listen(HOST, PORT); });
  15338. auto se = detail::scope_exit([&] {
  15339. svr.stop();
  15340. t.join();
  15341. ASSERT_FALSE(svr.is_running());
  15342. });
  15343. svr.wait_until_ready();
  15344. // Exact "chunked"
  15345. {
  15346. auto req = "POST /test HTTP/1.1\r\n"
  15347. "Host: localhost\r\n"
  15348. "Content-Length: 5\r\n"
  15349. "Transfer-Encoding: chunked\r\n"
  15350. "Connection: close\r\n"
  15351. "\r\n"
  15352. "hello";
  15353. std::string response;
  15354. ASSERT_TRUE(send_request(1, req, &response));
  15355. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15356. response.substr(0, response.find("\r\n")));
  15357. }
  15358. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15359. {
  15360. auto req = "POST /test HTTP/1.1\r\n"
  15361. "Host: localhost\r\n"
  15362. "Content-Length: 5\r\n"
  15363. "Transfer-Encoding: gzip, chunked\r\n"
  15364. "Connection: close\r\n"
  15365. "\r\n"
  15366. "hello";
  15367. std::string response;
  15368. ASSERT_TRUE(send_request(1, req, &response));
  15369. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15370. response.substr(0, response.find("\r\n")));
  15371. }
  15372. }
  15373. // Regression for issue #2450: a DELETE without Content-Length on a
  15374. // keep-alive connection must not let the post-response drain consume the
  15375. // next request's bytes.
  15376. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15377. Server svr;
  15378. std::atomic<int> delete_count(0);
  15379. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15380. delete_count++;
  15381. res.status = StatusCode::NoContent_204;
  15382. });
  15383. auto port = svr.bind_to_any_port(HOST);
  15384. thread t = thread([&] { svr.listen_after_bind(); });
  15385. auto se = detail::scope_exit([&] {
  15386. svr.stop();
  15387. t.join();
  15388. });
  15389. svr.wait_until_ready();
  15390. auto error = Error::Success;
  15391. auto sock = detail::create_client_socket(
  15392. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15393. /*connection_timeout_sec=*/2, 0,
  15394. /*read_timeout_sec=*/2, 0,
  15395. /*write_timeout_sec=*/2, 0, std::string(), error);
  15396. ASSERT_NE(INVALID_SOCKET, sock);
  15397. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15398. auto send_request_and_read_response = [&](const std::string &req,
  15399. std::string &out) -> bool {
  15400. auto sent = send(sock, req.data(), req.size(), 0);
  15401. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15402. char buf[4096];
  15403. for (;;) {
  15404. auto n = recv(sock, buf, sizeof(buf), 0);
  15405. if (n <= 0) { return !out.empty(); }
  15406. out.append(buf, static_cast<size_t>(n));
  15407. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15408. }
  15409. };
  15410. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15411. "Host: localhost\r\n"
  15412. "\r\n";
  15413. std::string resp1;
  15414. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15415. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15416. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15417. "Host: localhost\r\n"
  15418. "Connection: close\r\n"
  15419. "\r\n";
  15420. std::string resp2;
  15421. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15422. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15423. EXPECT_EQ(2, delete_count.load());
  15424. }
  15425. namespace no_proxy_test {
  15426. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15427. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15428. // calling listen().
  15429. class ScopedServer {
  15430. public:
  15431. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15432. ~ScopedServer() {
  15433. svr_.stop();
  15434. if (th_.joinable()) { th_.join(); }
  15435. }
  15436. Server &svr() { return svr_; }
  15437. int port() const { return port_; }
  15438. void listen() {
  15439. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15440. svr_.wait_until_ready();
  15441. }
  15442. private:
  15443. Server svr_;
  15444. std::thread th_;
  15445. int port_ = 0;
  15446. };
  15447. class ProxyAndTargetServers {
  15448. public:
  15449. ProxyAndTargetServers() {
  15450. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15451. proxy_hits_++;
  15452. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15453. res.set_content("via-proxy", "text/plain");
  15454. });
  15455. target_.Get(".*", [this](const Request &req, Response &res) {
  15456. target_hits_++;
  15457. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15458. res.set_content("direct", "text/plain");
  15459. });
  15460. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15461. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15462. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15463. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15464. proxy_mock_.wait_until_ready();
  15465. target_.wait_until_ready();
  15466. }
  15467. ~ProxyAndTargetServers() {
  15468. proxy_mock_.stop();
  15469. target_.stop();
  15470. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15471. if (target_thread_.joinable()) { target_thread_.join(); }
  15472. }
  15473. Server &proxy_mock() { return proxy_mock_; }
  15474. Server &target() { return target_; }
  15475. int proxy_port() const { return proxy_port_; }
  15476. int target_port() const { return target_port_; }
  15477. int proxy_hits() const { return proxy_hits_.load(); }
  15478. int target_hits() const { return target_hits_.load(); }
  15479. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15480. void reset_counters() {
  15481. proxy_hits_ = 0;
  15482. target_hits_ = 0;
  15483. last_had_proxy_authz_ = false;
  15484. }
  15485. private:
  15486. Server proxy_mock_;
  15487. Server target_;
  15488. std::thread proxy_thread_;
  15489. std::thread target_thread_;
  15490. int proxy_port_ = 0;
  15491. int target_port_ = 0;
  15492. std::atomic<int> proxy_hits_{0};
  15493. std::atomic<int> target_hits_{0};
  15494. std::atomic<bool> last_had_proxy_authz_{false};
  15495. };
  15496. inline std::unique_ptr<Client> make_client(const std::string &host,
  15497. ProxyAndTargetServers &s) {
  15498. auto cli = detail::make_unique<Client>(host, s.target_port());
  15499. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15500. cli->set_proxy("127.0.0.1", s.proxy_port());
  15501. return cli;
  15502. }
  15503. } // namespace no_proxy_test
  15504. using no_proxy_test::make_client;
  15505. using no_proxy_test::ProxyAndTargetServers;
  15506. TEST(NoProxyTest, ExactHostnameBypasses) {
  15507. ProxyAndTargetServers s;
  15508. auto cli = make_client("example.com", s);
  15509. cli->set_no_proxy({"example.com"});
  15510. auto res = cli->Get("/");
  15511. ASSERT_TRUE(res);
  15512. EXPECT_EQ(0, s.proxy_hits());
  15513. EXPECT_EQ(1, s.target_hits());
  15514. }
  15515. TEST(NoProxyTest, SubdomainBypasses) {
  15516. ProxyAndTargetServers s;
  15517. auto cli = make_client("foo.example.com", s);
  15518. cli->set_no_proxy({"example.com"});
  15519. auto res = cli->Get("/");
  15520. ASSERT_TRUE(res);
  15521. EXPECT_EQ(0, s.proxy_hits());
  15522. EXPECT_EQ(1, s.target_hits());
  15523. }
  15524. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15525. // Regression guard: "evilexample.com" must not be considered a subdomain
  15526. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15527. // check would let traffic bypass the proxy and leak credentials direct
  15528. // to the attacker host.
  15529. ProxyAndTargetServers s;
  15530. auto cli = make_client("evilexample.com", s);
  15531. cli->set_no_proxy({"example.com"});
  15532. auto res = cli->Get("/");
  15533. ASSERT_TRUE(res);
  15534. EXPECT_GE(s.proxy_hits(), 1);
  15535. EXPECT_EQ(0, s.target_hits());
  15536. }
  15537. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15538. ProxyAndTargetServers s;
  15539. auto cli = make_client("example.com.evil.com", s);
  15540. cli->set_no_proxy({"example.com"});
  15541. auto res = cli->Get("/");
  15542. ASSERT_TRUE(res);
  15543. EXPECT_GE(s.proxy_hits(), 1);
  15544. EXPECT_EQ(0, s.target_hits());
  15545. }
  15546. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15547. ProxyAndTargetServers s;
  15548. auto cli = make_client("example.com", s);
  15549. cli->set_no_proxy({".example.com"});
  15550. auto res = cli->Get("/");
  15551. ASSERT_TRUE(res);
  15552. EXPECT_EQ(0, s.proxy_hits());
  15553. EXPECT_EQ(1, s.target_hits());
  15554. }
  15555. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15556. ProxyAndTargetServers s;
  15557. auto cli = make_client("Example.COM", s);
  15558. cli->set_no_proxy({"EXAMPLE.com"});
  15559. auto res = cli->Get("/");
  15560. ASSERT_TRUE(res);
  15561. EXPECT_EQ(0, s.proxy_hits());
  15562. EXPECT_EQ(1, s.target_hits());
  15563. }
  15564. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15565. ProxyAndTargetServers s;
  15566. auto cli = make_client("example.com.", s);
  15567. cli->set_no_proxy({"example.com"});
  15568. auto res = cli->Get("/");
  15569. ASSERT_TRUE(res);
  15570. EXPECT_EQ(0, s.proxy_hits());
  15571. EXPECT_EQ(1, s.target_hits());
  15572. }
  15573. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15574. // Trailing dots must be normalized on BOTH sides — host and entry.
  15575. // An implementation that only strips the host-side trailing dot would
  15576. // fail to match host "example.com" against entry "example.com." because
  15577. // a literal substring search would compare 11 chars against 12.
  15578. ProxyAndTargetServers s;
  15579. auto cli = make_client("example.com", s);
  15580. cli->set_no_proxy({"example.com."});
  15581. auto res = cli->Get("/");
  15582. ASSERT_TRUE(res);
  15583. EXPECT_EQ(0, s.proxy_hits());
  15584. EXPECT_EQ(1, s.target_hits());
  15585. }
  15586. TEST(NoProxyTest, WildcardBypassesEverything) {
  15587. ProxyAndTargetServers s;
  15588. auto cli = make_client("anything.invalid.test", s);
  15589. cli->set_no_proxy({"*"});
  15590. auto res = cli->Get("/");
  15591. ASSERT_TRUE(res);
  15592. EXPECT_EQ(0, s.proxy_hits());
  15593. EXPECT_EQ(1, s.target_hits());
  15594. }
  15595. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15596. ProxyAndTargetServers s;
  15597. Client cli("127.0.0.1", s.target_port());
  15598. cli.set_proxy("127.0.0.1", s.proxy_port());
  15599. cli.set_no_proxy({"127.0.0.1"});
  15600. auto res = cli.Get("/");
  15601. ASSERT_TRUE(res);
  15602. EXPECT_EQ(0, s.proxy_hits());
  15603. EXPECT_EQ(1, s.target_hits());
  15604. }
  15605. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  15606. ProxyAndTargetServers s;
  15607. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  15608. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  15609. cli.set_proxy("127.0.0.1", s.proxy_port());
  15610. cli.set_no_proxy({"::1"});
  15611. auto res = cli.Get("/");
  15612. ASSERT_TRUE(res);
  15613. EXPECT_EQ(0, s.proxy_hits());
  15614. EXPECT_EQ(1, s.target_hits());
  15615. }
  15616. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  15617. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  15618. // must still be recognized as IPv6 for CIDR matching. Implementations
  15619. // that detect IPv6 only when the host begins with '[' would parse the
  15620. // host as a hostname and miss the match.
  15621. ProxyAndTargetServers s;
  15622. Client cli("fe80::1", s.target_port());
  15623. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15624. cli.set_proxy("127.0.0.1", s.proxy_port());
  15625. cli.set_no_proxy({"fe80::/10"});
  15626. auto res = cli.Get("/");
  15627. ASSERT_TRUE(res);
  15628. EXPECT_EQ(0, s.proxy_hits());
  15629. EXPECT_EQ(1, s.target_hits());
  15630. }
  15631. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  15632. ProxyAndTargetServers s;
  15633. Client cli("::1", s.target_port());
  15634. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  15635. cli.set_proxy("127.0.0.1", s.proxy_port());
  15636. cli.set_no_proxy({"[::1]"});
  15637. auto res = cli.Get("/");
  15638. ASSERT_TRUE(res);
  15639. EXPECT_EQ(0, s.proxy_hits());
  15640. EXPECT_EQ(1, s.target_hits());
  15641. }
  15642. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  15643. ProxyAndTargetServers s;
  15644. Client cli("fe80::1", s.target_port());
  15645. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15646. cli.set_proxy("127.0.0.1", s.proxy_port());
  15647. cli.set_no_proxy({"[fe80::]/10"});
  15648. auto res = cli.Get("/");
  15649. ASSERT_TRUE(res);
  15650. EXPECT_EQ(0, s.proxy_hits());
  15651. EXPECT_EQ(1, s.target_hits());
  15652. }
  15653. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  15654. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  15655. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  15656. // tricks via address-family conversion.
  15657. ProxyAndTargetServers s;
  15658. Client cli("::ffff:127.0.0.1", s.target_port());
  15659. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  15660. cli.set_proxy("127.0.0.1", s.proxy_port());
  15661. cli.set_no_proxy({"127.0.0.1"});
  15662. auto res = cli.Get("/");
  15663. ASSERT_TRUE(res);
  15664. EXPECT_GE(s.proxy_hits(), 1);
  15665. EXPECT_EQ(0, s.target_hits());
  15666. }
  15667. TEST(NoProxyTest, IPv4CidrMatch) {
  15668. ProxyAndTargetServers s;
  15669. Client cli("127.0.0.1", s.target_port());
  15670. cli.set_proxy("127.0.0.1", s.proxy_port());
  15671. cli.set_no_proxy({"127.0.0.0/8"});
  15672. auto res = cli.Get("/");
  15673. ASSERT_TRUE(res);
  15674. EXPECT_EQ(0, s.proxy_hits());
  15675. EXPECT_EQ(1, s.target_hits());
  15676. }
  15677. TEST(NoProxyTest, IPv4CidrNonMatch) {
  15678. ProxyAndTargetServers s;
  15679. Client cli("127.0.0.1", s.target_port());
  15680. cli.set_proxy("127.0.0.1", s.proxy_port());
  15681. cli.set_no_proxy({"10.0.0.0/8"});
  15682. auto res = cli.Get("/");
  15683. ASSERT_TRUE(res);
  15684. EXPECT_GE(s.proxy_hits(), 1);
  15685. EXPECT_EQ(0, s.target_hits());
  15686. }
  15687. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  15688. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  15689. // IPv4 target matches.
  15690. ProxyAndTargetServers s;
  15691. Client cli("127.0.0.1", s.target_port());
  15692. cli.set_proxy("127.0.0.1", s.proxy_port());
  15693. cli.set_no_proxy({"0.0.0.0/0"});
  15694. auto res = cli.Get("/");
  15695. ASSERT_TRUE(res);
  15696. EXPECT_EQ(0, s.proxy_hits());
  15697. EXPECT_EQ(1, s.target_hits());
  15698. }
  15699. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  15700. ProxyAndTargetServers s;
  15701. Client cli("127.0.0.1", s.target_port());
  15702. cli.set_proxy("127.0.0.1", s.proxy_port());
  15703. cli.set_no_proxy({"127.0.0.1"});
  15704. auto res = cli.Get("/");
  15705. ASSERT_TRUE(res);
  15706. EXPECT_EQ(0, s.proxy_hits());
  15707. EXPECT_EQ(1, s.target_hits());
  15708. }
  15709. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  15710. ProxyAndTargetServers s;
  15711. Client cli("127.0.0.1", s.target_port());
  15712. cli.set_proxy("127.0.0.1", s.proxy_port());
  15713. cli.set_no_proxy({"127.0.0.0/33"});
  15714. auto res = cli.Get("/");
  15715. ASSERT_TRUE(res);
  15716. EXPECT_GE(s.proxy_hits(), 1);
  15717. EXPECT_EQ(0, s.target_hits());
  15718. }
  15719. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  15720. // Empty prefix after the slash must be rejected, not silently treated as /32.
  15721. ProxyAndTargetServers s;
  15722. Client cli("127.0.0.1", s.target_port());
  15723. cli.set_proxy("127.0.0.1", s.proxy_port());
  15724. cli.set_no_proxy({"127.0.0.1/"});
  15725. auto res = cli.Get("/");
  15726. ASSERT_TRUE(res);
  15727. EXPECT_GE(s.proxy_hits(), 1);
  15728. EXPECT_EQ(0, s.target_hits());
  15729. }
  15730. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  15731. ProxyAndTargetServers s;
  15732. auto cli = make_client("internal.corp", s);
  15733. cli->set_proxy_basic_auth("u", "p");
  15734. cli->set_no_proxy({"internal.corp"});
  15735. auto res = cli->Get("/");
  15736. ASSERT_TRUE(res);
  15737. EXPECT_EQ(1, s.target_hits());
  15738. EXPECT_EQ(0, s.proxy_hits());
  15739. EXPECT_FALSE(s.last_had_proxy_authz())
  15740. << "Proxy-Authorization must not be sent direct to the target";
  15741. }
  15742. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  15743. ProxyAndTargetServers s;
  15744. auto cli = make_client("public.example", s);
  15745. cli->set_proxy_basic_auth("u", "p");
  15746. cli->set_no_proxy({"internal.corp"}); // does not match
  15747. auto res = cli->Get("/");
  15748. ASSERT_TRUE(res);
  15749. EXPECT_GE(s.proxy_hits(), 1);
  15750. EXPECT_TRUE(s.last_had_proxy_authz());
  15751. }
  15752. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  15753. ProxyAndTargetServers s;
  15754. auto cli = make_client("anything.test", s);
  15755. auto res = cli->Get("/");
  15756. ASSERT_TRUE(res);
  15757. EXPECT_GE(s.proxy_hits(), 1);
  15758. EXPECT_EQ(0, s.target_hits());
  15759. }
  15760. TEST(NoProxyTest, PortSpecificEntryRejected) {
  15761. ProxyAndTargetServers s;
  15762. auto cli = make_client("example.com", s);
  15763. cli->set_no_proxy({"example.com:8080"});
  15764. auto res = cli->Get("/");
  15765. ASSERT_TRUE(res);
  15766. EXPECT_GE(s.proxy_hits(), 1);
  15767. EXPECT_EQ(0, s.target_hits());
  15768. }
  15769. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  15770. ProxyAndTargetServers s;
  15771. auto cli = make_client("anything.test", s);
  15772. cli->set_no_proxy({"", " ", "\t"});
  15773. auto res = cli->Get("/");
  15774. ASSERT_TRUE(res);
  15775. EXPECT_GE(s.proxy_hits(), 1);
  15776. EXPECT_EQ(0, s.target_hits());
  15777. }
  15778. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  15779. // An entry with leading/trailing whitespace must still match — env-style
  15780. // values are commonly pasted with stray spaces and an implementation
  15781. // that feeds the raw token directly to inet_pton would fail to match
  15782. // valid CIDRs because of the spaces.
  15783. ProxyAndTargetServers s;
  15784. Client cli("127.0.0.1", s.target_port());
  15785. cli.set_proxy("127.0.0.1", s.proxy_port());
  15786. cli.set_no_proxy({" 127.0.0.0/8 "});
  15787. auto res = cli.Get("/");
  15788. ASSERT_TRUE(res);
  15789. EXPECT_EQ(0, s.proxy_hits());
  15790. EXPECT_EQ(1, s.target_hits());
  15791. }
  15792. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  15793. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  15794. // go direct and must NOT carry Proxy-Authorization.
  15795. std::atomic<int> proxy_hits{0};
  15796. std::atomic<int> target_hits{0};
  15797. std::atomic<bool> target_saw_authz{false};
  15798. no_proxy_test::ScopedServer proxy_mock, target;
  15799. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15800. proxy_hits++;
  15801. res.status = 302;
  15802. res.set_header("Location", "http://127.0.0.1:" +
  15803. std::to_string(target.port()) + "/landed");
  15804. });
  15805. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15806. target_hits++;
  15807. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  15808. res.set_content("direct", "text/plain");
  15809. });
  15810. proxy_mock.listen();
  15811. target.listen();
  15812. Client cli("public.example", target.port());
  15813. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15814. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15815. cli.set_proxy_basic_auth("u", "p");
  15816. cli.set_no_proxy({"127.0.0.1"});
  15817. cli.set_follow_location(true);
  15818. auto res = cli.Get("/redir");
  15819. ASSERT_TRUE(res);
  15820. EXPECT_GE(proxy_hits.load(), 1);
  15821. EXPECT_GE(target_hits.load(), 1);
  15822. EXPECT_FALSE(target_saw_authz.load());
  15823. }
  15824. #ifdef CPPHTTPLIB_SSL_ENABLED
  15825. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  15826. // Direct origin replying 407 must not trigger the digest retry; otherwise
  15827. // proxy creds would be sent to the (possibly hostile) origin.
  15828. std::atomic<int> target_hits{0};
  15829. std::atomic<bool> target_saw_proxy_authz{false};
  15830. no_proxy_test::ScopedServer target;
  15831. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15832. target_hits++;
  15833. if (req.has_header("Proxy-Authorization")) {
  15834. target_saw_proxy_authz = true;
  15835. }
  15836. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15837. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  15838. "nonce=\"abc\", algorithm=MD5");
  15839. });
  15840. target.listen();
  15841. // The proxy address is set to the target's port: the bypass MUST kick in;
  15842. // if it doesn't, the test still routes "via proxy" to the same server and
  15843. // the Proxy-Authorization assertion below catches the leak.
  15844. Client cli("evil.example", target.port());
  15845. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  15846. cli.set_proxy("127.0.0.1", target.port());
  15847. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15848. cli.set_no_proxy({"evil.example"});
  15849. auto res = cli.Get("/x");
  15850. ASSERT_TRUE(res);
  15851. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15852. EXPECT_EQ(1, target_hits.load());
  15853. EXPECT_FALSE(target_saw_proxy_authz.load());
  15854. }
  15855. #endif
  15856. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  15857. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  15858. std::atomic<int> proxy_hits{0};
  15859. std::atomic<int> bypass_hits{0};
  15860. std::atomic<bool> proxy_saw_c_url{false};
  15861. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  15862. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  15863. proxy_hits++;
  15864. if (req.path.find("/start") != std::string::npos) {
  15865. res.status = 302;
  15866. res.set_header("Location", "http://127.0.0.1:" +
  15867. std::to_string(bypass_server.port()) +
  15868. "/middle");
  15869. return;
  15870. }
  15871. if (req.path.find("/end") != std::string::npos) {
  15872. proxy_saw_c_url = true;
  15873. res.set_content("c-via-proxy", "text/plain");
  15874. return;
  15875. }
  15876. res.set_content("unexpected", "text/plain");
  15877. });
  15878. // public.example's "advertised" port is arbitrary (the request never lands
  15879. // there — it goes through the proxy), but use a dynamic value to stay
  15880. // friendly with sharded parallel runs.
  15881. int public_port = bypass_server.port();
  15882. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  15883. bypass_hits++;
  15884. res.status = 302;
  15885. res.set_header("Location", "http://public.example:" +
  15886. std::to_string(public_port) + "/end");
  15887. });
  15888. proxy_mock.listen();
  15889. bypass_server.listen();
  15890. Client cli("public.example", public_port);
  15891. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15892. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15893. cli.set_no_proxy({"127.0.0.1"});
  15894. cli.set_follow_location(true);
  15895. auto res = cli.Get("/start");
  15896. ASSERT_TRUE(res);
  15897. EXPECT_EQ(StatusCode::OK_200, res->status);
  15898. EXPECT_EQ("c-via-proxy", res->body);
  15899. EXPECT_GE(proxy_hits.load(), 2);
  15900. EXPECT_GE(bypass_hits.load(), 1);
  15901. EXPECT_TRUE(proxy_saw_c_url.load());
  15902. }
  15903. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  15904. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  15905. // request reconnects to the correct endpoint.
  15906. std::atomic<int> proxy_hits{0};
  15907. std::atomic<int> target_hits{0};
  15908. no_proxy_test::ScopedServer proxy_mock, target;
  15909. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15910. proxy_hits++;
  15911. res.set_content("via-proxy", "text/plain");
  15912. });
  15913. target.svr().Get(".*", [&](const Request &, Response &res) {
  15914. target_hits++;
  15915. res.set_content("direct", "text/plain");
  15916. });
  15917. proxy_mock.listen();
  15918. target.listen();
  15919. Client cli("public.example", target.port());
  15920. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15921. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15922. cli.set_keep_alive(true);
  15923. auto res1 = cli.Get("/a");
  15924. ASSERT_TRUE(res1);
  15925. EXPECT_EQ("via-proxy", res1->body);
  15926. EXPECT_EQ(1, proxy_hits.load());
  15927. EXPECT_EQ(0, target_hits.load());
  15928. cli.set_no_proxy({"public.example"});
  15929. auto res2 = cli.Get("/b");
  15930. ASSERT_TRUE(res2);
  15931. EXPECT_EQ("direct", res2->body);
  15932. EXPECT_EQ(1, proxy_hits.load());
  15933. EXPECT_EQ(1, target_hits.load());
  15934. }
  15935. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  15936. namespace proxy_tunnel_test {
  15937. // SSLServer counterpart to no_proxy_test::ScopedServer.
  15938. class ScopedSSLServer {
  15939. public:
  15940. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  15941. port_ = svr_.bind_to_any_port("127.0.0.1");
  15942. }
  15943. ~ScopedSSLServer() {
  15944. svr_.stop();
  15945. if (th_.joinable()) { th_.join(); }
  15946. }
  15947. SSLServer &svr() { return svr_; }
  15948. int port() const { return port_; }
  15949. void listen() {
  15950. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15951. svr_.wait_until_ready();
  15952. }
  15953. private:
  15954. SSLServer svr_;
  15955. std::thread th_;
  15956. int port_ = 0;
  15957. };
  15958. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  15959. class ScopedConnectProxy {
  15960. public:
  15961. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  15962. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  15963. if (listen_fd_ < 0) { return; }
  15964. int yes = 1;
  15965. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  15966. sockaddr_in a{};
  15967. a.sin_family = AF_INET;
  15968. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  15969. a.sin_port = 0;
  15970. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  15971. return;
  15972. }
  15973. socklen_t alen = sizeof(a);
  15974. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  15975. 0) {
  15976. return;
  15977. }
  15978. port_ = ntohs(a.sin_port);
  15979. if (::listen(listen_fd_, 1) != 0) { return; }
  15980. th_ = std::thread([this] { run(); });
  15981. }
  15982. ~ScopedConnectProxy() {
  15983. stop_ = true;
  15984. if (listen_fd_ >= 0) {
  15985. ::shutdown(listen_fd_, SHUT_RDWR);
  15986. ::close(listen_fd_);
  15987. }
  15988. if (th_.joinable()) { th_.join(); }
  15989. }
  15990. int port() const { return port_; }
  15991. int connect_hits() const { return connect_hits_.load(); }
  15992. private:
  15993. void run() {
  15994. while (!stop_.load()) {
  15995. fd_set rfds;
  15996. FD_ZERO(&rfds);
  15997. FD_SET(listen_fd_, &rfds);
  15998. timeval tv{0, 100 * 1000};
  15999. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16000. if (sel <= 0) { continue; }
  16001. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16002. if (client_fd < 0) { continue; }
  16003. std::string req;
  16004. char buf[2048];
  16005. while (req.find("\r\n\r\n") == std::string::npos) {
  16006. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16007. if (n <= 0) { break; }
  16008. req.append(buf, static_cast<size_t>(n));
  16009. }
  16010. if (req.compare(0, 7, "CONNECT") != 0) {
  16011. ::close(client_fd);
  16012. continue;
  16013. }
  16014. connect_hits_++;
  16015. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16016. ::send(client_fd, ok, std::strlen(ok), 0);
  16017. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16018. sockaddr_in o{};
  16019. o.sin_family = AF_INET;
  16020. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16021. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16022. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16023. 0) {
  16024. ::close(client_fd);
  16025. ::close(origin_fd);
  16026. continue;
  16027. }
  16028. auto forward = [](int from, int to) {
  16029. char b[8192];
  16030. for (;;) {
  16031. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16032. if (n <= 0) { break; }
  16033. ssize_t off = 0;
  16034. while (off < n) {
  16035. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16036. if (s <= 0) {
  16037. off = n;
  16038. break;
  16039. }
  16040. off += s;
  16041. }
  16042. }
  16043. ::shutdown(to, SHUT_WR);
  16044. };
  16045. std::thread t1([&] { forward(client_fd, origin_fd); });
  16046. std::thread t2([&] { forward(origin_fd, client_fd); });
  16047. t1.join();
  16048. t2.join();
  16049. ::close(client_fd);
  16050. ::close(origin_fd);
  16051. }
  16052. }
  16053. int forward_port_ = -1;
  16054. int listen_fd_ = -1;
  16055. int port_ = 0;
  16056. std::thread th_;
  16057. std::atomic<bool> stop_{false};
  16058. std::atomic<int> connect_hits_{0};
  16059. };
  16060. } // namespace proxy_tunnel_test
  16061. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16062. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16063. // retry; otherwise proxy creds would be sent to the origin.
  16064. std::atomic<int> origin_hits{0};
  16065. std::atomic<bool> origin_saw_proxy_authz{false};
  16066. proxy_tunnel_test::ScopedSSLServer origin;
  16067. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16068. origin_hits++;
  16069. if (req.has_header("Proxy-Authorization")) {
  16070. origin_saw_proxy_authz = true;
  16071. }
  16072. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16073. res.set_header("Proxy-Authenticate",
  16074. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16075. "algorithm=MD5");
  16076. });
  16077. origin.listen();
  16078. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16079. ASSERT_NE(0, proxy.port());
  16080. SSLClient cli(HOST, origin.port());
  16081. cli.enable_server_certificate_verification(false);
  16082. cli.set_proxy(HOST, proxy.port());
  16083. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16084. auto res = cli.Get("/x");
  16085. ASSERT_TRUE(res);
  16086. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16087. EXPECT_EQ(1, origin_hits.load());
  16088. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16089. EXPECT_EQ(1, proxy.connect_hits());
  16090. }
  16091. #endif