diff --git a/Bridge/HttpBridgeActivity.cs b/Bridge/HttpBridgeActivity.cs index 91ffd2b..c8ede7b 100644 --- a/Bridge/HttpBridgeActivity.cs +++ b/Bridge/HttpBridgeActivity.cs @@ -86,7 +86,8 @@ namespace UMC.Host { if (HttpBridgeClient.IsRunning) { - if(request.IsApp){ + if (request.IsApp) + { this.Prompt("App不支持关停Web VPN"); } @@ -203,6 +204,7 @@ namespace UMC.Host { provider.Attributes["scheme"] = scheme; provider.Attributes["domain"] = domain; + UMC.Proxy.WebServlet.MainDomain = domain; isTag = true; } if (String.Equals(provider.Attributes["bridge"], bridgeUrl) == false) @@ -235,12 +237,12 @@ namespace UMC.Host var desc = new UMC.Web.WebMeta().Put("title", isbridge ? "Web VPN已经开启" : (data["tip"] ?? "无可用的流量,请充值")).Put("icon", isbridge ? "\uEA06" : "\uEA05"); - + UISection ui = UISection.Create(new UIHeader().Desc(desc, "{icon}\n{title}", style), new UITitle("Web VPN")); var caption = data["caption"]; - ui.AddCell("所属账户", String.IsNullOrEmpty(caption) ? "[点击完善]" : caption, new UIClick("System", "License","Name")); + ui.AddCell("所属账户", String.IsNullOrEmpty(caption) ? "[点击完善]" : caption, new UIClick("System", "License", "Name")); var bridgeSrc = data["bridgeSrc"]; @@ -255,12 +257,12 @@ namespace UMC.Host } - ui.NewSection("Web VPN").AddCell("剩余流量", data["allowSize"]) - .AddCell("上行流量", data["inputSize"]) - .AddCell("下行流量", data["outputSize"]) - .AddCell("流量过期", data["expireTime"]).Footer.Put("text", "注意:流量过期后,剩余流量将会清零"); - - + ui.NewSection("Web VPN").AddCell("剩余流量", data["allowSize"]) + .AddCell("上行流量", data["inputSize"]) + .AddCell("下行流量", data["outputSize"]) + .AddCell("流量过期", data["expireTime"]).Footer.Put("text", "注意:流量过期后,剩余流量将会清零"); + + ui.UIFootBar = new UIFootBar() { IsFixed = true }; ui.UIFootBar.AddText( new UIEventText(HttpBridgeClient.IsRunning ? "关停" : "开启").Click(new UIClick(HttpBridgeClient.IsRunning ? "Stop" : "Start").Post(request.Model, request.Command)), new UIEventText("去充值").Style(new UIStyle().BgColor()).Click(new UIClick("Recharge").Post(request))); diff --git a/Mime/HttpMimeServier.cs b/Mime/HttpMimeServier.cs index 929e895..b40c1e6 100644 --- a/Mime/HttpMimeServier.cs +++ b/Mime/HttpMimeServier.cs @@ -60,6 +60,7 @@ namespace UMC.Host string Config(ProviderConfiguration hosts) { UMC.Proxy.WebServlet.IsHttps = UMC.Data.WebResource.Instance().Provider["scheme"] == "https"; + UMC.Proxy.WebServlet.MainDomain = UMC.Data.WebResource.Instance().Provider["domain"] ?? "localhost"; _urls.Clear(); var host = new Dictionary(); diff --git a/Program.cs b/Program.cs index 28ac809..e44b367 100644 --- a/Program.cs +++ b/Program.cs @@ -19,15 +19,7 @@ namespace UMC.Host { public static void Main(string[] args) { - // var files = System.IO.Directory.GetFiles("/Users/wushunming/Documents/APIUMC/UMC.Host", "*.cs", SearchOption.AllDirectories); - - // var textFile = new StreamWriter(Utility.Writer(Utility.MapPath("all.txt"), true)); - // foreach (var d in files) - // { - // textFile.WriteLine(); - // textFile.Write(Utility.Reader(d)); - // } - // textFile.Close(); + AppDomain.CurrentDomain.UnhandledException += UnhandledException; var variable = System.Environment.GetEnvironmentVariable("UMC"); @@ -485,7 +477,7 @@ namespace UMC.Host Register(); // File.WriteAllText(UMC.Data.Utility.MapPath($".lock"), $"{{\"Id\":\"{System.Diagnostics.Process.GetCurrentProcess().Id}\"}}"); - // UMC.Data.HotCache.Namespace(typeof(UMC.Proxy.Entities.Cookie).Namespace); + UMC.Data.HotCache.Namespace(typeof(UMC.Proxy.Entities.Cookie).Namespace); UMC.Proxy.DataFactory.Instance(); UMC.Data.DataFactory.Instance(); diff --git a/Proxy/Entities/Codes/Site.cs b/Proxy/Entities/Codes/Site.cs index d758d0c..bce3c65 100644 --- a/Proxy/Entities/Codes/Site.cs +++ b/Proxy/Entities/Codes/Site.cs @@ -5,8 +5,8 @@ namespace UMC.Proxy.Entities { public partial class Site { - readonly static Action[] _SetValues = new Action[] { (r, t) => r.Account = Reflection.ParseObject(t, r.Account), (r, t) => r.AdminConf = Reflection.ParseObject(t, r.AdminConf), (r, t) => r.AppendJSConf = Reflection.ParseObject(t, r.AppendJSConf), (r, t) => r.AppSecret = Reflection.ParseObject(t, r.AppSecret), (r, t) => r.AppSecretAuth = Reflection.ParseObject(t, r.AppSecretAuth), (r, t) => r.AuthConf = Reflection.ParseObject(t, r.AuthConf), (r, t) => r.AuthExpire = Reflection.ParseObject(t, r.AuthExpire), (r, t) => r.AuthType = Reflection.ParseObject(t, r.AuthType), (r, t) => r.Caption = Reflection.ParseObject(t, r.Caption), (r, t) => r.Conf = Reflection.ParseObject(t, r.Conf), (r, t) => r.Domain = Reflection.ParseObject(t, r.Domain), (r, t) => r.Flag = Reflection.ParseObject(t, r.Flag), (r, t) => r.HeaderConf = Reflection.ParseObject(t, r.HeaderConf), (r, t) => r.HelpKey = Reflection.ParseObject(t, r.HelpKey), (r, t) => r.Home = Reflection.ParseObject(t, r.Home), (r, t) => r.Host = Reflection.ParseObject(t, r.Host), (r, t) => r.HostModel = Reflection.ParseObject(t, r.HostModel), (r, t) => r.HostReConf = Reflection.ParseObject(t, r.HostReConf), (r, t) => r.ImagesConf = Reflection.ParseObject(t, r.ImagesConf), (r, t) => r.IsAuth = Reflection.ParseObject(t, r.IsAuth), (r, t) => r.IsDebug = Reflection.ParseObject(t, r.IsDebug), (r, t) => r.IsDesktop = Reflection.ParseObject(t, r.IsDesktop), (r, t) => r.IsMarket = Reflection.ParseObject(t, r.IsMarket), (r, t) => r.IsModule = Reflection.ParseObject(t, r.IsModule), (r, t) => r.LogConf = Reflection.ParseObject(t, r.LogConf), (r, t) => r.LogoutPath = Reflection.ParseObject(t, r.LogoutPath), (r, t) => r.MobileHome = Reflection.ParseObject(t, r.MobileHome), (r, t) => r.ModifyTime = Reflection.ParseObject(t, r.ModifyTime), (r, t) => r.OpenModel = Reflection.ParseObject(t, r.OpenModel), (r, t) => r.OutputCookies = Reflection.ParseObject(t, r.OutputCookies), (r, t) => r.RedirectPath = Reflection.ParseObject(t, r.RedirectPath), (r, t) => r.Root = Reflection.ParseObject(t, r.Root), (r, t) => r.SiteKey = Reflection.ParseObject(t, r.SiteKey), (r, t) => r.SLB = Reflection.ParseObject(t, r.SLB), (r, t) => r.StaticConf = Reflection.ParseObject(t, r.StaticConf), (r, t) => r.Time = Reflection.ParseObject(t, r.Time), (r, t) => r.Timeout = Reflection.ParseObject(t, r.Timeout), (r, t) => r.Type = Reflection.ParseObject(t, r.Type), (r, t) => r.UserBrowser = Reflection.ParseObject(t, r.UserBrowser), (r, t) => r.UserModel = Reflection.ParseObject(t, r.UserModel), (r, t) => r.Version = Reflection.ParseObject(t, r.Version) }; - readonly static string[] _Columns = new string[] { "Account", "AdminConf", "AppendJSConf", "AppSecret", "AppSecretAuth", "AuthConf", "AuthExpire", "AuthType", "Caption", "Conf", "Domain", "Flag", "HeaderConf", "HelpKey", "Home", "Host", "HostModel", "HostReConf", "ImagesConf", "IsAuth", "IsDebug", "IsDesktop", "IsMarket", "IsModule", "LogConf", "LogoutPath", "MobileHome", "ModifyTime", "OpenModel", "OutputCookies", "RedirectPath", "Root", "SiteKey", "SLB", "StaticConf", "Time", "Timeout", "Type", "UserBrowser", "UserModel", "Version" }; + readonly static Action[] _SetValues = new Action[] { (r, t) => r.Account = Reflection.ParseObject(t, r.Account), (r, t) => r.AdminConf = Reflection.ParseObject(t, r.AdminConf), (r, t) => r.AppendJSConf = Reflection.ParseObject(t, r.AppendJSConf), (r, t) => r.AppSecret = Reflection.ParseObject(t, r.AppSecret), (r, t) => r.AppSecretAuth = Reflection.ParseObject(t, r.AppSecretAuth), (r, t) => r.AuthConf = Reflection.ParseObject(t, r.AuthConf), (r, t) => r.AuthExpire = Reflection.ParseObject(t, r.AuthExpire), (r, t) => r.AuthType = Reflection.ParseObject(t, r.AuthType), (r, t) => r.Caption = Reflection.ParseObject(t, r.Caption), (r, t) => r.Domain = Reflection.ParseObject(t, r.Domain), (r, t) => r.Flag = Reflection.ParseObject(t, r.Flag), (r, t) => r.HeaderConf = Reflection.ParseObject(t, r.HeaderConf), (r, t) => r.HelpKey = Reflection.ParseObject(t, r.HelpKey), (r, t) => r.Home = Reflection.ParseObject(t, r.Home), (r, t) => r.Host = Reflection.ParseObject(t, r.Host), (r, t) => r.HostModel = Reflection.ParseObject(t, r.HostModel), (r, t) => r.HostReConf = Reflection.ParseObject(t, r.HostReConf), (r, t) => r.ImagesConf = Reflection.ParseObject(t, r.ImagesConf), (r, t) => r.IsAuth = Reflection.ParseObject(t, r.IsAuth), (r, t) => r.IsDebug = Reflection.ParseObject(t, r.IsDebug), (r, t) => r.IsDesktop = Reflection.ParseObject(t, r.IsDesktop), (r, t) => r.IsMarket = Reflection.ParseObject(t, r.IsMarket), (r, t) => r.IsModule = Reflection.ParseObject(t, r.IsModule), (r, t) => r.LogConf = Reflection.ParseObject(t, r.LogConf), (r, t) => r.LogoutPath = Reflection.ParseObject(t, r.LogoutPath), (r, t) => r.MobileHome = Reflection.ParseObject(t, r.MobileHome), (r, t) => r.ModifyTime = Reflection.ParseObject(t, r.ModifyTime), (r, t) => r.OpenModel = Reflection.ParseObject(t, r.OpenModel), (r, t) => r.OutputCookies = Reflection.ParseObject(t, r.OutputCookies), (r, t) => r.RedirectPath = Reflection.ParseObject(t, r.RedirectPath), (r, t) => r.Root = Reflection.ParseObject(t, r.Root), (r, t) => r.SiteKey = Reflection.ParseObject(t, r.SiteKey), (r, t) => r.SLB = Reflection.ParseObject(t, r.SLB), (r, t) => r.StaticConf = Reflection.ParseObject(t, r.StaticConf), (r, t) => r.SubSite = Reflection.ParseObject(t, r.SubSite), (r, t) => r.Time = Reflection.ParseObject(t, r.Time), (r, t) => r.Timeout = Reflection.ParseObject(t, r.Timeout), (r, t) => r.Type = Reflection.ParseObject(t, r.Type), (r, t) => r.UserBrowser = Reflection.ParseObject(t, r.UserBrowser), (r, t) => r.UserModel = Reflection.ParseObject(t, r.UserModel), (r, t) => r.Version = Reflection.ParseObject(t, r.Version) }; + readonly static string[] _Columns = new string[] { "Account", "AdminConf", "AppendJSConf", "AppSecret", "AppSecretAuth", "AuthConf", "AuthExpire", "AuthType", "Caption", "Domain", "Flag", "HeaderConf", "HelpKey", "Home", "Host", "HostModel", "HostReConf", "ImagesConf", "IsAuth", "IsDebug", "IsDesktop", "IsMarket", "IsModule", "LogConf", "LogoutPath", "MobileHome", "ModifyTime", "OpenModel", "OutputCookies", "RedirectPath", "Root", "SiteKey", "SLB", "StaticConf", "SubSite", "Time", "Timeout", "Type", "UserBrowser", "UserModel", "Version" }; protected override void SetValue(string name, object obv) { var index = Utility.Search(_Columns, name, StringComparer.CurrentCultureIgnoreCase); @@ -23,7 +23,6 @@ namespace UMC.Proxy.Entities AppendValue(action, "AuthExpire", this.AuthExpire); AppendValue(action, "AuthType", this.AuthType); AppendValue(action, "Caption", this.Caption); - AppendValue(action, "Conf", this.Conf); AppendValue(action, "Domain", this.Domain); AppendValue(action, "Flag", this.Flag); AppendValue(action, "HeaderConf", this.HeaderConf); @@ -49,6 +48,7 @@ namespace UMC.Proxy.Entities AppendValue(action, "SiteKey", this.SiteKey); AppendValue(action, "SLB", this.SLB); AppendValue(action, "StaticConf", this.StaticConf); + AppendValue(action, "SubSite", this.SubSite); AppendValue(action, "Time", this.Time); AppendValue(action, "Timeout", this.Timeout); AppendValue(action, "Type", this.Type); @@ -69,32 +69,32 @@ namespace UMC.Proxy.Entities cols[6] = RecordColumn.Column("AuthExpire", this.AuthExpire); cols[7] = RecordColumn.Column("AuthType", this.AuthType); cols[8] = RecordColumn.Column("Caption", this.Caption); - cols[9] = RecordColumn.Column("Conf", this.Conf); - cols[10] = RecordColumn.Column("Domain", this.Domain); - cols[11] = RecordColumn.Column("Flag", this.Flag); - cols[12] = RecordColumn.Column("HeaderConf", this.HeaderConf); - cols[13] = RecordColumn.Column("HelpKey", this.HelpKey); - cols[14] = RecordColumn.Column("Home", this.Home); - cols[15] = RecordColumn.Column("Host", this.Host); - cols[16] = RecordColumn.Column("HostModel", this.HostModel); - cols[17] = RecordColumn.Column("HostReConf", this.HostReConf); - cols[18] = RecordColumn.Column("ImagesConf", this.ImagesConf); - cols[19] = RecordColumn.Column("IsAuth", this.IsAuth); - cols[20] = RecordColumn.Column("IsDebug", this.IsDebug); - cols[21] = RecordColumn.Column("IsDesktop", this.IsDesktop); - cols[22] = RecordColumn.Column("IsMarket", this.IsMarket); - cols[23] = RecordColumn.Column("IsModule", this.IsModule); - cols[24] = RecordColumn.Column("LogConf", this.LogConf); - cols[25] = RecordColumn.Column("LogoutPath", this.LogoutPath); - cols[26] = RecordColumn.Column("MobileHome", this.MobileHome); - cols[27] = RecordColumn.Column("ModifyTime", this.ModifyTime); - cols[28] = RecordColumn.Column("OpenModel", this.OpenModel); - cols[29] = RecordColumn.Column("OutputCookies", this.OutputCookies); - cols[30] = RecordColumn.Column("RedirectPath", this.RedirectPath); - cols[31] = RecordColumn.Column("Root", this.Root); - cols[32] = RecordColumn.Column("SiteKey", this.SiteKey); - cols[33] = RecordColumn.Column("SLB", this.SLB); - cols[34] = RecordColumn.Column("StaticConf", this.StaticConf); + cols[9] = RecordColumn.Column("Domain", this.Domain); + cols[10] = RecordColumn.Column("Flag", this.Flag); + cols[11] = RecordColumn.Column("HeaderConf", this.HeaderConf); + cols[12] = RecordColumn.Column("HelpKey", this.HelpKey); + cols[13] = RecordColumn.Column("Home", this.Home); + cols[14] = RecordColumn.Column("Host", this.Host); + cols[15] = RecordColumn.Column("HostModel", this.HostModel); + cols[16] = RecordColumn.Column("HostReConf", this.HostReConf); + cols[17] = RecordColumn.Column("ImagesConf", this.ImagesConf); + cols[18] = RecordColumn.Column("IsAuth", this.IsAuth); + cols[19] = RecordColumn.Column("IsDebug", this.IsDebug); + cols[20] = RecordColumn.Column("IsDesktop", this.IsDesktop); + cols[21] = RecordColumn.Column("IsMarket", this.IsMarket); + cols[22] = RecordColumn.Column("IsModule", this.IsModule); + cols[23] = RecordColumn.Column("LogConf", this.LogConf); + cols[24] = RecordColumn.Column("LogoutPath", this.LogoutPath); + cols[25] = RecordColumn.Column("MobileHome", this.MobileHome); + cols[26] = RecordColumn.Column("ModifyTime", this.ModifyTime); + cols[27] = RecordColumn.Column("OpenModel", this.OpenModel); + cols[28] = RecordColumn.Column("OutputCookies", this.OutputCookies); + cols[29] = RecordColumn.Column("RedirectPath", this.RedirectPath); + cols[30] = RecordColumn.Column("Root", this.Root); + cols[31] = RecordColumn.Column("SiteKey", this.SiteKey); + cols[32] = RecordColumn.Column("SLB", this.SLB); + cols[33] = RecordColumn.Column("StaticConf", this.StaticConf); + cols[34] = RecordColumn.Column("SubSite", this.SubSite); cols[35] = RecordColumn.Column("Time", this.Time); cols[36] = RecordColumn.Column("Timeout", this.Timeout); cols[37] = RecordColumn.Column("Type", this.Type); diff --git a/Proxy/Entities/Site.cs b/Proxy/Entities/Site.cs index 64ee9c5..7361eca 100644 --- a/Proxy/Entities/Site.cs +++ b/Proxy/Entities/Site.cs @@ -87,7 +87,7 @@ namespace UMC.Proxy.Entities /// /// 应用子目录 /// - public String Conf { get; set; } + public String SubSite { get; set; } public String AuthConf { get; set; } public String StaticConf { get; set; } diff --git a/Proxy/HttpProxy.cs b/Proxy/HttpProxy.cs index 20abe10..c116498 100644 --- a/Proxy/HttpProxy.cs +++ b/Proxy/HttpProxy.cs @@ -1,6 +1,4 @@ -using System.Globalization; - -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -12,16 +10,130 @@ using System.Text.RegularExpressions; using System.Text; using System.Security.Cryptography; using System.Collections.Specialized; -using UMC.Data; -using System.Reflection; using System.IO.Compression; -using System.Diagnostics.CodeAnalysis; namespace UMC.Proxy { public class HttpProxy { + public HttpProxy(SiteConfig site, UMC.Net.NetContext context, int staticModel, string rawUrl, string pfxDomain) + { + this.Site = site; + this.IsLog = site.Site.IsDebug == true; + + this.Loger = new StringWriter(); + + this.Context = context; + this.User = context.Token.Identity(); + + this.RawUrl = rawUrl; + this.StaticModel = staticModel; + + + if (this.StaticModel == 0 || User.IsAuthenticated == false) + { + this.SiteCookie = new Entities.Cookie { Domain = Site.Root, user_id = context.Token.UserId.Value, IndexValue = 0 }; + + InitClientCookie(); + } + else if (User.IsAuthenticated) + { + var deviceIndex = UMC.Data.Utility.IntParse(context.Cookies[DeviceIndex], 0); + if (deviceIndex == 0) + { + this.SiteCookie = DataFactory.Instance().Cookie(this.Site.Root, User.Id.Value, deviceIndex) ?? new Entities.Cookie { Domain = Site.Root, user_id = context.Token.UserId.Value, IndexValue = 0 }; + if ((this.SiteCookie.LoginTime ?? 0) < context.Token.LoginTime) + { + + ClearCookie(); + + DataFactory.Instance().Put(new Entities.Cookie + { + Domain = Site.Root, + user_id = User.Id.Value, + IndexValue = 0, + LoginTime = Utility.TimeSpan() + }); + } + else + { + InitClientCookie(); + } + } + else + { + this.SiteCookie = DataFactory.Instance().Cookie(this.Site.Root, User.Id.Value, deviceIndex) ?? DataFactory.Instance().Cookie(this.Site.Root, User.Id.Value, 0) ?? new Entities.Cookie { Domain = Site.Root, user_id = context.Token.UserId.Value, IndexValue = 0 }; + + InitClientCookie(); + } + + + } + + this.Authority = this.Context.Url.Authority; + + + if (site.Domains.Length > 0) + { + this.Domain = WeightUri(pfxDomain); + } + + if (site.Test.Length > 0 && User.IsAuthenticated) + { + var authManager = UMC.Security.AuthManager.Instance(); + for (var i = 0; i < site.Test.Length; i++) + { + var tUrl = site.Test[i]; + if (tUrl.Users.Contains(User.Name)) + { + this.Domain = new UMCUri(tUrl.Url); + this.IsTest = true; + break; + } + else if (tUrl.Auths.Length > 0) + { + if (authManager.Check(this.User, 0, tUrl.Auths).Contains(1)) + { + this.IsTest = true; + this.Domain = new UMCUri(tUrl.Url); + break; + + } + } + } + } + + + this.RawUrl = ReplaceRawUrl(this.RawUrl); + + this.StartTime = UMC.Data.Reflection.TimeSpanMilli(DateTime.Now); + } + private HttpProxy(HttpProxy proxy, SiteConfig siteConfig) + { + var user = siteConfig.Site.Account; + + this.Site = siteConfig; + this.Loger = proxy.Loger; + this.IsLog = proxy.IsLog; + this.Password = UMC.Data.DataFactory.Instance().Password(SiteConfig.MD5Key(siteConfig.Root, user)); + + this.SiteCookie = new Entities.Cookie + { + Account = user, + user_id = UMC.Data.Utility.Guid(user, true), + Domain = this.Site.Root, + IndexValue = 0 + }; + this.IsChangeUser = false; + this.Context = proxy.Context; + this.Domain = new UMCUri(siteConfig.Domains[0]); + this.RawUrl = proxy.RawUrl; + this.Host = proxy.Host; + this.User = proxy.User; + + this.Authority = proxy.Authority; + } public UMCUri Domain { get; @@ -60,44 +172,11 @@ namespace UMC.Proxy get; private set; } - private HttpProxy(HttpProxy proxy, SiteConfig siteConfig) - { - var user = siteConfig.Site.Account; - - this.Site = siteConfig; - this.Loger = proxy.Loger; - this.IsLog = proxy.IsLog; - this.Password = UMC.Data.DataFactory.Instance().Password(SiteConfig.MD5Key(siteConfig.Root, user)); - - this.SiteCookie = new Entities.Cookie - { - Account = user, - user_id = UMC.Data.Utility.Guid(user, true), - Domain = this.Site.Root, - IndexValue = 0 - }; - this.IsChangeUser = false; - this.Context = proxy.Context; - this.Domain = new UMCUri(siteConfig.Domains[0]); - this.RawUrl = proxy.RawUrl; - this.Host = proxy.Host; - this.Cookies = new CookieContainer(); - this.User = proxy.User; - - - } - - const string DeviceIndex = "DeviceIndex"; - private bool IsCDN - { - get; set; - } - public static UMCUri WeightUri(SiteConfig site, Net.NetContext context) + public static int WeightUri(SiteConfig site, Net.NetContext context) { - if (site.WeightTotal > 0) { var value = 0; @@ -116,7 +195,6 @@ namespace UMC.Proxy case 2: if (context.Token != null && context.Token.Device.HasValue) { - value = Math.Abs(UMC.Data.Utility.IntParse(context.Token.Device.Value)) % site.WeightTotal; } else @@ -142,13 +220,54 @@ namespace UMC.Proxy qty += site.Weights[i]; if (value < qty) { - return new UMCUri(site.Domains[i]); - + return i; } } } - return new UMCUri(site.Domains[0]); + return 0; + } + UMCUri WeightUri(string p) + { + UMCUri url; + var d = this.Site.Domains[WeightUri(this.Site, this.Context)]; + var dIndex = d.IndexOf('*'); + if (dIndex > -1) + { + this.Host = d.Substring(dIndex + 1); + + if (String.IsNullOrEmpty(p)) + { + p = "www"; + } + _CacheKey = p; + + this.Authority = $".{this.Site.Root}.{WebServlet.MainDomain}"; + url = new UMCUri($"{d.Substring(0, dIndex)}{p}{this.Host}"); + } + else + { + url = new UMCUri(d); + if (String.IsNullOrEmpty(this.Site.Site.Host) == false) + { + var host = this.Site.Site.Host; + if (String.Equals(host, "*")) + { + this.Host = this.Context.Url.Authority; + } + else + { + this.Host = host; + } + + } + else + { + this.Host = url.Host; + } + } + return url; + } private bool IsTest; UMC.Security.Identity _Account; @@ -166,8 +285,8 @@ namespace UMC.Proxy } else if (String.Equals(this.SiteCookie.Account, user.Name)) { - var feildConfig = UMC.Data.JSON.Deserialize(this.SiteCookie.Config) ?? new Hashtable(); - if (feildConfig.ContainsKey("__ROLE")) + var feildConfig = UMC.Data.JSON.Deserialize(this.SiteCookie.Config);//?? new Hashtable(); + if (feildConfig?.ContainsKey("__ROLE") == true) { _Account = UMC.Security.Identity.Create(user, (feildConfig["__ROLE"] as string ?? "").Split(',')); } @@ -191,128 +310,13 @@ namespace UMC.Proxy return _Account; } } - public HttpProxy(SiteConfig site, UMC.Net.NetContext context, int staticModel, bool isCDN, string rawUrl) - { - this.Site = site; - this.IsLog = site.Site.IsDebug == true; - this.Loger = new StringWriter(); - this.Context = context; - this.User = context.Token.Identity(); - this.RawUrl = rawUrl; - this.StaticModel = staticModel; - this.IsCDN = isCDN; - - this.Cookies = new CookieContainer(); - - if (site.Domains.Length > 0) - { - this.Domain = WeightUri(site, context); - } - - InitClientCookie(); - if (StaticModel != 0) - { - if (this.Site.Site.AuthType > WebAuthType.All) - { - if (User.IsAuthenticated) - { - var deviceIndex = UMC.Data.Utility.IntParse(context.Cookies[$"{this.Site.Root}-{DeviceIndex}"], 0); - - if (site.Site.UserModel == Entities.UserModel.Bridge && deviceIndex == 0) - { - this.SiteCookie = new Entities.Cookie { Domain = Site.Root, user_id = User.Id.Value, IndexValue = 0 }; - } - else - { - this.SiteCookie = DataFactory.Instance().Cookie(this.Site.Root, User.Id.Value, deviceIndex); - } - if (this.SiteCookie == null && deviceIndex != 0) - { - this.SiteCookie = DataFactory.Instance().Cookie(this.Site.Root, User.Id.Value, 0); - - } - } - if (this.SiteCookie == null) - { - this.SiteCookie = new Entities.Cookie { Domain = Site.Root, user_id = User.Id.Value, IndexValue = 0 }; - } - } - - if (site.Test.Length > 0 && User.IsAuthenticated) - { - var authManager = UMC.Security.AuthManager.Instance(); - for (var i = 0; i < site.Test.Length; i++) - { - var tUrl = site.Test[i]; - if (tUrl.Users.Contains(User.Name)) - { - this.Domain = new UMCUri(tUrl.Url); - this.IsTest = true; - break; - } - else if (tUrl.Auths.Length > 0) - { - if (authManager.Check(this.User, 0, tUrl.Auths).Contains(1)) - { - this.IsTest = true; - this.Domain = new UMCUri(tUrl.Url); - break; - - } - } - - - } - } - - this.RawUrl = ReplaceRawUrl(this.RawUrl); - - - } - if (String.IsNullOrEmpty(this.Site.Site.Host) == false && this.Domain != null) - { - var port = this.Domain.Port; - var host = this.Site.Site.Host; - switch (port) - { - case 80: - case 443: - - if (String.Equals(host, "*")) - { - this.Host = this.Context.Url.Authority; - } - else - { - this.Host = host; - } - break; - default: - if (String.Equals(host, "*")) - { - this.Host = this.Context.Url.Authority; - } - else - { - this.Host = $"{host}:{port}"; - } - break; - } - - } - - if (this.SiteCookie == null) - { - this.SiteCookie = new Entities.Cookie { Domain = Site.Root, user_id = context.Token.UserId.Value, IndexValue = 0 }; - - } - this.StartTime = UMC.Data.Reflection.TimeSpanMilli(DateTime.Now); - } + string Cookies = String.Empty; void InitClientCookie() { + var sb = new StringBuilder(); var ms = this.Context.Cookies; for (var i = 0; i < ms.Count; i++) { @@ -320,19 +324,24 @@ namespace UMC.Proxy var value = ms.Get(i); switch (name) { + case DeviceIndex: case Web.WebServlet.SessionCookieName: break; default: - if (String.Equals($"{this.Site.Root}-{DeviceIndex}", name) == false) + if (sb.Length > 0) { - this.Cookies.Add(new System.Net.Cookie(name, value, "/", this.Domain.Host)); + sb.Append("; "); } + sb.Append(name); + sb.Append("="); + sb.Append(value); break; } } + this.Cookies = sb.ToString(); } - HashSet OuterCookies = new HashSet(); + List OuterCookies = new List(); public int StaticModel { get; @@ -427,7 +436,6 @@ namespace UMC.Proxy { var sb = new StringWriter(); - sb.WriteLine("
"); sb.WriteLine("回到云桌面"); sb.WriteLine("关闭登录"); @@ -774,8 +782,6 @@ namespace UMC.Proxy String GetConfig(Hashtable login, MatchEvaluator matchEvaluator, params string[] sParams) { - - var script = (login["Script"] as string ?? ""); script = script.Trim(); @@ -841,18 +847,12 @@ namespace UMC.Proxy var valResult = Regex.Replace(value, matchEvaluator); - var webr = this.Context.Transfer(getUrl, this.Cookies).Header(Header); + var webr = this.Context.Transfer(getUrl); webr.ContentType = ContentType; - var res = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr) : webr).Net(Method, valResult); - var cs = res.Headers.GetValues("Set-Cookie"); - if (cs != null) - { - foreach (var c in cs) - { - OuterCookies.Add(c); - } - } + var res = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr) : webr).Header(Header).Net(Method, valResult); + + this.SetCookie(res); if (this.IsLog == true) { this.Loger.Write(Method); @@ -900,18 +900,11 @@ namespace UMC.Proxy { config = SiteConfig.Config(value); } - var webr2 = this.Context.Transfer(getUrl, this.Cookies).Header(Header); + var webr2 = this.Context.Transfer(getUrl); + var res2 = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr2) : webr2).Header(Header).Get(); - var res2 = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr2) : webr2).Get(); - var cs2 = res2.Headers.GetValues("Set-Cookie"); - if (cs2 != null) - { - foreach (var c in cs2) - { - OuterCookies.Add(c); - } - } + this.SetCookie(res2); if (this.IsLog == true) { @@ -1247,12 +1240,14 @@ namespace UMC.Proxy { if (url.StartsWith("/")) { - jscode.Add(this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url), this.Cookies)).Get().ReadAsString()); + var webr = this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url))).Get(); + this.SetCookie(webr); + jscode.Add(webr.ReadAsString()); } else { - jscode.Add(this.Context.Transfer(new Uri(this.Domain, url), this.Cookies).Send("GET", null).ReadAsString()); + jscode.Add(this.Context.Transfer(new Uri(this.Domain, url)).Get().ReadAsString()); } Data.Utility.Writer(staticFile, jscode[jscode.Count - 1]); } @@ -1264,8 +1259,8 @@ namespace UMC.Proxy } else if (url.StartsWith("/")) { - var webr = this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url), this.Cookies)).Get(); - + var webr = this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url))).Get(); + this.SetCookie(webr); args.Add(webr.ReadAsString()); } } @@ -1276,7 +1271,64 @@ namespace UMC.Proxy bool IsLog; String errorMsg; + void SetCookie(string c) + { + var index = c.IndexOf('='); + if (index > 0) + { + var name = c.Substring(0, index + 1); + var isIndex = this.Cookies.IndexOf(name); + if (isIndex > -1) + { + var end = this.Cookies.IndexOf(';', isIndex); + + if (end > 0) + { + this.Cookies = this.Cookies.Remove(isIndex, end - isIndex + 2); + } + else + { + this.Cookies = this.Cookies.Remove(isIndex, this.Cookies.Length - isIndex).Trim(' ', ';'); + } + + } + var endex = c.IndexOf(';'); + if (endex > 0) + { + var cValue = c.Substring(0, endex); + + if (String.IsNullOrEmpty(this.Cookies)) + { + this.Cookies = cValue; + } + else + { + this.Cookies = $"{this.Cookies}; {cValue}"; + } + } + var i = OuterCookies.FindIndex(r => r.Substring(0, r.IndexOf('=') + 1) == name); + if (i > -1) + { + OuterCookies[i] = c; + } + else + { + OuterCookies.Add(c); + } + } + } + void SetCookie(NetHttpResponse response) + { + var cs = response.Headers.GetValues("Set-Cookie"); + if (cs != null) + { + foreach (var c in cs) + { + this.SetCookie(c); + } + } + } String ResetPasswork(Hashtable loginConfig, NameValueCollection form, SiteConfig siteConfig) { @@ -1294,11 +1346,12 @@ namespace UMC.Proxy var checkConfig = GetConf(String.Format("SITE_MIME_{0}_CHECK", proxy.Site.Root).ToUpper()); if (checkConfig.ContainsKey("Finish")) { - proxy.Cookies = new CookieContainer(); - if (String.IsNullOrEmpty(proxy.Site.Home) == false) + + if (String.IsNullOrEmpty(proxy.Site.Home) == false && proxy.Site.Home.StartsWith("http") == false) { - var r = this.Context.Transfer(new Uri(proxy.Domain, proxy.Site.Home), proxy.Cookies).Get(); + var r = proxy.Reqesut(this.Context.Transfer(new Uri(proxy.Domain, proxy.Site.Home))).Get(); r.ReadAsString(); + proxy.SetCookie(r); } var config = new Hashtable(); @@ -1325,13 +1378,11 @@ namespace UMC.Proxy } return newPass; } - else + else if (this.IsLog == true) { - if (this.IsLog == true) - { - this.Loger.WriteLine(this.errorMsg); - } + this.Loger.WriteLine(this.errorMsg); } + } else { @@ -1365,10 +1416,7 @@ namespace UMC.Proxy } finally { - if (response != null) - { - response.ReadAsString(); - } + response?.ReadAsString(); } } @@ -1951,7 +1999,6 @@ namespace UMC.Proxy { var conf = GetConf(String.Format("SITE_MIME_{0}_{2}_{1}", Site.Root, fdKey, fieldKey).ToUpper()); - var obj = UMC.Data.JSON.Deserialize(GetConfig(conf, matchEvaluator, list.ToArray())); if (obj is Array) { @@ -1968,17 +2015,14 @@ namespace UMC.Proxy FeildConfig[fdKey] = h["Value"]; if (String.IsNullOrEmpty(fValue)) { - errorMsg = $"获取到{feilds[fdKey]}的格式不正确"; return false; } } else { - errorMsg = $"获取到{feilds[fdKey]}的格式不正确"; return false; - } break; default: @@ -2117,7 +2161,7 @@ namespace UMC.Proxy this.Isurlencoded = ContentType.Contains("urlencoded"); var valResult = Regex.Replace(value, matchEvaluator); - var webR = this.Context.Transfer(getUrl, this.Cookies).Header(Header); + var webR = this.Context.Transfer(getUrl).Header(Header); webR.ContentType = ContentType; httpResponse = this.Reqesut(webR).Net(Method, valResult); if (this.IsLog == true) @@ -2132,7 +2176,7 @@ namespace UMC.Proxy } break; case "GET": - var webr2 = this.Context.Transfer(getUrl, this.Cookies).Header(Header); + var webr2 = this.Context.Transfer(getUrl).Header(Header); httpResponse = this.Reqesut(webr2).Get(); if (this.IsLog == true) @@ -2149,14 +2193,7 @@ namespace UMC.Proxy errorMsg = "接口Method不支持"; return false; } - var cs = httpResponse.Headers.GetValues("Set-Cookie"); - if (cs != null) - { - foreach (var c in cs) - { - OuterCookies.Add(c); - } - } + this.SetCookie(httpResponse); if (this.IsLog == true) { this.Loger.WriteLine("{0} {1} {2}", httpResponse.ProtocolVersion, (int)httpResponse.StatusCode, httpResponse.StatusDescription); @@ -2308,19 +2345,15 @@ namespace UMC.Proxy if (String.IsNullOrEmpty(Password)) { var home = Data.WebResource.Instance().WebDomain(); - this.Context.Redirect($"{this.Context.Url.Scheme}://{this.Site.Site.Account.Substring(1)}.{home}/UMC.Login?callback={Uri.EscapeDataString(this.Context.Url.AbsoluteUri)}"); return true; } - } else { WebServlet.Error(this.Context, "登录异常", String.Format("{0}应用引用模式设置错误,请联系管理员", this.Site.Caption, this.SiteCookie.Account), ""); return true; } - - } @@ -2419,7 +2452,7 @@ namespace UMC.Proxy } if (login.ContainsKey("IsNotCookieClear") == false) { - this.Cookies = new CookieContainer(); + this.Cookies = String.Empty; } var feildConfig = UMC.Data.JSON.Deserialize(this.SiteCookie.Config) ?? new Hashtable(); @@ -2550,7 +2583,6 @@ namespace UMC.Proxy var quoteRoot = this.Site.Site.Account.Substring(1); this.Context.Token.Put("DeviceQuote", currentTime.ToString()).Commit(Context.UserHostAddress, Context.Server); var home = Data.WebResource.Instance().WebDomain(); - this.Context.Redirect($"{this.Context.Url.Scheme}://{quoteRoot}.{home}/UMC.Login?callback={Uri.EscapeDataString(this.Context.Url.AbsoluteUri)}"); } return true; @@ -2584,8 +2616,7 @@ namespace UMC.Proxy } finally { - if (httpResponse != null) - httpResponse.ReadAsString(); + httpResponse?.ReadAsString(); } } public bool ShareUser() @@ -2766,23 +2797,17 @@ namespace UMC.Proxy if (isHome) { - // var home = form.Get("Home") ?? "UMC.Login"; - // if (home.Contains("UMC.Login")) - // { - - - if (String.IsNullOrEmpty(_LoginRedirectLocation) == false) { var path = _LoginRedirectLocation; - if (_LoginRedirectLocation.StartsWith("http://") || _LoginRedirectLocation.StartsWith("http://")) + if (_LoginRedirectLocation.StartsWith("http://") || _LoginRedirectLocation.StartsWith("https://")) { path = new Uri(_LoginRedirectLocation).PathAndQuery; } if (IsLoginPath(this.Site, path)) { - this.Context.Redirect(new Uri(this.Domain, this.Site.Home ?? "/").PathAndQuery); + this.Context.Redirect(this.Site.Home ?? "/"); } else @@ -2792,7 +2817,7 @@ namespace UMC.Proxy } else { - this.Context.Redirect(new Uri(this.Domain, this.Site.Home ?? "/").PathAndQuery); + this.Context.Redirect(this.Site.Home ?? "/"); } } @@ -2849,11 +2874,6 @@ namespace UMC.Proxy return false; } - public CookieContainer Cookies - { - get; - private set; - } public static void LogWrite(NetContext context, SiteConfig config, int statusCode, String pathAndQuery, string account, int duration, NameValueCollection reHeaders, String attachmentFile) @@ -2920,11 +2940,14 @@ namespace UMC.Proxy m_HttpHeaders = httpResponse.Headers; var statusCode = Convert.ToInt32(httpResponse.StatusCode); this.Context.StatusCode = statusCode; - foreach (var o in this.OuterCookies) + var a = this.Authority; + var h = this.Host; + + if (a[0] == '.') { - m_HttpHeaders.Add("Set-Cookie", o); + a = a.Substring(a.IndexOf('.') + 1); + h = h.Substring(1); } - for (var i = 0; i < m_HttpHeaders.Count; i++) { var key = m_HttpHeaders.GetKey(i); @@ -2936,7 +2959,9 @@ namespace UMC.Proxy foreach (var k in vs) { - this.Context.AddHeader(key, ReplaceRedirect(k)); + var kname = k.Substring(0, k.IndexOf('=') + 1); + this.OuterCookies.RemoveAll(r => r.StartsWith(kname)); + this.Context.AddHeader(key, k.Replace(h, a)); } break; @@ -2982,6 +3007,10 @@ namespace UMC.Proxy break; } } + foreach (var o in this.OuterCookies) + { + this.Context.AddHeader("Set-Cookie", o.Replace(h, a)); + } var ContentType = httpResponse.ContentType; if (String.IsNullOrEmpty(ContentType) == false) @@ -3104,13 +3133,9 @@ namespace UMC.Proxy LogWrite(this.Context, this.Site, this.Context.StatusCode, String.Format("{0} {1}", Context.HttpMethod, this.RawUrl), this.SiteCookie.Account, (int)(UMC.Data.Reflection.TimeSpanMilli(DateTime.Now) - StartTime), m_HttpHeaders, _AttachmentFile); - // if (this.Site.Site.AuthType > WebAuthType.All) - // { this.SaveCookie(); - // } if (this.IsLog && User.IsAuthenticated) { - this.Loger.WriteLine("Cookie:{0}", this.Cookies.GetCookieHeader(this.Domain)); var file = UMC.Data.Reflection.ConfigPath(String.Format("Static\\log\\{0}\\{1}.log", Site.Root, User.Name)); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(file))) @@ -3172,28 +3197,70 @@ namespace UMC.Proxy { this.Context.ReadAsForm(this.Login); } - void Login(NameValueCollection form) + void ClearCookie() { - String Domain = this.Context.Url.Host; - var cdmn = Domain; - - String cookieStr = String.Empty; - if (Regex.IsMatch(Domain, @"^(\d{1,3}.)+\d{1,3}$") == false) + if (this.Site.OutputCookies.Count == 0) { - - var ds = cdmn.Split('.'); - if (ds.Length > 2) + var ms = this.Context.Cookies; + for (var i = 0; i < ms.Count; i++) { - cdmn = ds[ds.Length - 2] + "." + ds[ds.Length - 1]; + var name = ms.GetKey(i); + var value = ms.Get(i); + switch (name) + { + case DeviceIndex: + case Web.WebServlet.SessionCookieName: + break; + default: + this.OuterCookies.Add($"{name}=; Expires={DateTime.Now.AddDays(-1).ToString("r")}; HttpOnly; Path=/"); + break; + } } - cookieStr = $" Domain={cdmn};"; + this.Cookies = String.Empty; } + else + { + var em = this.Site.OutputCookies.GetEnumerator(); + while (em.MoveNext()) + { + this.OuterCookies.Add($"{em.Current.Key}=; Expires={DateTime.Now.AddDays(-1).ToString("r")}; HttpOnly; Path={em.Current.Value}"); + } + var sb = new StringBuilder(); + var ms = this.Context.Cookies; + for (var i = 0; i < ms.Count; i++) + { + var name = ms.GetKey(i); + var value = ms.Get(i); + switch (name) + { + case DeviceIndex: + case Web.WebServlet.SessionCookieName: + break; + default: + if (this.Site.OutputCookies.TryGetValue(name, out var path) == false) + { + if (sb.Length > 0) + { + sb.Append("; "); + } + sb.Append(name); + sb.Append("="); + sb.Append(value); + } + break; + } + } + this.Cookies = sb.ToString(); + } + } + void Login(NameValueCollection form) + { var apis = this.Context.Url.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (apis.Length == 1) { - this.Context.AddHeader("Set-Cookie", $"{this.Site.Root}-{DeviceIndex}=0; Expires={DateTime.Now.AddYears(-10).ToString("r")}; HttpOnly;{cookieStr} Path=/"); + this.Context.AddHeader("Set-Cookie", $"{DeviceIndex}=; Expires={DateTime.Now.AddDays(-10).ToString("r")}; HttpOnly; Path=/"); if (this.Site.Site.UserModel == Entities.UserModel.Bridge) @@ -3268,21 +3335,23 @@ namespace UMC.Proxy break; } } - this.Cookies = new CookieContainer(); + this.Cookies = String.Empty; //new CookieContainer(); this.Login(true, false, form, String.Empty); this.ProcessEnd(); return; default: if (Utility.IntParse(lv, -1) > -1) { + ClearCookie(); + if (String.Equals(lv, "0") == false) { - this.Context.AddHeader("Set-Cookie", $"{this.Site.Root}-{DeviceIndex}={lv}; HttpOnly;{cookieStr} Path=/");//, DeviceIndex, lv)); + this.Context.AddHeader("Set-Cookie", $"{DeviceIndex}={lv}; HttpOnly; Path=/"); } else { - this.Context.AddHeader("Set-Cookie", $"{this.Site.Root}-{DeviceIndex}=0; Expires={DateTime.Now.AddYears(-10).ToString("r")}; HttpOnly;{cookieStr} Path=/");//, DeviceIndex, DateTime.Now.AddYears(-10).ToString("r"))); + this.Context.AddHeader("Set-Cookie", $"{DeviceIndex}=; Expires={DateTime.Now.AddYears(-10).ToString("r")}; HttpOnly; Path=/"); } this.Context.Redirect("/UMC.Login/Go"); @@ -3347,6 +3416,7 @@ namespace UMC.Proxy } } } + string _CacheKey; public void ProcessRequest() { @@ -3363,7 +3433,7 @@ namespace UMC.Proxy default: { - var webReq = this.Reqesut(this.Context.Transfer(getUrl, this.Cookies)); + var webReq = this.Reqesut(this.Context.Transfer(getUrl)); SiteConfig.ReplaceSetting replaceSetting; if (this.CheckPath(getUrl.AbsolutePath, this.Context.ContentType, out replaceSetting)) @@ -3427,7 +3497,7 @@ namespace UMC.Proxy return; } - var pmd5Key = this.Site.Site.Version ?? String.Empty; + var pmd5Key = $"{this.Site.Site.Version ?? String.Empty}{_CacheKey}"; if (this.StaticModel >= 0) { switch (this.StaticModel) @@ -3437,10 +3507,10 @@ namespace UMC.Proxy case 1: break; case 2: - pmd5Key = this.SiteCookie.Account; + pmd5Key = $"{pmd5Key}{this.SiteCookie.Account}"; break; default: - pmd5Key = String.Format("{0}_{1}", this.SiteCookie.Account, UMC.Data.Utility.TimeSpan() / 60 / this.StaticModel); + pmd5Key = String.Format("{0}_{1}_{2}", this.SiteCookie.Account, UMC.Data.Utility.TimeSpan() / 60 / this.StaticModel, pmd5Key); break; } } @@ -3485,7 +3555,7 @@ namespace UMC.Proxy } this.Context.UseSynchronousIO(this.ProcessEnd); - var webr = this.Reqesut(Context.Transfer(getUrl, this.Cookies)); + var webr = this.Reqesut(Context.Transfer(getUrl)); webr.Get(httpResponse => { @@ -3529,13 +3599,12 @@ namespace UMC.Proxy } else if (this.CheckPath(getUrl.AbsolutePath, ContentType, out replaceSetting)) { - if ((replaceSetting.Model & SiteConfig.HostReplaceModel.Remove) == SiteConfig.HostReplaceModel.Remove || - (replaceSetting.Model & SiteConfig.HostReplaceModel.Replace) == SiteConfig.HostReplaceModel.Replace) + if ((replaceSetting.Model & SiteConfig.HostReplaceModel.Replace) == SiteConfig.HostReplaceModel.Replace) { model = 3; } } - else if (String.Equals(ContentType, "text/css", StringComparison.CurrentCultureIgnoreCase) && IsCDN) + else if (String.Equals(ContentType, "text/css", StringComparison.CurrentCultureIgnoreCase)) { model = 4; } @@ -3598,7 +3667,7 @@ namespace UMC.Proxy UMC.Data.Utility.Move(tempFile, filename); using (var fileStream = System.IO.File.OpenRead(filename)) { - this.Context.OutputCache(cacheStream); + this.Context.OutputCache(fileStream); } this.Context.OutputFinish(); @@ -3896,32 +3965,54 @@ namespace UMC.Proxy { File.Delete(cacheKey); } + + string Authority; public HttpWebRequest Reqesut(HttpWebRequest webr) { if (this.StaticModel != 0) { WebServlet.WebHeaderConf(webr, this.Site, this.Context, this.SiteCookie.Account); } - if (String.IsNullOrEmpty(this.Host) == false) + + var Referer = webr.Headers[HttpRequestHeader.Referer]; + var h = this.Host; + if (h.StartsWith('.')) { - var h = this.Host; - webr.Headers[HttpRequestHeader.Host] = h; - if (String.Equals(h, this.Context.Url.Authority) == false) + webr.Headers[HttpRequestHeader.Host] = this.Domain.Authority; + if (String.IsNullOrEmpty(Referer) == false) { - var Referer = webr.Headers[HttpRequestHeader.Referer]; - if (String.IsNullOrEmpty(Referer) == false) - { - webr.Headers[HttpRequestHeader.Referer] = String.Format("{0}://{1}{2}", this.Domain.Scheme, h, Referer.Substring(Referer.IndexOf('/', 8))); + var pIndex2 = Referer.IndexOf('/', 8); + var p = Referer.Substring(pIndex2); + var pIndex = Referer.IndexOf('/', 1); + var host = Referer.Substring(pIndex + 2, pIndex2 - pIndex - 2); + var reqHost = host.Replace(Authority, h); + webr.Headers[HttpRequestHeader.Referer] = String.Format("{0}://{1}{2}", this.Domain.Scheme, reqHost, p); + + if (String.IsNullOrEmpty(webr.Headers["Origin"]) == false) + webr.Headers["Origin"] = String.Format("{0}://{1}/", this.Domain.Scheme, reqHost); - } - var Origin = webr.Headers["Origin"]; - if (String.IsNullOrEmpty(Origin) == false) - { - webr.Headers["Origin"] = String.Format("{0}://{1}/", this.Domain.Scheme, h); - } } } + else + { + + webr.Headers[HttpRequestHeader.Host] = h; + + if (String.IsNullOrEmpty(Referer) == false && String.Equals(h, this.Context.Url.Authority) == false) + { + var pIndex2 = Referer.IndexOf('/', 8); + var p = Referer.Substring(pIndex2); + webr.Headers[HttpRequestHeader.Referer] = String.Format("{0}://{1}{2}", this.Domain.Scheme, h, p); + if (String.IsNullOrEmpty(webr.Headers["Origin"]) == false) + webr.Headers["Origin"] = String.Format("{0}://{1}/", this.Domain.Scheme, h); + + } + } + if (String.IsNullOrEmpty(this.Cookies) == false) + { + webr.Headers[HttpRequestHeader.Cookie] = this.Cookies; + } webr.Timeout = (this.Site.Site.Timeout ?? 100) * 1000; return webr; } @@ -3964,14 +4055,14 @@ namespace UMC.Proxy { if (replaceSetting != null) { - var setting = new SiteConfig.ReplaceSetting() { Hosts = new Dictionary(replaceSetting.Hosts) }; + var setting = new SiteConfig.ReplaceSetting();// Hosts = new Dictionary(replaceSetting.Hosts) }; setting.Model = replaceSetting.Model | mv.Current.Value.Model; - var mm = mv.Current.Value.Hosts.GetEnumerator(); + var mm = mv.Current.Value.Domains.GetEnumerator(); while (mm.MoveNext()) { - setting.Hosts[mm.Current.Key] = mm.Current.Value; + setting.Domains.Add(mm.Current); } replaceSetting = setting; } @@ -4213,64 +4304,60 @@ namespace UMC.Proxy return sb.ToString(); } + void InputReplaceHost(System.IO.Stream writer, System.IO.Stream reader, SiteConfig.ReplaceSetting rpsetting) { - var host = this.Context.Url.Host; - var scheme = String.Format("{0}://", this.Context.Url.Scheme); - var dScheme = Uri.EscapeDataString(scheme); - - var host2 = this.Domain.UMCAuthority; - if (String.IsNullOrEmpty(Site.Site.Host) == false && String.Equals(Site.Site.Host, "*") == false) - { - if (host2.IndexOf(':') > -1) - { - host2 = String.Format("{0}:{1}", Site.Site.Host, this.Domain.Port); - } - else - { - host2 = Site.Site.Host; - } - } - - var hash = new List>(); - hash.Add(new Tuple(host, host2)); + var hash = new List>(); - if (rpsetting.Hosts.Count > 0) + if (rpsetting.Domains.Count > 0) { - var hem = rpsetting.Hosts.GetEnumerator(); + var hem = rpsetting.Domains.GetEnumerator(); while (hem.MoveNext()) { - hash.Add(new Tuple(hem.Current.Key, hem.Current.Value.UMCAuthority)); + hash.Add(Tuple.Create(hem.Current.Main, hem.Current.ProxyPort, hem.Current.Decode)); + // hash.Add(new Tuple(hem.Current.Key, hem.Current.Value.UMCAuthority)); } } + hash.Add(Tuple.Create(Site.MainHost.Main, Site.MainHost.ProxyPort, Site.MainHost.Decode)); + // hash.Add(new Tuple(this.Authority, this.Host)); + ReplaceHost(writer, reader, hash, (x, y) => false); } - void ReplaceHost(System.IO.Stream writer, System.IO.Stream reader, List> shosts, Func, bool> func) + static byte[] strHttps = UTF8Encoding.ASCII.GetBytes("https://"); + static byte[] strHttp = UTF8Encoding.ASCII.GetBytes("http://"); + static byte[] httpsEncode = UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString("https://")); + static byte[] httpEncode = UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString("http://")); + static byte[] strEncodePort = UTF8Encoding.ASCII.GetBytes("%3A"); + void ReplaceHost(System.IO.Stream writer, System.IO.Stream reader, List> hosts, Func, bool> func) { - var hosts = new List>(); - var hLength = 0; - foreach (var em in shosts) - { - hosts.Add(new Tuple(UTF8Encoding.ASCII.GetBytes(em.Item1), UTF8Encoding.ASCII.GetBytes(em.Item2), UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString(em.Item2)))); - var Ht = em.Item1; - if (hLength < Ht.Length) - { - hLength = Ht.Length; - } - } + // var hbuffer = System.Buffers.ArrayPool.Shared.Rent(60 * 3 * shosts.Count); + // var hosts = new List>(); + var hLength = hosts.Max(r => r.Item1.Length); + // ReadOnlySpan + // int start = 0; + // foreach (var em in shosts) + // { - var strHttps = UTF8Encoding.ASCII.GetBytes("https://"); - var strHttp = UTF8Encoding.ASCII.GetBytes("http://"); - var nowScheme = UTF8Encoding.ASCII.GetBytes(String.Format("{0}://", this.Context.Url.Scheme)); - var nowSchemeEncode = UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString(String.Format("{0}://", this.Context.Url.Scheme))); - var httpsEncode = UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString("https://")); - var httpEncode = UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString("http://")); - var strEncodePort = UTF8Encoding.ASCII.GetBytes("%3A"); + // // hosts.Add(new Tuple(UTF8Encoding.ASCII.GetBytes(em.Item1), UTF8Encoding.ASCII.GetBytes(em.Item2), UTF8Encoding.ASCII.GetBytes(Uri.EscapeDataString(em.Item2)))); + // var Ht = em.Item1; + // if (hLength < Ht.Length) + // { + // hLength = Ht.Length; + // } + // } + byte[] nowScheme = strHttp; + + byte[] nowSchemeEncode = httpEncode; + if (this.Context.Url.Scheme.Length > 4) + { + nowScheme = strHttps; + nowSchemeEncode = httpsEncode; + } var bsize = 14 + hLength; var bf = new byte[1]; @@ -4282,19 +4369,19 @@ namespace UMC.Proxy while (reader.Read(bf, 0, 1) > 0) { - switch ((char)bf[0]) + switch (bf[0]) { - case ' ': - case '\r': - case '\t': - case '\n': + case 20://' ': + case 10://'\r': + case 09://'\t': + case 13://'\n': isPort = false; buffer.Add(bf[0]); writer.Write(buffer.ToArray(), 0, buffer.Count); buffer.Clear(); isFind = false; continue; - case ':': + case 58://':': if (isFind) { isPort = true; @@ -4478,50 +4565,41 @@ namespace UMC.Proxy return; } - var host = this.Domain.Host; - var host2 = this.Context.Url.Authority; + // var host2 = this.Authority; var rp = rpsetting.Model; - if ((rp & SiteConfig.HostReplaceModel.Remove) == SiteConfig.HostReplaceModel.Remove) - { - host2 = ""; + // if ((rp & SiteConfig.HostReplaceModel.Remove) == SiteConfig.HostReplaceModel.Remove) + // { + // host2 = ""; - } - else if ((rp & SiteConfig.HostReplaceModel.Replace) != SiteConfig.HostReplaceModel.Replace) + // } + // else + if ((rp & SiteConfig.HostReplaceModel.Replace) != SiteConfig.HostReplaceModel.Replace) { OuterEncoding(response, encoding, output, isEncoding); return; } - var hosts = new List>(); - hosts.Add(new Tuple(host, host2)); - - hosts.Add(new Tuple(this.Context.Url.Host, host2)); + var hosts = new List>(); - if (String.IsNullOrEmpty(this.Host) == false && String.Equals(Site.Site.Host, "*") == false) - { - var hStr = Site.Site.Host; - if (String.IsNullOrEmpty(hStr) == false) - { - hosts.Add(new Tuple(hStr, host2)); - } - } - if (rpsetting.Hosts?.Count > 0) + if (rpsetting.Domains.Count > 0) { - var em = rpsetting.Hosts.GetEnumerator(); + var em = rpsetting.Domains.GetEnumerator(); while (em.MoveNext()) { - hosts.Add(new Tuple(em.Current.Value.Host, em.Current.Key)); + hosts.Add(Tuple.Create(em.Current.Proxy, em.Current.Main, em.Current.Main)); + // hosts.Add(new Tuple(em.Current.Value.Host, em.Current.Key)); } } + // if (String.Equals(this.Host, host2) == false) + // { + hosts.Add(Tuple.Create(Site.MainHost.Proxy, Site.MainHost.Main, Site.MainHost.Main)); + Stream stream; if (isEncoding) { - - stream = - new DeflateStream(output, CompressionMode.Compress); + stream = new DeflateStream(output, CompressionMode.Compress); this.Context.AddHeader("Content-Encoding", "deflate"); - } else { @@ -4557,38 +4635,50 @@ namespace UMC.Proxy return; } - var host = this.Domain.Host; - var host2 = this.Context.Url.Host; - switch (hostRpMode) - { - case SiteConfig.HostReplaceModel.Remove: - host2 = String.Empty; - break; - } + // var host2 = this.Authority; + // switch (hostRpMode) + // { + // case SiteConfig.HostReplaceModel.Remove: + // host2 = String.Empty; + // break; + // } + // var hosts = new List>(); - var hosts = new List>(); - hosts.Add(new Tuple(host, host2)); + // if (String.Equals(this.Host, host2) == false) + // { + // hosts.Add(new Tuple(this.Host, host2)); + // } - if (String.IsNullOrEmpty(this.Host) == false) - { - hosts.Add(new Tuple(Site.Site.Host, host2)); + // if (replaceSetting != null) + // { + // if (replaceSetting.Hosts.Count > 0) + // { + // var em = replaceSetting.Hosts.GetEnumerator(); + // while (em.MoveNext()) + // { + // hosts.Add(new Tuple(em.Current.Value.Host, em.Current.Key)); + // } + + // } + // } - } - if (replaceSetting != null) + var hosts = new List>(); + + if (replaceSetting.Domains.Count > 0) { - if (replaceSetting.Hosts.Count > 0) + var em = replaceSetting.Domains.GetEnumerator(); + while (em.MoveNext()) { - var em = replaceSetting.Hosts.GetEnumerator(); - while (em.MoveNext()) - { - - hosts.Add(new Tuple(em.Current.Value.Host, em.Current.Key)); - } - + hosts.Add(Tuple.Create(em.Current.Proxy, em.Current.Main, em.Current.Main)); + // hosts.Add(new Tuple(em.Current.Value.Host, em.Current.Key)); } + } + // if (String.Equals(this.Host, host2) == false) + // { + hosts.Add(Tuple.Create(Site.MainHost.Proxy, Site.MainHost.Main, Site.MainHost.Main)); Stream stream; if (isEncoding) { @@ -4632,7 +4722,7 @@ namespace UMC.Proxy ReplaceHost(stream, DataFactory.Instance().Decompress(response, encoding), hosts, (x, r) => false); } } - static bool EndsWith(List buffer, byte[] end) + static bool EndsWith(List buffer, Span end) { var el = end.Length; var bl = buffer.Count; diff --git a/Proxy/SiteActivity.cs b/Proxy/SiteActivity.cs index c54367f..cb66398 100644 --- a/Proxy/SiteActivity.cs +++ b/Proxy/SiteActivity.cs @@ -50,7 +50,6 @@ namespace UMC.Proxy.Activities } void Market(Site site) { - // System.Net.Cache.HttpCacheAgeControl var secret = UMC.Data.WebResource.Instance().Provider["appSecret"]; if (String.IsNullOrEmpty(secret)) { @@ -72,7 +71,7 @@ namespace UMC.Proxy.Activities confData.Remove("IsDesktop"); confData.Remove("SiteKey"); confData.Remove("HostModel"); - confData.Remove("HostReConf"); + // confData.Remove("HostReConf"); confData.Remove("Conf"); var login = UMC.Data.DataFactory.Instance().Config($"SITE_MIME_{site.Root}_LOGIN".ToUpper()); @@ -150,9 +149,9 @@ namespace UMC.Proxy.Activities { var config = this.AsyncDialog("Config", g => { - var from = new Web.UIFormDialog() { Title = "透传会话" }; - from.AddTextarea("Cookie名称", "OutputCookie", site.OutputCookies).PlaceHolder("Cookie的名称").NotRequired(); - from.AddFooter("多个用换行、空格或逗号符分割,用*表示透传所有Cookie"); + var from = new Web.UIFormDialog() { Title = "过期会话" }; + from.AddTextarea("Cookie名称", "OutputCookie", site.OutputCookies).PlaceHolder("Cookie的名称和路径").NotRequired(); + from.AddFooter("当从新登录时需要清空的Cookie,值为name和path字典对。"); from.Submit("确认", "Site.Config"); return from; }); @@ -201,20 +200,20 @@ namespace UMC.Proxy.Activities } var path = new Hashtable(); - if (String.IsNullOrEmpty(site.Conf) == false) + if (String.IsNullOrEmpty(site.SubSite) == false) { - var v = UMC.Data.JSON.Deserialize(site.Conf) as Hashtable; + var v = UMC.Data.JSON.Deserialize(site.SubSite) as Hashtable; if (v != null) { path = v; } } path[Key] = Value; - site.Conf = UMC.Data.JSON.Serialize(path); + site.SubSite = UMC.Data.JSON.Serialize(path); DataFactory.Instance().Put(new Site { Root = site.Root, - Conf = site.Conf + SubSite = site.SubSite }); this.Context.Send("Site.Config", true); @@ -1025,9 +1024,9 @@ namespace UMC.Proxy.Activities var path = new Hashtable(); - if (String.IsNullOrEmpty(site.Conf) == false) + if (String.IsNullOrEmpty(site.SubSite) == false) { - var v = UMC.Data.JSON.Deserialize(site.Conf) as Hashtable; + var v = UMC.Data.JSON.Deserialize(site.SubSite) as Hashtable; if (v != null) { path = v; @@ -1136,7 +1135,7 @@ namespace UMC.Proxy.Activities ui2 = ui.NewSection().AddCell("内容转化", String.IsNullOrEmpty(site.HostReConf) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "HostReConf")).Post(request.Model, request.Command)); - // ui2.AddCell("透传会话", String.IsNullOrEmpty(site.OutputCookies) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "OutputCookie")).Post(request.Model, request.Command)); + ui2.AddCell("过期会话", String.IsNullOrEmpty(site.OutputCookies) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "OutputCookie")).Post(request.Model, request.Command)); var m = "标准模式"; switch ((site.UserModel ?? UserModel.Standard)) @@ -1313,9 +1312,9 @@ namespace UMC.Proxy.Activities { var path = new Hashtable(); - if (String.IsNullOrEmpty(site.Conf) == false) + if (String.IsNullOrEmpty(site.SubSite) == false) { - var v = UMC.Data.JSON.Deserialize(site.Conf) as Hashtable; + var v = UMC.Data.JSON.Deserialize(site.SubSite) as Hashtable; if (v != null) { path = v; @@ -1323,7 +1322,7 @@ namespace UMC.Proxy.Activities } path.Remove(Model); - DataFactory.Instance().Put(new Site { Root = site.Root, Conf = UMC.Data.JSON.Serialize(path) }); + DataFactory.Instance().Put(new Site { Root = site.Root, SubSite = UMC.Data.JSON.Serialize(path) }); } else { diff --git a/Proxy/SiteConfig.cs b/Proxy/SiteConfig.cs index b4fa7d0..e930cc4 100644 --- a/Proxy/SiteConfig.cs +++ b/Proxy/SiteConfig.cs @@ -7,6 +7,12 @@ using System.Linq; namespace UMC.Proxy { + // class HostConvert + // { + // Span Item1; + // Span Item1(); + // Span Item1; + // } public class UMCUri : Uri { public UMCUri([StringSyntax("Uri")] string uriString) : base(uriString) @@ -36,7 +42,7 @@ namespace UMC.Proxy public enum HostReplaceModel { Replace = 1, - Remove = 2, + // Remove = 2, Input = 4, CDN = 8, Script = 16 @@ -48,10 +54,18 @@ namespace UMC.Proxy get; set; } - public System.Collections.Generic.Dictionary Hosts + // public System.Collections.Generic.Dictionary Hosts + // { + // get; + // set; + // } + HashSet _Domains = new HashSet(new EqualityComparer()); + public HashSet Domains { - get; - set; + get + { + return _Domains; + } } } public class LogSetting @@ -91,6 +105,27 @@ namespace UMC.Proxy set; } } + public class HostConvert + { + public byte[] Main; + public byte[] Proxy; + public byte[] ProxyPort; + public byte[] Decode; + } + class EqualityComparer : IEqualityComparer + { + + public bool Equals(HostConvert x, HostConvert y) + { + return Utility.IntParse(System.Security.Cryptography.MD5.HashData(x.Main)) == Utility.IntParse(System.Security.Cryptography.MD5.HashData(y.Main)); + + } + + public int GetHashCode(HostConvert obj) + { + return Utility.IntParse(System.Security.Cryptography.MD5.HashData(obj.Main)); + } + } public class KeyValue { @@ -136,16 +171,8 @@ namespace UMC.Proxy public SiteConfig(Entities.Site site) { this.Caption = site.Caption; - var vindex = this.Caption.IndexOf("v.", StringComparison.CurrentCultureIgnoreCase); - if (vindex > -1) - { - this.Caption = this.Caption.Substring(0, vindex); - } - if (String.IsNullOrEmpty(site.Home) == false && (site.Home.StartsWith("https:") || site.Home.StartsWith("http:"))) - { - this.Home = new Uri(site.Home).PathAndQuery; - } - else + + if (String.IsNullOrEmpty(site.Home) == false)//&& (site.Home.StartsWith("https:") || site.Home.StartsWith("http:"))) { this.Home = site.Home; } @@ -161,13 +188,13 @@ namespace UMC.Proxy for (var i = 0; i < dom.Length; i++) { var v = dom[i].Trim(); - var timeout = String.Empty; + var KeepAlive = String.Empty; if (String.IsNullOrEmpty(v) == false) { var valueIndex = v.IndexOf('~'); if (valueIndex > 0) { - timeout = v.Substring(valueIndex).Trim(); + KeepAlive = v.Substring(valueIndex + 1).Trim(); v = v.Substring(0, valueIndex).Trim(); } if (v.EndsWith("]")) @@ -187,16 +214,16 @@ namespace UMC.Proxy ls.Add(1); } - var sIndex = tUrl.LastIndexOf('/'); + var sIndex = tUrl.IndexOf('/', 8); if (sIndex > 0) { tUrl = tUrl.Substring(0, sIndex); } domains.Add(tUrl); - if (String.IsNullOrEmpty(timeout) == false) + if (String.IsNullOrEmpty(KeepAlive) == false) { - Net.NetProxy.KeepAlives(new Uri(tUrl), Utility.IntParse(timeout, 60)); + Net.NetProxy.KeepAlives(new Uri(tUrl), Utility.IntParse(KeepAlive, 60)); } } else @@ -226,7 +253,7 @@ namespace UMC.Proxy } if (tUsers.Count > 0 || tAuth.Count > 0) { - var sIndex = tUrl.LastIndexOf('/');//, tIndex); + var sIndex = tUrl.IndexOf('/', 8);//, tIndex); if (sIndex > 0) { tUrl = tUrl.Substring(0, sIndex); @@ -239,7 +266,7 @@ namespace UMC.Proxy { if (tUrl.StartsWith("file://") == false) { - var sIndex = tUrl.LastIndexOf('/'); + var sIndex = tUrl.IndexOf('/', 8); if (sIndex > 0) { tUrl = tUrl.Substring(0, sIndex); @@ -249,9 +276,9 @@ namespace UMC.Proxy total++; ls.Add(1); } - if (String.IsNullOrEmpty(timeout) == false) + if (String.IsNullOrEmpty(KeepAlive) == false) { - Net.NetProxy.KeepAlives(new Uri(tUrl), Utility.IntParse(timeout, 60)); + Net.NetProxy.KeepAlives(new Uri(tUrl), Utility.IntParse(KeepAlive, 60)); } } @@ -279,16 +306,15 @@ namespace UMC.Proxy this.Weights = ls.ToArray(); this.AllowPath = Config(site.AuthConf); - this.OutputCookies = Config(site.OutputCookies); this.LogoutPath = Config(site.LogoutPath); this.AppendJSConf = Config(site.AppendJSConf); this.RedirectPath = Config(site.RedirectPath); this.ImagesConf = Config(site.ImagesConf); var subSite = new List(); - if (String.IsNullOrEmpty(site.Conf) == false) + if (String.IsNullOrEmpty(site.SubSite) == false) { - var v = UMC.Data.JSON.Deserialize(site.Conf) as Hashtable; + var v = UMC.Data.JSON.Deserialize(site.SubSite) as Hashtable; if (v != null) { var pem = v.GetEnumerator(); @@ -309,12 +335,14 @@ namespace UMC.Proxy } _subSite = subSite.ToArray(); InitStatic(site.StaticConf); - InitHost(site.HostReConf); InitHeader(site.HeaderConf); InitLogConf(site.LogConf); + InitCookie(site.OutputCookies); + this.AllowAllPath = this.AllowPath.Contains("*"); + InitHost(site.HostReConf); } public bool AllowAllPath @@ -406,6 +434,42 @@ namespace UMC.Proxy this.LogConf.ResHeaders = rhs.ToArray(); this.LogConf.Cookies = cs.ToArray(); } + void InitCookie(String sConf) + { + + if (String.IsNullOrEmpty(sConf) == false) + { + + foreach (var k in sConf.Split('\n', ',')) + { + + var v = k.Trim(); + if (String.IsNullOrEmpty(v) == false && String.Equals(k, "none") == false) + { + var nindex = v.IndexOf(':'); + if (nindex == -1) + { + nindex = v.IndexOf(' '); + if (nindex == -1) + { + nindex = v.IndexOf('\t'); + } + } + if (nindex > -1) + { + var mv = v.Substring(nindex + 1).Trim(); + var key = v.Substring(0, nindex).Trim(); + if (mv.StartsWith('/')) + { + _OutputCookies[key] = mv; + } + } + + } + + } + } + } void InitHeader(String sConf) { @@ -448,9 +512,6 @@ namespace UMC.Proxy } - - - } } @@ -526,12 +587,44 @@ namespace UMC.Proxy } } - + public HostConvert MainHost + { + get; + private set; + } void InitHost(String sConf) { + // this.Do var domain = Data.WebResource.Instance().Provider["domain"]; - var union = Data.WebResource.Instance().Provider["union"] ?? "."; + var union = "."; + if (this.Domains.Length > 0) + { + var url = this.Domains[0]; + var hostConvert = this.MainHost = new HostConvert(); + + if (url.Contains('*')) + { + hostConvert.Main = System.Text.ASCIIEncoding.UTF8.GetBytes(String.Format(".{0}{1}{2}", this.Site.Root, union, domain)); + var l = new UMCUri(url.Replace("*.", "")); + hostConvert.Proxy = System.Text.ASCIIEncoding.UTF8.GetBytes("." + l.Host); + hostConvert.ProxyPort = System.Text.ASCIIEncoding.UTF8.GetBytes("." + l.UMCAuthority); + hostConvert.Decode = System.Text.ASCIIEncoding.UTF8.GetBytes(Uri.EscapeDataString("." + l.UMCAuthority)); + } + else + { + if (String.IsNullOrEmpty(this.Site.Host) == false) + { + url = url.Replace(new UMCUri(url).Host, this.Site.Host); + } + hostConvert.Main = System.Text.ASCIIEncoding.UTF8.GetBytes(String.Format("{0}{1}{2}", this.Site.Root, union, domain)); + var l = new UMCUri(url); + hostConvert.Proxy = System.Text.ASCIIEncoding.UTF8.GetBytes(l.Host); + hostConvert.ProxyPort = System.Text.ASCIIEncoding.UTF8.GetBytes(l.UMCAuthority); + hostConvert.Decode = System.Text.ASCIIEncoding.UTF8.GetBytes(Uri.EscapeDataString(l.UMCAuthority)); + + } + } if (String.IsNullOrEmpty(sConf) == false) { foreach (var k in sConf.Split('\n')) @@ -557,11 +650,11 @@ namespace UMC.Proxy key = v.Substring(0, nindex).Trim(); if (_HostPage.ContainsKey(key) == false) { - _HostPage[key] = new ReplaceSetting() { Model = HostReplaceModel.Replace, Hosts = new System.Collections.Generic.Dictionary() }; + _HostPage[key] = new ReplaceSetting() { Model = HostReplaceModel.Replace }; } ReplaceSetting replaceSetting = _HostPage[key]; HostReplaceModel hostReplace = replaceSetting.Model; - var list = replaceSetting.Hosts; + var list = replaceSetting.Domains; foreach (var kv in mv) { @@ -625,14 +718,40 @@ namespace UMC.Proxy } if (String.IsNullOrEmpty(url) == false) { - var surl = new UMCUri(url); - if (String.IsNullOrEmpty(sit.Host) == false) + // var v= + var hostConvert = new HostConvert(); + + if (url.Contains('*')) + { + hostConvert.Main = System.Text.ASCIIEncoding.UTF8.GetBytes(String.Format(".{0}{1}{2}", sit.Root, union, domain)); + var l = new UMCUri(url.Replace("*.", "")); + hostConvert.Proxy = System.Text.ASCIIEncoding.UTF8.GetBytes("." + l.Host); + hostConvert.ProxyPort = System.Text.ASCIIEncoding.UTF8.GetBytes("." + l.UMCAuthority); + hostConvert.Decode = System.Text.ASCIIEncoding.UTF8.GetBytes(Uri.EscapeDataString("." + l.UMCAuthority)); + } + else { - surl = new UMCUri(url.Replace(surl.Host, sit.Host)); + if (String.IsNullOrEmpty(sit.Host) == false) + { + url = url.Replace(new UMCUri(url).Host, sit.Host); + } + hostConvert.Main = System.Text.ASCIIEncoding.UTF8.GetBytes(String.Format("{0}{1}{2}", sit.Root, union, domain)); + var l = new UMCUri(url); + hostConvert.Proxy = System.Text.ASCIIEncoding.UTF8.GetBytes(l.Host); + hostConvert.ProxyPort = System.Text.ASCIIEncoding.UTF8.GetBytes(l.UMCAuthority); + hostConvert.Decode = System.Text.ASCIIEncoding.UTF8.GetBytes(Uri.EscapeDataString(l.UMCAuthority)); + + } + list.Add(hostConvert); + // var surl = new UMCUri(url); + // if (String.IsNullOrEmpty(sit.Host) == false) + // { + // surl = new UMCUri(url.Replace(surl.Host, sit.Host)); + // } - list[String.Format("{0}{1}{2}", sit.Root, union, domain)] = surl;// new Uri(String.f); + // list[String.Format("{0}{1}{2}", sit.Root, union, domain)] = surl;// new Uri(String.f); break; } @@ -644,7 +763,7 @@ namespace UMC.Proxy hostReplace |= HostReplaceModel.Replace; break; case "rm": - hostReplace |= HostReplaceModel.Remove; + hostReplace |= HostReplaceModel.Replace; break; case "input": case "in": @@ -750,10 +869,14 @@ namespace UMC.Proxy get; private set; } - public String[] OutputCookies + System.Collections.Generic.Dictionary _OutputCookies = new Dictionary(); + + public System.Collections.Generic.Dictionary OutputCookies { - get; - private set; + get + { + return _OutputCookies; + } } public String[] ImagesConf { diff --git a/Proxy/SiteServerActivity.cs b/Proxy/SiteServerActivity.cs index c185143..d5b9235 100644 --- a/Proxy/SiteServerActivity.cs +++ b/Proxy/SiteServerActivity.cs @@ -183,14 +183,13 @@ namespace UMC.Proxy.Activities var union = provider["union"] ?? "."; var scheme = provider["scheme"] ?? "http"; fm.AddRadio("主协议", "scheme").Put("http", "http", scheme == "http").Put("https", "https", scheme == "https"); - // fm.AddRadio("连接符", "union").Put("-", "-", union == "-").Put(".", ".", union == "."); fm.Submit("确认", $"{request.Model}.{request.Command}"); return fm; }); - // provider.Attributes["union"] = Domains["union"]; + provider.Attributes["scheme"] = Domains["scheme"]; provider.Attributes["domain"] = Domains["domain"]; - + var pc = UMC.Data.Reflection.Configuration("assembly") ?? new ProviderConfiguration(); pc.Add(provider); diff --git a/Proxy/WebFactory.cs b/Proxy/WebFactory.cs index b823a5b..eacd20a 100644 --- a/Proxy/WebFactory.cs +++ b/Proxy/WebFactory.cs @@ -28,7 +28,7 @@ namespace UMC.Proxy public override void ProcessActivity(WebRequest request, WebResponse response) { var user = this.Context.Token.Identity(); - var httpProxy = new HttpProxy(site, this.Context.Client.Context, -1, false, "/"); + var httpProxy = new HttpProxy(site, this.Context.Client.Context, -1, "/", String.Empty); if (httpProxy.Domain == null) { this.Prompt("安全审记", $"此应用临时关闭,请联系应用管理员"); @@ -173,7 +173,7 @@ namespace UMC.Proxy var getUrl = new Uri(httpProxy.Domain, $"/UMC/{Utility.Guid(this.Context.Token.Device.Value)}/{query}"); var content = this.Context.Client.Context; - var webReq = httpProxy.Reqesut(content.Transfer(getUrl, httpProxy.Cookies)); + var webReq = httpProxy.Reqesut(content.Transfer(getUrl)); webReq.ContentType = "application/x-www-form-urlencoded"; webReq.Post(sb.ToString(), res => { diff --git a/Proxy/WebServlet.cs b/Proxy/WebServlet.cs index ae5c117..c8f6bff 100644 --- a/Proxy/WebServlet.cs +++ b/Proxy/WebServlet.cs @@ -467,7 +467,6 @@ namespace UMC.Proxy var appids = new List(); foreach (var p in account.Providers) { - // var p = account[i]; if (String.Equals(p.Type, "dingtalk")) { @@ -617,7 +616,7 @@ namespace UMC.Proxy var ds = cdmn.Split('.'); if (ds.Length > 2) { - cdmn = cdmn.Substring(ds[0].Length + 1);// ds[ds.Length - 2] + "." + ds[ds.Length - 1]; + cdmn = cdmn.Substring(ds[0].Length + 1); } } context.AddHeader("Set-Cookie", String.Format(cookieStr, sessionKey, DateTime.Now.AddYears(10).ToString("r"), cdmn, SameSite)); @@ -1006,9 +1005,6 @@ namespace UMC.Proxy { webMeta.Put("msg", "域名所有权签名验证不通过").Put("code", "error"); } - - - } UMC.Data.JSON.Serialize(webMeta, context.Output); context.OutputFinish(); @@ -1096,7 +1092,7 @@ namespace UMC.Proxy if (psite2 != null) { context.Token = new UMC.Data.AccessToken(Guid.Empty).Login(new UMC.Security.Guest(Guid.Empty), 0); - var httpProxy = new HttpProxy(psite2, context, 0, true, rawUrl); + var httpProxy = new HttpProxy(psite2, context, 0, rawUrl, String.Empty); if (httpProxy.Domain == null) { @@ -1282,7 +1278,7 @@ namespace UMC.Proxy rawUrl = rawUrl.Substring(keyIndex2); } } - var httpProxy = new HttpProxy(psite, context, 0, true, rawUrl); + var httpProxy = new HttpProxy(psite, context, 0, rawUrl, String.Empty); if (httpProxy.Domain == null) { Close(context); @@ -1323,65 +1319,45 @@ namespace UMC.Proxy var host = context.Url.Host; SiteConfig siteConfig = null; + var pfxDomain = String.Empty; var ishttps = IsHttps; + if (host.Length > MainDomain.Length && host.EndsWith(MainDomain)) + { + var rook = host.Substring(0, host.Length - MainDomain.Length - 1); + var ls = rook.Split('.', '-'); + if (ls.Length > 1) + { + pfxDomain = rook.Substring(0, rook.Length - ls[ls.Length - 1].Length - 1); + siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(ls[ls.Length - 1]); + } + else + { - for (var i = 0; i < host.Length; i++) + siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(ls[0]); + } + } + if (siteConfig == null) { - if (host[i] == '.') + + var hostSite = DataFactory.Instance().HostSite(host); + if (hostSite != null) { - var hostSite = DataFactory.Instance().HostSite(host); - if (hostSite != null) + if (hostSite.IsAuthModel == true) { - if (hostSite.IsAuthModel == true) + if (hostSite.Scheme == 2) { - if (hostSite.Scheme == 2) - { - ishttps = true; - } - - siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(hostSite.Root); - break; + ishttps = true; } - else - { - Transfer(hostSite, context, rawUrl); + siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(hostSite.Root); - return; - } } - - siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(host.Substring(0, i)); - break; - } - else if (host[i] == '-') - { - siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(host.Substring(0, i)); - if (siteConfig == null) + else { - var hostSite = DataFactory.Instance().HostSite(host); - if (hostSite != null) - { - if (hostSite.IsAuthModel == true) - { - if (hostSite.Scheme == 2) - { - ishttps = true; - } + Transfer(hostSite, context, rawUrl); - siteConfig = UMC.Proxy.DataFactory.Instance().SiteConfig(hostSite.Root); - break; - } - else - { - Transfer(hostSite, context, rawUrl); - - return; - } - } + return; } - break; } - } if (ishttps && context.Url.Port == 80) { @@ -1412,7 +1388,7 @@ namespace UMC.Proxy } if (siteConfig != null) { - Proxy(context, siteConfig, rawUrl); + Proxy(context, siteConfig, pfxDomain, rawUrl); return; } @@ -1432,7 +1408,14 @@ namespace UMC.Proxy break; } + var file = Path == "/" ? "/index.html" : Path; + var staticFile = FilePath($"{UMC.Data.Reflection.ConfigPath("Static")}{file}"); + if (System.IO.File.Exists(staticFile)) + { + TransmitFile(context, staticFile, true); + return; + } switch (Path) { case "/notsupport": @@ -1608,7 +1591,10 @@ namespace UMC.Proxy HttpWebRequest WebTransfer(SiteConfig siteConfig, UMC.Net.NetContext context, string rawUrl) { - var webR = new Uri(HttpProxy.WeightUri(siteConfig, context), rawUrl).WebRequest(); + + var d = siteConfig.Domains[HttpProxy.WeightUri(siteConfig, context)]; //siteConfig.Domains[WeightUri(this.Site, this.Context)]; + var dIndex = d.IndexOf('*'); + var webR = new Uri(new Uri(dIndex > 0 ? d.Remove(dIndex, 2) : d), rawUrl).WebRequest(); WebHeaderConf(webR, siteConfig, context, String.Empty); @@ -1877,7 +1863,6 @@ namespace UMC.Proxy context.OutputFinish(); break; case "PUT": - //x X500DistinguishedName/x var ns = new NameValueCollection(); if (Data.Utility.CheckSign(context.Headers, "umc-", siteConfig.Site.AppSecret) == false) { @@ -1921,6 +1906,22 @@ namespace UMC.Proxy } } + static string _MainDomain; + public static string MainDomain + { + get + { + if (String.IsNullOrEmpty(_MainDomain)) + { + _MainDomain = UMC.Data.WebResource.Instance().Provider["domain"] ?? "localhost"; + } + return _MainDomain; + } + set + { + _MainDomain = value; + } + } void Transfer(SiteConfig siteConfig, UMC.Net.NetContext context, string RawUrl) { @@ -2100,7 +2101,7 @@ namespace UMC.Proxy if (i == -1) { context.StatusCode = 405; - context.ContentType = "text/plain;charset=utf-8"; + context.ContentType = "text/plain; charset=utf-8"; context.Output.Write("接收Body错误"); context.OutputFinish(); } @@ -2132,7 +2133,7 @@ namespace UMC.Proxy var v = UMC.Data.HotCache.Cache(type, hsh["value"] as Hashtable); if (v != null) { - context.ContentType = "application/json;charset=utf-8"; + context.ContentType = "application/json; charset=utf-8"; UMC.Data.JSON.Serialize(v, context.Output, "ts"); return; } @@ -2197,9 +2198,9 @@ namespace UMC.Proxy { get; set; } - // public i - void Proxy(UMC.Net.NetContext context, SiteConfig psite, string rawUrl) + + void Proxy(UMC.Net.NetContext context, SiteConfig psite, String pfxDomain, string rawUrl) { for (var i = 0; i < psite.SubSite.Length; i++) { @@ -2324,7 +2325,8 @@ namespace UMC.Proxy this.StaticFile(psite, psite.Domains[0].Substring(7), context, rawUrl); return; } - var httpProxy = new HttpProxy(psite, context, HttpProxy.CheckStaticPage(psite, path), false, rawUrl); + var httpProxy = new HttpProxy(psite, context, HttpProxy.CheckStaticPage(psite, path), rawUrl, pfxDomain); + if (httpProxy.Domain == null) { Close(context); @@ -2380,7 +2382,7 @@ namespace UMC.Proxy var getUrl = new Uri(httpProxy.Domain, httpProxy.RawUrl); - context.Tag = httpProxy.Reqesut(context.Transfer(getUrl, httpProxy.Cookies)); + context.Tag = httpProxy.Reqesut(context.Transfer(getUrl)); } diff --git a/UMC.Host.csproj b/UMC.Host.csproj index 64baf34..550561a 100644 --- a/UMC.Host.csproj +++ b/UMC.Host.csproj @@ -1,13 +1,10 @@ + true Exe net7.0 - UMC.Proxy - 4