From 4c2f737caa4f02ff1bc200a7a8873884610acefb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E9=A1=BA=E6=98=8E?= Date: Wed, 13 Sep 2023 00:50:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96DNS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Mime/HttpMime.cs | 3 +- Mime/HttpMimeSocket.cs | 83 ++- Mime/HttpsMimeSocket.cs | 64 ++- Program.cs | 3 + Proxy/HttpProxy.cs | 1101 ++++++++++++++++++++----------------- Proxy/SiteAppActivity.cs | 26 +- Proxy/SiteConfig.cs | 17 +- Proxy/SiteMimeActivity.cs | 222 ++++---- 8 files changed, 867 insertions(+), 652 deletions(-) diff --git a/Mime/HttpMime.cs b/Mime/HttpMime.cs index 66a9e2f..2f98b4d 100644 --- a/Mime/HttpMime.cs +++ b/Mime/HttpMime.cs @@ -9,7 +9,6 @@ namespace UMC.Host public abstract class HttpMime : IDisposable { - // int pid = 0; public abstract int Id { get; } public int ActiveTime { @@ -17,7 +16,7 @@ namespace UMC.Host get; set; } public int TimeOut { protected set; get; } = 20; - // public int TimeOut + public virtual string Scheme => "http"; public abstract void OutputFinish(); public abstract void Write(byte[] buffer, int offset, int count); diff --git a/Mime/HttpMimeSocket.cs b/Mime/HttpMimeSocket.cs index 517dbf2..e67324c 100644 --- a/Mime/HttpMimeSocket.cs +++ b/Mime/HttpMimeSocket.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Specialized; using System.IO; using System.Net; using System.Net.Security; @@ -17,7 +18,7 @@ namespace UMC.Host class HttpsWebSocket : WebSocket { - public byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(0x600);//new byte[0x600]; + public byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(0x600); System.IO.Stream stream; public HttpsWebSocket(HttpMime mime, System.IO.Stream stream) { @@ -25,9 +26,9 @@ namespace UMC.Host this.stream = stream; WebSocketRead(); } - public override void Receive(byte[] buffer, int offset, int size) + public override async void Receive(byte[] buffer, int offset, int size) { - stream.Write(buffer, offset, size); + await stream.WriteAsync(buffer, offset, size); } HttpMime mime1; @@ -38,10 +39,11 @@ namespace UMC.Host { while ((size = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { + // var mime1.Write(buffer, 0, size); } } - catch // (Exception ex) + catch { this.Dispose(); return; @@ -79,7 +81,10 @@ namespace UMC.Host SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs(); eventArgs.SetBuffer(buffer); eventArgs.Completed += Http; - this.socket.ReceiveAsync(eventArgs); + if (!this.socket.ReceiveAsync(eventArgs)) + { + ProcessReceive(eventArgs); + } } HttpMime mime; @@ -116,10 +121,9 @@ namespace UMC.Host } } - public override void Receive(byte[] buffer, int offset, int size) + public override async void Receive(byte[] buffer, int offset, int size) { - - socket.Send(buffer, offset, size, SocketFlags.None); + await socket.SendAsync(new ArraySegment(buffer, offset, size), SocketFlags.None); } protected override void Header(byte[] data, int offset, int size) { @@ -166,9 +170,6 @@ namespace UMC.Host { ProcessReceive(eventArgs); } - - - } Socket _socket; int pid = 0; @@ -313,28 +314,66 @@ namespace UMC.Host var client = new Socket(SocketType.Stream, ProtocolType.Tcp); - await client.ConnectAsync(url.Host, url.Port); - + await client.ConnectAsync(await NetProxy.DNS(url.Host), url.Port); + // await client.ConnectAsync(url.Host, url.Port); if (url.Scheme == "https") { SslStream ssl = new SslStream(new NetworkStream(client, true), false, (sender, certificate, chain, sslPolicyErrors) => true); await ssl.AuthenticateAsClientAsync(url.Host, null, SslProtocols.None, false); - var ws = new HttpsWebSocket(this, ssl); - var size = UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer);// - request = ws; - await ssl.WriteAsync(ws.buffer, 0, size); - _webSocket = ws; + + await ssl.WriteAsync(_data, 0, UMC.Net.NetHttpResponse.Header(webRequest, _data)); + int size = await ssl.ReadAsync(_data, 0, _data.Length); + + if (NetBridge.ResponseHeader(_data, 0, size, new NameValueCollection(), out var statucode) && statucode == HttpStatusCode.SwitchingProtocols) + { + request = _webSocket = new HttpsWebSocket(this, ssl); + + this._socket.Send(_data, 0, size, SocketFlags.None); + } + else + { + this._socket.Send(_data, 0, size, SocketFlags.None); + this.Dispose(); + } } else { - var ws = new HttpWebSocket(this, client); - request = _webSocket; - client.Send(ws.buffer, 0, UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer), SocketFlags.None); - _webSocket = ws; + client.Send(_data, 0, UMC.Net.NetHttpResponse.Header(webRequest, _data), SocketFlags.None); + var size = client.Receive(_data, 0, _data.Length, SocketFlags.None); + if (NetBridge.ResponseHeader(_data, 0, size, new NameValueCollection(), out var statucode) && statucode == HttpStatusCode.SwitchingProtocols) + { + request = _webSocket = new HttpWebSocket(this, client); + this._socket.Send(_data, 0, size, SocketFlags.None); + } + else + { + + this._socket.Send(_data, 0, size, SocketFlags.None); + this.Dispose(); + } } + // if (url.Scheme == "https") + // { + // SslStream ssl = new SslStream(new NetworkStream(client, true), false, (sender, certificate, chain, sslPolicyErrors) => true); + // await ssl.AuthenticateAsClientAsync(url.Host, null, SslProtocols.None, false); + // var ws = new HttpsWebSocket(this, ssl); + // var size = UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer);// + // request = ws; + // await ssl.WriteAsync(ws.buffer, 0, size); + // _webSocket = ws; + // } + // else + // { + // var ws = new HttpWebSocket(this, client); + // request = _webSocket; + // client.Send(ws.buffer, 0, UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer), SocketFlags.None); + // _webSocket = ws; + + // } + HttpMimeServier.httpMimes.TryRemove(this.pid, out var _); } catch (Exception ex) diff --git a/Mime/HttpsMimeSocket.cs b/Mime/HttpsMimeSocket.cs index 24fa842..0c0d065 100644 --- a/Mime/HttpsMimeSocket.cs +++ b/Mime/HttpsMimeSocket.cs @@ -2,6 +2,7 @@ using System.Net.WebSockets; namespace UMC.Host; using System; +using System.Collections.Specialized; using System.IO; using System.Net; using System.Net.Security; @@ -37,14 +38,14 @@ public class HttpsMimeSocket : HttpMime public override String Host => _Host; public override String RemoteIpAddress => _remoteIpAddress; - public override void Write(byte[] buffer, int offset, int count) + public override async void Write(byte[] buffer, int offset, int count) { if (isDispose == false) { try { - _stream.Write(buffer, offset, count); + await _stream.WriteAsync(buffer, offset, count); } catch { @@ -115,25 +116,64 @@ public class HttpsMimeSocket : HttpMime var client = new Socket(SocketType.Stream, ProtocolType.Tcp); - await client.ConnectAsync(url.Host, url.Port); - + // await client.ConnectAsync(url.Host, url.Port); + + await client.ConnectAsync(await NetProxy.DNS(url.Host), url.Port); + + // if (url.Scheme == "https") + // { + // SslStream ssl = new SslStream(new NetworkStream(client, true), false, (sender, certificate, chain, sslPolicyErrors) => true); + // await ssl.AuthenticateAsClientAsync(url.Host, null, SslProtocols.None, false); + // var ws = new HttpsWebSocket(this, ssl); + // var size = UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer);// + // request = ws; + // await ssl.WriteAsync(ws.buffer, 0, size); + // _webSocket = ws; + // } + // else + // { + // var ws = new HttpWebSocket(this, client); + // request = _webSocket; + // client.Send(ws.buffer, 0, UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer), SocketFlags.None); + // _webSocket = ws; + + // } if (url.Scheme == "https") { SslStream ssl = new SslStream(new NetworkStream(client, true), false, (sender, certificate, chain, sslPolicyErrors) => true); await ssl.AuthenticateAsClientAsync(url.Host, null, SslProtocols.None, false); - var ws = new HttpsWebSocket(this, ssl); - request = ws; - await ssl.WriteAsync(ws.buffer, 0, UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer)); - _webSocket = ws; + await ssl.WriteAsync(_data, 0, UMC.Net.NetHttpResponse.Header(webRequest, _data)); + int size = await ssl.ReadAsync(_data, 0, _data.Length); + + if (NetBridge.ResponseHeader(_data, 0, size, new NameValueCollection(), out var statucode) && statucode == HttpStatusCode.SwitchingProtocols) + { + request = _webSocket = new HttpsWebSocket(this, ssl); + + this._stream.Write(_data, 0, size); + } + else + { + this._stream.Write(_data, 0, size); + this.Dispose(); + } } else { - var ws = new HttpWebSocket(this, client); - request = ws; - client.Send(ws.buffer, 0, UMC.Net.NetHttpResponse.Header(webRequest, ws.buffer), SocketFlags.None); - _webSocket = ws; + client.Send(_data, 0, UMC.Net.NetHttpResponse.Header(webRequest, _data), SocketFlags.None); + var size = client.Receive(_data, 0, _data.Length, SocketFlags.None); + if (NetBridge.ResponseHeader(_data, 0, size, new NameValueCollection(), out var statucode) && statucode == HttpStatusCode.SwitchingProtocols) + { + request = _webSocket = new HttpWebSocket(this, client); + this._stream.Write(_data, 0, size); + } + else + { + + this._stream.Write(_data, 0, size); + this.Dispose(); + } } diff --git a/Program.cs b/Program.cs index 3dc3bb6..d9535fe 100644 --- a/Program.cs +++ b/Program.cs @@ -11,6 +11,7 @@ using System.IO.Pipes; using System.Runtime.InteropServices; using System.Linq; using System.Reflection; +using System.Threading.Tasks; [assembly: UMC.Web.Mapping] namespace UMC.Host @@ -20,6 +21,8 @@ namespace UMC.Host public static void Main(string[] args) { + var ipHost = Dns.GetHostAddresses("blj.sau.edu.cn"); + AppDomain.CurrentDomain.UnhandledException += UnhandledException; var variable = System.Environment.GetEnvironmentVariable("UMC"); diff --git a/Proxy/HttpProxy.cs b/Proxy/HttpProxy.cs index ebcdbe6..5fd5cb6 100644 --- a/Proxy/HttpProxy.cs +++ b/Proxy/HttpProxy.cs @@ -474,7 +474,6 @@ namespace UMC.Proxy } - } bool CheckAccountSelectHtml() { @@ -742,20 +741,22 @@ namespace UMC.Proxy } } - String GetConfig(Hashtable login, MatchEvaluator matchEvaluator, params string[] sParams) + void GetConfig(Hashtable login, MatchEvaluator matchEvaluator, Action action) { var script = (login["Script"] as string ?? ""); script = script.Trim(); if ((script.StartsWith("{") && script.EndsWith("}")) || (script.StartsWith("[") && script.EndsWith("]"))) { - return Regex.Replace(script, matchEvaluator); + action(Regex.Replace(script, matchEvaluator)); + return; } var rawUrl = login["RawUrl"] as string; if (String.IsNullOrEmpty(rawUrl)) { errorMsg = $"未配置请求的Url"; - return "[]"; + action("[]"); + return; } var Header = login["Header"] as string; @@ -787,12 +788,15 @@ namespace UMC.Proxy if (String.IsNullOrEmpty(Method)) { errorMsg = $"未配置{rawUrl}请求的Method"; - return "[]"; + + action("[]"); + return; } - var args = new List(sParams); - var config = new String[0]; + + String valResult = null; + var value = (login["Content"] as string) ?? String.Empty; - var value = login["Content"] as string; + var webr = this.Context.Transfer(getUrl); switch (Method) { case "POST": @@ -801,120 +805,190 @@ namespace UMC.Proxy if (String.IsNullOrEmpty(ContentType)) { errorMsg = $"未配置{rawUrl}请求的ContentType"; - return "[]"; + + action("[]"); + return; } else { - this.Isurlencoded = ContentType.Contains("urlencoded"); - - var valResult = Regex.Replace(value, matchEvaluator); - - var webr = this.Context.Transfer(getUrl); - webr.ContentType = ContentType; - var res = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr) : webr).Header(Header).Net(Method, valResult); + this.Isurlencoded = ContentType.Contains("urlencoded"); - this.SetCookie(res); - if (this.IsLog == true) - { - this.Loger.Write(Method); - this.Loger.Write(":"); - this.Loger.WriteLine(getUrl.PathAndQuery); - this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr.Headers.ToByteArray())); + valResult = Regex.Replace(value, matchEvaluator); - this.Loger.WriteLine(valResult); - this.Loger.WriteLine(); - this.Loger.WriteLine("{0} {1} {2}", res.ProtocolVersion, (int)res.StatusCode, res.StatusDescription); + } + break; + } - this.Loger.WriteLine(Utility.NameValue(res.Headers)); - } + (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr) : webr).Header(Header).Net(Method, valResult, res => + { + this.SetCookie(res); + if (this.IsLog == true) + { + this.Loger.Write(Method); + this.Loger.Write(":"); + this.Loger.WriteLine(getUrl.PathAndQuery); + this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr.Headers.ToByteArray())); - if (res.ContentType.Contains("image/")) - { - return $"{{\"image\":\"{Convert.ToBase64String(res.ReadAsByteArray())}\"}}"; - } - else - { - args.Add(res.ReadAsString()); - } - if (this.IsLog == true) - { - this.Loger.WriteLine(args[args.Count - 1]); - this.Loger.WriteLine(); - } + this.Loger.WriteLine(valResult); + this.Loger.WriteLine(); - int statusCode = Convert.ToInt32(res.StatusCode); - if (statusCode >= 500) - { - LogWrite(this.Context, this.Site, statusCode, String.Format("{0} {1}", Method, getUrl.PathAndQuery), this.SiteCookie.Account, 0, res.Headers, this._AttachmentFile); + this.Loger.WriteLine("{0} {1} {2}", res.ProtocolVersion, (int)res.StatusCode, res.StatusDescription); - } - if (res.StatusCode != HttpStatusCode.OK) - { - return "{}"; - } - } - break; - default: - case "GET": - if (String.IsNullOrEmpty(value) == false) - { - config = SiteConfig.Config(value); - } - var webr2 = this.Context.Transfer(getUrl); + this.Loger.WriteLine(Utility.NameValue(res.Headers)); + } - var res2 = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr2) : webr2).Header(Header).Get(); + int statusCode = Convert.ToInt32(res.StatusCode); + if (statusCode >= 500) + { + LogWrite(this.Context, this.Site, statusCode, String.Format("{0} {1}", Method, getUrl.PathAndQuery), this.SiteCookie.Account, 0, res.Headers, this._AttachmentFile); - this.SetCookie(res2); + } + res.ReadAsString(str => + { if (this.IsLog == true) { - - this.Loger.Write(Method); - this.Loger.Write(":"); - this.Loger.WriteLine(getUrl.PathAndQuery); - this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr2.Headers.ToByteArray())); + this.Loger.WriteLine(str); this.Loger.WriteLine(); - this.Loger.WriteLine("{0} {1} {2}", res2.ProtocolVersion, (int)res2.StatusCode, res2.StatusDescription); - this.Loger.WriteLine(Utility.NameValue(res2.Headers)); } - - if (res2.ContentType.Contains("image/")) + if (res.StatusCode != HttpStatusCode.OK) { - return $"{{\"image\":\"{Convert.ToBase64String(res2.ReadAsByteArray())}\"}}"; + action("{}"); + return; } - else + if (String.IsNullOrEmpty(script) || String.Equals(script, "none", StringComparison.CurrentCultureIgnoreCase)) { - args.Add(res2.ReadAsString()); + action("{}"); + return; } - if (this.IsLog == true) + else { - this.Loger.WriteLine(args[args.Count - 1]); - this.Loger.WriteLine(); + action(UMC.Data.JSON.Serialize(GetKeyValue(str, script))); } - if (res2.StatusCode != HttpStatusCode.OK) + }, this.Context.Error); + + }); + + } + String GetConfig(Hashtable login, MatchEvaluator matchEvaluator) + { + var script = (login["Script"] as string ?? ""); + + script = script.Trim(); + if ((script.StartsWith("{") && script.EndsWith("}")) || (script.StartsWith("[") && script.EndsWith("]"))) + { + return Regex.Replace(script, matchEvaluator); + } + var rawUrl = login["RawUrl"] as string; + if (String.IsNullOrEmpty(rawUrl)) + { + errorMsg = $"未配置请求的Url"; + return "[]"; + + } + var Header = login["Header"] as string; + if (String.IsNullOrEmpty(Header) == false) + { + this.Isurlencoded = false; + Header = Regex.Replace(Header, matchEvaluator); + } + + this.Isurlencoded = true; + + var PathAndQuery = Regex.Replace(rawUrl, matchEvaluator); + + Uri getUrl; + + var sStrDomain = login["Domain"] as string; + + if (String.IsNullOrEmpty(sStrDomain) == false) + { + getUrl = new Uri(new Uri(sStrDomain), PathAndQuery); + + } + else + { + getUrl = new Uri(Domain, PathAndQuery); + } + + var Method = login["Method"] as string ?? "GET"; + + String valResult = null; + var webr = this.Context.Transfer(getUrl); + var value = (login["Content"] as string) ?? String.Empty; + switch (Method) + { + case "POST": + case "PUT": + var ContentType = login["ContentType"] as string; + if (String.IsNullOrEmpty(ContentType)) { - return "{}"; + this.Isurlencoded = false; + } - int statusCode2 = Convert.ToInt32(res2.StatusCode); - if (statusCode2 >= 500) + else { - LogWrite(this.Context, this.Site, statusCode2, String.Format("{0} {1}", Method, getUrl.PathAndQuery), this.SiteCookie.Account, 0, res2.Headers, _AttachmentFile); - } + this.Isurlencoded = ContentType.Contains("urlencoded"); + + valResult = Regex.Replace(value, matchEvaluator); + webr.ContentType = ContentType; + } break; } + var res = (this.Domain.Host.Equals(getUrl.Host) ? this.Reqesut(webr) : webr).Header(Header).Net(Method, valResult); + + this.SetCookie(res); + var str = res.ReadAsString(); + if (this.IsLog == true) + { + this.Loger.Write(Method); + this.Loger.Write(":"); + this.Loger.WriteLine(getUrl.PathAndQuery); + this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr.Headers.ToByteArray())); + + this.Loger.WriteLine(valResult); + this.Loger.WriteLine(); + + this.Loger.WriteLine("{0} {1} {2}", res.ProtocolVersion, (int)res.StatusCode, res.StatusDescription); + + this.Loger.WriteLine(Utility.NameValue(res.Headers)); + // } + + // if (res.ContentType.Contains("image/")) + // { + // return $"{{\"image\":\"{Convert.ToBase64String(res.ReadAsByteArray())}\"}}"; + // } + // else + // { + // args.Add(res.ReadAsString()); + // } + // if (this.IsLog == true) + // { + this.Loger.WriteLine(str); + this.Loger.WriteLine(); + } + + int statusCode = Convert.ToInt32(res.StatusCode); + if (statusCode >= 500) + { + LogWrite(this.Context, this.Site, statusCode, String.Format("{0} {1}", Method, getUrl.PathAndQuery), this.SiteCookie.Account, 0, res.Headers, this._AttachmentFile); + + } + if (res.StatusCode != HttpStatusCode.OK) + { + return "{}"; + } if (String.IsNullOrEmpty(script) || String.Equals(script, "none", StringComparison.CurrentCultureIgnoreCase)) { return "{}"; } - - var vvsValue = GetKeyValue(args[args.Count - 1], script); - return UMC.Data.JSON.Serialize(vvsValue); + return UMC.Data.JSON.Serialize(GetKeyValue(str, script)); } Object GetKeyValue(String html, string nvConfig) { @@ -1164,53 +1238,53 @@ namespace UMC.Proxy return null; } - String GetScript(List jscode, List args, MatchEvaluator matchEvaluator, params String[] config) - { - - foreach (var s in config) - { - var surl = s.Trim(); - if (String.IsNullOrEmpty(surl) == false) - { - this.Isurlencoded = true; - var url = Regex.Replace(surl, matchEvaluator); - if (url.EndsWith(".js")) - { - if (url.StartsWith("https://") || url.StartsWith("http://") || url.StartsWith("/")) - { - var t = MD5(url); - var staticFile = Data.Reflection.ConfigPath("Static/TEMP/" + t); - if (System.IO.File.Exists(staticFile) == false) - { - if (url.StartsWith("/")) - { - 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)).Get().ReadAsString()); - } - Data.Utility.Writer(staticFile, jscode[jscode.Count - 1]); - } - else - { - jscode.Add(Data.Utility.Reader(staticFile)); - } - } - } - else if (url.StartsWith("/")) - { - var webr = this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url))).Get(); - this.SetCookie(webr); - args.Add(webr.ReadAsString()); - } - } - } - return DataFactory.Instance().Evaluate(String.Join(";", jscode.ToArray()), args.ToArray()); - } + // String GetScript(List jscode, List args, MatchEvaluator matchEvaluator, params String[] config) + // { + + // foreach (var s in config) + // { + // var surl = s.Trim(); + // if (String.IsNullOrEmpty(surl) == false) + // { + // this.Isurlencoded = true; + // var url = Regex.Replace(surl, matchEvaluator); + // if (url.EndsWith(".js")) + // { + // if (url.StartsWith("https://") || url.StartsWith("http://") || url.StartsWith("/")) + // { + // var t = MD5(url); + // var staticFile = Data.Reflection.ConfigPath("Static/TEMP/" + t); + // if (System.IO.File.Exists(staticFile) == false) + // { + // if (url.StartsWith("/")) + // { + // 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)).Get().ReadAsString()); + // } + // Data.Utility.Writer(staticFile, jscode[jscode.Count - 1]); + // } + // else + // { + // jscode.Add(Data.Utility.Reader(staticFile)); + // } + // } + // } + // else if (url.StartsWith("/")) + // { + // var webr = this.Reqesut(this.Context.Transfer(new Uri(this.Domain, url))).Get(); + // this.SetCookie(webr); + // args.Add(webr.ReadAsString()); + // } + // } + // } + // return DataFactory.Instance().Evaluate(String.Join(";", jscode.ToArray()), args.ToArray()); + // } bool IsLog; @@ -1922,13 +1996,7 @@ namespace UMC.Proxy var Password = this.Password; var matchEvaluator = Match(FeildConfig, newPass); - var list = new List(); - list.Add(username); - list.Add(Password); - if (string.IsNullOrEmpty(newPass) == false) - { - list.Add(newPass); - } + this.Isurlencoded = true; var feilds = login["Feilds"] as Hashtable ?? new Hashtable(); if (feilds.Count > 0) @@ -1937,13 +2005,19 @@ namespace UMC.Proxy while (fd.MoveNext()) { var fdKey = fd.Current; + if (fdKey == "LoginAfter") + { + continue; + } var fvalue = form.Get(fdKey); if (String.IsNullOrEmpty(fvalue)) { - 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())); + var conf = GetConf($"SITE_MIME_{Site.Root}_{fieldKey}_{fdKey}".ToUpper()); + + var obj = UMC.Data.JSON.Deserialize(GetConfig(conf, matchEvaluator)); + if (obj is Array) { Array array = obj as Array; @@ -2074,20 +2148,19 @@ namespace UMC.Proxy { getUrl = new Uri(Domain, PathAndQuery); } - - - var Method = login["Method"] as string; + var Method = login["Method"] as string ?? "GET"; if (String.IsNullOrEmpty(Method)) { errorMsg = "接口Method未配置"; return false; } - + var webR = this.Context.Transfer(getUrl).Header(Header); + String valResult = null; switch (Method) { case "POST": case "PUT": - var value = login["Content"] as string; + var value = (login["Content"] as string) ?? String.Empty; var ContentType = login["ContentType"] as string; if (String.IsNullOrEmpty(ContentType)) { @@ -2101,52 +2174,30 @@ namespace UMC.Proxy } else { - this.Isurlencoded = ContentType.Contains("urlencoded"); - var valResult = Regex.Replace(value, matchEvaluator); - - var webR = this.Context.Transfer(getUrl).Header(Header); + valResult = Regex.Replace(value, matchEvaluator); webR.ContentType = ContentType; - httpResponse = this.Reqesut(webR).Net(Method, valResult); - if (this.IsLog == true) - { - this.Loger.Write(Method); - this.Loger.Write(":"); - this.Loger.WriteLine(getUrl.PathAndQuery); - this.Loger.WriteLine(Utility.NameValue(webR.Headers)); - this.Loger.WriteLine(valResult); - this.Loger.WriteLine(); - } - } - break; - case "GET": - var webr2 = this.Context.Transfer(getUrl).Header(Header); - httpResponse = this.Reqesut(webr2).Get(); - if (this.IsLog == true) - { - this.Loger.Write(Method); - this.Loger.Write(":"); - this.Loger.WriteLine(getUrl.PathAndQuery); - this.Loger.WriteLine(webr2.Headers); - - this.Loger.WriteLine(); } break; - default: - errorMsg = "接口Method不支持"; - return false; } - this.SetCookie(httpResponse); + httpResponse = this.Reqesut(webR).Net(Method, valResult); if (this.IsLog == true) { - this.Loger.WriteLine("{0} {1} {2}", httpResponse.ProtocolVersion, (int)httpResponse.StatusCode, httpResponse.StatusDescription); + this.Loger.Write(Method); + this.Loger.Write(":"); + this.Loger.WriteLine(getUrl.PathAndQuery); + this.Loger.WriteLine(Utility.NameValue(webR.Headers)); + this.Loger.WriteLine(valResult); + this.Loger.WriteLine(); + this.Loger.WriteLine("{0} {1} {2}", httpResponse.ProtocolVersion, (int)httpResponse.StatusCode, httpResponse.StatusDescription); this.Loger.WriteLine(Utility.NameValue(httpResponse.Headers)); this.Loger.WriteLine(); } + this.SetCookie(httpResponse); var finish = login["Finish"] as string; if (finish.StartsWith("H:")) @@ -2227,10 +2278,13 @@ namespace UMC.Proxy } else if (String.Equals("Url", finish) == false) { - if (_CheckBody.Contains(finish)) + var vs = finish.Split('|', StringSplitOptions.RemoveEmptyEntries); + for (var i = 0; i < vs.Length; i++) { - return true; - + if (_CheckBody.Contains(vs[i])) + { + return true; + } } } break; @@ -2262,6 +2316,7 @@ namespace UMC.Proxy } } + String _CheckBody; bool Login(bool isHome, bool isBody, NameValueCollection form, String apiKey) @@ -2421,8 +2476,10 @@ namespace UMC.Proxy NetHttpResponse httpResponse = null; try { + // Console.WriteLine("用户登录"); var isOk = XHR(login, form, feildConfig, "LOGIN", "", out httpResponse); + // Console.WriteLine("登录完成"); if (isBody) { if (httpResponse.IsReadBody) @@ -2432,8 +2489,16 @@ namespace UMC.Proxy } else { - this.Context.UseSynchronousIO(this.ProcessEnd); - this.Response(httpResponse); + using (var ms = new System.IO.MemoryStream()) + { + httpResponse.ReadAsStream(ms); + ms.Position = 0; + + this.Header(httpResponse); + this.Context.ContentLength = ms.Length; + ms.CopyTo(this.Context.OutputStream); + + } } return true; @@ -2441,7 +2506,7 @@ namespace UMC.Proxy } if (isOk) { - return LoginAtfer(feildConfig, form, isHome, login, httpResponse); + return LoginAfter(feildConfig, form, isHome, login, httpResponse); } else { @@ -2491,7 +2556,7 @@ namespace UMC.Proxy httpResponse.ReadAsString(); if (XHR(login, form, feildConfig, "LOGIN", "", out httpResponse)) { - return LoginAtfer(feildConfig, form, isHome, login, httpResponse); + return LoginAfter(feildConfig, form, isHome, login, httpResponse); } else { @@ -2541,7 +2606,7 @@ namespace UMC.Proxy feildConfig = UMC.Data.JSON.Deserialize(this.SiteCookie.Config) ?? new Hashtable(); if (XHR(login, form, feildConfig, "LOGIN", "", out httpResponse)) { - return LoginAtfer(feildConfig, form, isHome, login, httpResponse); + return LoginAfter(feildConfig, form, isHome, login, httpResponse); } else { @@ -2599,7 +2664,7 @@ namespace UMC.Proxy return false; } - bool LoginAtfer(Hashtable fieldConfig, NameValueCollection form, bool isHome, Hashtable loginConfig, NetHttpResponse httpResponse) + bool LoginAfter(Hashtable fieldConfig, NameValueCollection form, bool isHome, Hashtable loginConfig, NetHttpResponse httpResponse) { this.IsChangeUser = true; var configValue = new Hashtable(); @@ -2611,6 +2676,9 @@ namespace UMC.Proxy configValue[fdcem.Key] = fdcem.Value; } } + + var feilds = loginConfig["Feilds"] as Hashtable;//?? new Hashtable(); + switch (this.Site.Site.UserModel) { case Entities.UserModel.Share: @@ -2690,6 +2758,18 @@ namespace UMC.Proxy this.Context.Output.WriteLine("window.top.postMessage(JSON.stringify({ type: 'close', value: 'close' }), '*');"); return true; } + + if (CheckBrowser() == false) + { + return true; + + } + if (feilds?.ContainsKey("LoginAfter") == true) + { + var conf = GetConf($"SITE_MIME_{Site.Root}_LOGIN_LOGINAFTER".ToUpper()); + + GetConfig(conf, this.Match(loginConfig, this.SiteCookie.Account, this.Password, "")); + } var a = this.Authority; var h = this.Host; @@ -2702,11 +2782,6 @@ namespace UMC.Proxy { this.Context.AddHeader("Set-Cookie", Utility.FirstReplace(o, h, a)); } - if (CheckBrowser() == false) - { - return true; - - } var callbackKey = loginConfig["Callback"] as string ?? "callback"; var callback = this.Context.QueryString.Get(callbackKey); if (String.IsNullOrEmpty(callback) == false) @@ -3186,7 +3261,8 @@ namespace UMC.Proxy public void LoginRequest() { - this.Context.ReadAsForm(this.Login); + this.Context.UseSynchronousIO(this.ProcessEnd); + this.Context.ReadAsForm(this.LoginEnd); } void ClearCookie(string domain) { @@ -3250,6 +3326,19 @@ namespace UMC.Proxy this.Cookies = sb.ToString(); } } + void LoginEnd(NameValueCollection form) + { + try + { + Login(form); + } + finally + { + this.Context.OutputFinish(); + } + // this.ProcessEnd(); + } + void Login(NameValueCollection form) { @@ -3267,7 +3356,7 @@ namespace UMC.Proxy { this.Context.Redirect("/UMC.Login/Go" + this.Context.Url.Query); } - this.ProcessEnd(); + return; } var lv = apis[1]; @@ -3314,7 +3403,6 @@ namespace UMC.Proxy case "Input": case "Go": this.Login(true, false, form, lv); - this.ProcessEnd(); return; case "New": var scookies = DataFactory.Instance().Cookies(this.Site.Root, User.Id.Value).OrderBy(r => r.IndexValue).ToList(); @@ -3330,7 +3418,6 @@ namespace UMC.Proxy } this.Cookies = String.Empty; //new CookieContainer(); this.Login(true, false, form, String.Empty); - this.ProcessEnd(); return; default: if (Utility.IntParse(lv, -1) > -1) @@ -3489,38 +3576,7 @@ namespace UMC.Proxy break; case "GET": { - - var IsCache = false; - - string filename = String.Empty; - - if (this.StaticModel >= 0) - { - var pmd5Key = $"{this.Site.Site.Version}{_RootKey}"; - switch (this.StaticModel) - { - case 0: - break; - case 1: - break; - case 2: - pmd5Key = $"{pmd5Key}{this.SiteCookie.Account}"; - break; - default: - pmd5Key = String.Format("{0}_{1}_{2}", this.SiteCookie.Account, UMC.Data.Utility.TimeSpan() / 60 / this.StaticModel, pmd5Key); - break; - } - if (IsTest == false) - { - IsCache = true; - if (this.Context.CheckCache(Site.Root, pmd5Key, out filename)) - { - this.ProcessEnd(); - return; - } - } - } - else if (IsLoginPath(this.Site, this.RawUrl, out var _go)) + if (IsLoginPath(this.Site, this.RawUrl, out var _go)) { if (_go) { @@ -3529,6 +3585,10 @@ namespace UMC.Proxy this.ProcessEnd(); return; } + else + { + Get(getUrl); + } } else { @@ -3543,323 +3603,360 @@ namespace UMC.Proxy SignOutHtml(); this.ProcessEnd(); } - return; } } - this.Context.UseSynchronousIO(this.ProcessEnd); - var webr = this.Reqesut(Context.Transfer(getUrl)); - - webr.Get(httpResponse => - { - var statusCode = Convert.ToInt32(httpResponse.StatusCode); + else + { + Get(getUrl); + } + } + break; + } + } + void Get(Uri getUrl) + { + var IsCache = false; - this.Context.StatusCode = statusCode; - var contentType = httpResponse.ContentType ?? String.Empty; + string filename = String.Empty; - if (String.IsNullOrEmpty(contentType) == false) - { - this.Context.ContentType = contentType; - } - else if (httpResponse.StatusCode == HttpStatusCode.OK) + if (this.StaticModel >= 0) + { + var pmd5Key = $"{this.Site.Site.Version}{_RootKey}"; + switch (this.StaticModel) + { + case 0: + break; + case 1: + break; + case 2: + pmd5Key = $"{pmd5Key}{this.SiteCookie.Account}"; + break; + default: + pmd5Key = String.Format("{0}_{1}_{2}", this.SiteCookie.Account, UMC.Data.Utility.TimeSpan() / 60 / this.StaticModel, pmd5Key); + break; + } + if (IsTest == false) + { + IsCache = true; + if (this.Context.CheckCache(Site.Root, pmd5Key, out filename)) + { + this.ProcessEnd(); + return; + } + } + } + this.Context.UseSynchronousIO(this.ProcessEnd); + var webr = this.Reqesut(Context.Transfer(getUrl)); + + webr.Get(httpResponse => + { + var statusCode = Convert.ToInt32(httpResponse.StatusCode); + + this.Context.StatusCode = statusCode; + var contentType = httpResponse.ContentType ?? String.Empty; + + if (String.IsNullOrEmpty(contentType) == false) + { + this.Context.ContentType = contentType; + } + else if (httpResponse.StatusCode == HttpStatusCode.OK) + { + this.Context.ContentType = Site.ContentType; + } + + var ContentType = contentType.Split(';')[0]; + String jsAppendKey = null; + SiteConfig.ReplaceSetting replaceSetting = null; + WebMeta ImageConfig = null; + int model = 0; + if (String.Equals(ContentType, "text/html", StringComparison.CurrentCultureIgnoreCase)) + { + if (CheckPath(getUrl.AbsolutePath, out jsAppendKey, this.Site.AppendJSConf)) + { + model = 1; + } + if (this.CheckPath(getUrl.AbsolutePath, ContentType, out replaceSetting)) + { + if (replaceSetting.Model != SiteConfig.HostReplaceModel.Input) + { + model = 1; + } + } + + } + else if (CheckPath(getUrl.AbsolutePath, out jsAppendKey, this.Site.AppendJSConf)) + { + model = 2; + } + else if (this.CheckPath(getUrl.AbsolutePath, ContentType, out replaceSetting)) + { + if ((replaceSetting.Model & SiteConfig.HostReplaceModel.Replace) == SiteConfig.HostReplaceModel.Replace) + { + model = 3; + } + } + else if (ContentType.StartsWith("image/") && ContentType.Contains("svg") == false) + { + var ckey = Context.QueryString.Get("umc-image"); + if (String.IsNullOrEmpty(ckey)) + { + CheckPath(getUrl.AbsolutePath, ContentType, out ckey, this.Site.ImagesConf); + } + if (TryImageConfig(this.Site.Root, ckey, out ImageConfig)) + { + var format = ImageConfig["Format"] ?? "Src"; + if (String.Equals(format, "Src") == false) + { + ContentType = "image/" + format; + } + model = 4; + } + } + if (IsCache) + { + if (String.Equals(httpResponse.Headers.Get("Cache-Control"), "no-store")) + { + IsCache = false; + } + } + if (httpResponse.StatusCode == HttpStatusCode.OK && IsCache) + { + switch (model) + { + case 1: + case 2: + case 3: + case 4: { - this.Context.ContentType = Site.ContentType; - } + var tempFile = System.IO.Path.GetTempFileName(); + var etag = Utility.TimeSpan(); + var cacheStream = NetClient.MimeStream(tempFile, ContentType, etag); + Header(httpResponse, false, false); - var ContentType = contentType.Split(';')[0]; - String jsAppendKey = null; - SiteConfig.ReplaceSetting replaceSetting = null; - WebMeta ImageConfig = null; - int model = 0; - if (String.Equals(ContentType, "text/html", StringComparison.CurrentCultureIgnoreCase)) - { - if (CheckPath(getUrl.AbsolutePath, out jsAppendKey, this.Site.AppendJSConf)) + httpResponse.ReadAsStream(content => { - model = 1; - } - if (this.CheckPath(getUrl.AbsolutePath, ContentType, out replaceSetting)) - { - if (replaceSetting.Model != SiteConfig.HostReplaceModel.Input) + content.Position = 0; + + switch (model) { - model = 1; + case 1: + this.OuterHTML(content, replaceSetting, httpResponse.ContentEncoding, cacheStream, false, jsAppendKey); + break; + case 2: + this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, String.Empty), cacheStream); + break; + case 3: + this.OuterReplaceHost(content, httpResponse.ContentEncoding, replaceSetting, cacheStream, false); + break; + case 4: + SiteImage.Convert(content, cacheStream, ImageConfig, filename); + break; } - } + content.Dispose(); + cacheStream.Flush(); + cacheStream.Close(); + UMC.Data.Utility.Move(tempFile, filename); + using (var fileStream = System.IO.File.OpenRead(filename)) + { + this.Context.OutputCache(fileStream); + } + this.Context.OutputFinish(); - } - else if (CheckPath(getUrl.AbsolutePath, out jsAppendKey, this.Site.AppendJSConf)) - { - model = 2; - } - else if (this.CheckPath(getUrl.AbsolutePath, ContentType, out replaceSetting)) - { - if ((replaceSetting.Model & SiteConfig.HostReplaceModel.Replace) == SiteConfig.HostReplaceModel.Replace) + + + }, e => { - model = 3; - } + cacheStream.Close(); + DeleteCache(tempFile); + this.Context.Error(e); + }); } - else if (ContentType.StartsWith("image/") && ContentType.Contains("svg") == false) + break; + default: { - var ckey = Context.QueryString.Get("umc-image"); - if (String.IsNullOrEmpty(ckey)) + var tempFile = File.Open(System.IO.Path.GetTempFileName(), FileMode.Create); + Header(httpResponse, true, false); + var tag = Utility.TimeSpan(); + this.Context.AddHeader("ETag", tag.ToString()); + + if (httpResponse.ContentLength > -1) { - CheckPath(getUrl.AbsolutePath, ContentType, out ckey, this.Site.ImagesConf); + this.Context.ContentLength = httpResponse.ContentLength; } - if (TryImageConfig(this.Site.Root, ckey, out ImageConfig)) + httpResponse.ReadAsData((b, i, c) => { - var format = ImageConfig["Format"] ?? "Src"; - if (String.Equals(format, "Src") == false) + if (c == 0 && b.Length == 0) { - ContentType = "image/" + format; - } - model = 4; - } - } - if (IsCache) - { - if (String.Equals(httpResponse.Headers.Get("Cache-Control"), "no-store")) - { - IsCache = false; - } - } - if (httpResponse.StatusCode == HttpStatusCode.OK && IsCache) - { - switch (model) - { - case 1: - case 2: - case 3: - case 4: - { - var tempFile = System.IO.Path.GetTempFileName(); - var etag = Utility.TimeSpan(); - var cacheStream = NetClient.MimeStream(tempFile, ContentType, etag); - Header(httpResponse, false, false); - - httpResponse.ReadAsStream(content => - { - content.Position = 0; - - switch (model) - { - case 1: - this.OuterHTML(content, replaceSetting, httpResponse.ContentEncoding, cacheStream, false, jsAppendKey); - break; - case 2: - this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, String.Empty), cacheStream); - break; - case 3: - this.OuterReplaceHost(content, httpResponse.ContentEncoding, replaceSetting, cacheStream, false); - break; - case 4: - SiteImage.Convert(content, cacheStream, ImageConfig, filename); - break; - } - content.Dispose(); - cacheStream.Flush(); - cacheStream.Close(); - UMC.Data.Utility.Move(tempFile, filename); - using (var fileStream = System.IO.File.OpenRead(filename)) - { - this.Context.OutputCache(fileStream); - } - this.Context.OutputFinish(); - + if (i == -1) + { + tempFile.Close(); + this.Context.Error(httpResponse.Error); - }, e => - { - cacheStream.Close(); - DeleteCache(tempFile); - this.Context.Error(e); - }); } - break; - default: + else { - var tempFile = File.Open(System.IO.Path.GetTempFileName(), FileMode.Create); - Header(httpResponse, true, false); - var tag = Utility.TimeSpan(); - this.Context.AddHeader("ETag", tag.ToString()); + this.Context.OutputFinish(); + tempFile.Flush(); - if (httpResponse.ContentLength > -1) + tempFile.Position = 0; + using (var tem = DataFactory.Instance().Decompress(tempFile, httpResponse.ContentEncoding)) { - this.Context.ContentLength = httpResponse.ContentLength; + var cacheStream = NetClient.MimeStream(filename, ContentType, tag); + + tem.CopyTo(cacheStream); + tempFile.Close(); + cacheStream.Close(); } - httpResponse.ReadAsData((b, i, c) => - { - if (c == 0 && b.Length == 0) - { - - if (i == -1) - { - tempFile.Close(); - this.Context.Error(httpResponse.Error); - - } - else - { - this.Context.OutputFinish(); - tempFile.Flush(); - - tempFile.Position = 0; - using (var tem = DataFactory.Instance().Decompress(tempFile, httpResponse.ContentEncoding)) - { - var cacheStream = NetClient.MimeStream(filename, ContentType, tag); - - tem.CopyTo(cacheStream); - tempFile.Close(); - cacheStream.Close(); - } - } - } - else - { - tempFile.Write(b, i, c); - this.Context.OutputStream.Write(b, i, c); - } - }); } - break; - } - return; - + } + else + { + tempFile.Write(b, i, c); + this.Context.OutputStream.Write(b, i, c); + } + }); } - else - { - switch (model) - { - case 4: - case 2: - Header(httpResponse, false, false); - httpResponse.ReadAsStream(content => + break; + } + return; + + } + else + { + switch (model) + { + case 4: + case 2: + Header(httpResponse, false, false); + httpResponse.ReadAsStream(content => + { + + content.Position = 0; + switch (model) + { + case 2: + this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, ""), this.Context.OutputStream); + break; + case 4: + + if (ContentType.Contains("Optimal")) { + this.Context.ContentType = "image/webp"; + } + SiteImage.Convert(content, this.Context.OutputStream, ImageConfig, String.Empty); + break; + } + this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, String.Empty), this.Context.OutputStream); - content.Position = 0; - switch (model) - { - case 2: - this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, ""), this.Context.OutputStream); - break; - case 4: + this.Context.OutputFinish(); - if (ContentType.Contains("Optimal")) - { - this.Context.ContentType = "image/webp"; - } - SiteImage.Convert(content, this.Context.OutputStream, ImageConfig, String.Empty); - break; - } - this.OutputAppendJS(content, httpResponse.ContentEncoding, MD5(jsAppendKey, String.Empty), this.Context.OutputStream); + }, this.Context.Error); + break; + case 1: + case 3: - this.Context.OutputFinish(); + Header(httpResponse, false, false); + if (String.IsNullOrEmpty(httpResponse.ContentEncoding)) + { + var stream = new DeflateStream(this.Context.OutputStream, CompressionMode.Compress); - }, this.Context.Error); - break; - case 1: - case 3: + this.Context.AddHeader("Content-Encoding", "deflate"); + var replacer = new Replacer(this, stream.Write, replaceSetting, 1, 0, 0, jsAppendKey); - Header(httpResponse, false, false); - if (String.IsNullOrEmpty(httpResponse.ContentEncoding)) + httpResponse.ReadAsData((b, i, c) => + { + if (c == 0 && b.Length == 0) + { + if (i == -1) { - var stream = new DeflateStream(this.Context.OutputStream, CompressionMode.Compress); - - this.Context.AddHeader("Content-Encoding", "deflate"); - var replacer = new Replacer(this, stream.Write, replaceSetting, 1, 0, 0, jsAppendKey); - - httpResponse.ReadAsData((b, i, c) => - { - if (c == 0 && b.Length == 0) - { - if (i == -1) - { - this.Context.Error(httpResponse.Error); - } - else - { - replacer.Flush(); - stream.Flush(); - this.Context.OutputFinish(); - } - } - else - { - replacer.Replace((buffer, offset, size) => - { - if (c < size) - { - size = c; - } - - Array.Copy(b, i, buffer, offset, size); - i += size; - c -= size; - return size; - }); - } - }); + this.Context.Error(httpResponse.Error); } else { - httpResponse.ReadAsStream(content => - { - content.Position = 0; - - switch (model) - { - case 1: - this.OuterHTML(content, replaceSetting, httpResponse.ContentEncoding, this.Context.OutputStream, true, jsAppendKey); - break; - case 3: - this.OuterReplaceHost(content, httpResponse.ContentEncoding, replaceSetting, this.Context.OutputStream, true); - break; - } - this.Context.OutputFinish(); - - }, this.Context.Error); + replacer.Flush(); + stream.Flush(); + this.Context.OutputFinish(); } + } + else + { + replacer.Replace((buffer, offset, size) => + { + if (c < size) + { + size = c; + } - return; - default: - Header(httpResponse); - break; - - } - } - - if (httpResponse.ContentLength > -1) - { - this.Context.ContentLength = httpResponse.ContentLength; + Array.Copy(b, i, buffer, offset, size); + i += size; + c -= size; + return size; + }); + } + }); } - httpResponse.ReadAsData((b, i, c) => + else { - if (c == 0 && b.Length == 0) + httpResponse.ReadAsStream(content => { - if (i == -1) - { - this.Context.Error(httpResponse.Error); - } - else + content.Position = 0; + + switch (model) { - this.Context.OutputFinish(); + case 1: + this.OuterHTML(content, replaceSetting, httpResponse.ContentEncoding, this.Context.OutputStream, true, jsAppendKey); + break; + case 3: + this.OuterReplaceHost(content, httpResponse.ContentEncoding, replaceSetting, this.Context.OutputStream, true); + break; } - } - else - { - this.Context.OutputStream.Write(b, i, c); - } - }); - }); + this.Context.OutputFinish(); - if (this.IsLog == true) - { - this.Loger.Write(this.Context.HttpMethod); - this.Loger.Write(":"); - this.Loger.WriteLine(getUrl.PathAndQuery); - this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr.Headers.ToByteArray())); + }, this.Context.Error); + } + + return; + default: + Header(httpResponse); + break; + + } + } + + if (httpResponse.ContentLength > -1) + { + this.Context.ContentLength = httpResponse.ContentLength; + } + httpResponse.ReadAsData((b, i, c) => + { + if (c == 0 && b.Length == 0) + { + if (i == -1) + { + this.Context.Error(httpResponse.Error); + } + else + { + this.Context.OutputFinish(); + } + } + else + { + this.Context.OutputStream.Write(b, i, c); + } + }); + }); + + if (this.IsLog == true) + { + this.Loger.Write(this.Context.HttpMethod); + this.Loger.Write(":"); + this.Loger.WriteLine(getUrl.PathAndQuery); + this.Loger.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(webr.Headers.ToByteArray())); - } - } - break; } + } bool CheckBrowser() { @@ -3999,13 +4096,13 @@ namespace UMC.Proxy switch (path[path.Length - 1]) { case '$': - if (rawUrl.EndsWith(path, 1, path.Length - 1)) + if (rawUrl.EndsWith(path, 0, path.Length - 1)) { return true; } break; case '*': - if (rawUrl.StartsWith(path, 1, path.Length - 1)) + if (rawUrl.StartsWith(path, 0, path.Length - 1)) { return true; } @@ -4065,7 +4162,7 @@ namespace UMC.Proxy { WebServlet.WebHeaderConf(webr, this.Site, this.Context, this.SiteCookie.Account); } - webr.ReadWriteTimeout = (this.Site.Site.Timeout ?? 100) * 1000; + webr.Timeout = (this.Site.Site.Timeout ?? 100) * 1000; return webr; } diff --git a/Proxy/SiteAppActivity.cs b/Proxy/SiteAppActivity.cs index f64c3cd..0df8a54 100644 --- a/Proxy/SiteAppActivity.cs +++ b/Proxy/SiteAppActivity.cs @@ -6,7 +6,6 @@ using UMC.Data.Entities; using UMC.Proxy.Entities; using System.IO; using UMC.Data; -using System.Text.RegularExpressions; namespace UMC.Proxy.Activities { @@ -69,7 +68,7 @@ namespace UMC.Proxy.Activities sts.Rows.Add("发布新应用", "Add", "javascript:void(0)", "/css/images/icon/add.png", "max", "", true); - + } var keys = new List(); @@ -132,9 +131,28 @@ namespace UMC.Proxy.Activities } } + var IsAuth = false; + switch (d.AuthType ?? Web.WebAuthType.User) + { + case Web.WebAuthType.Admin: + if (user.IsInRole(UMC.Security.Membership.AdminRole)) + { + IsAuth = true; + } + else if (UMC.Data.DataFactory.Instance().Roles(user.Id.Value, d.SiteKey.Value).Contains(UMC.Security.Membership.AdminRole)) + { + IsAuth = true; + } + break; + default: + IsAuth = true; + break; + } - - sts.Rows.Add(title.Trim(), d.Root, strUrl, webr.ImageResolve(d.Root, "1", 4, $"_t={d.ModifyTime}"), target, badge, isDesktop); + if (IsAuth) + { + sts.Rows.Add(title.Trim(), d.Root, strUrl, webr.ImageResolve(d.Root, "1", 4, $"_t={d.ModifyTime}"), target, badge, isDesktop); + } } } if (String.IsNullOrEmpty(UMC.Data.WebResource.Instance().Provider["appId"])) diff --git a/Proxy/SiteConfig.cs b/Proxy/SiteConfig.cs index 3b9c110..b64cf0f 100644 --- a/Proxy/SiteConfig.cs +++ b/Proxy/SiteConfig.cs @@ -516,14 +516,17 @@ namespace UMC.Proxy { var mv = v.Substring(nindex + 1).Trim(); var key = v.Substring(0, nindex).Trim(); - switch (key.ToLower()) + if (String.IsNullOrEmpty(mv) == false && String.IsNullOrEmpty(key) == false) { - case "content-type": - this.ContentType = mv; - break; - default: - _HeaderConf[key] = mv; - break; + switch (key.ToLower()) + { + case "content-type": + this.ContentType = mv; + break; + default: + _HeaderConf[key] = mv; + break; + } } } diff --git a/Proxy/SiteMimeActivity.cs b/Proxy/SiteMimeActivity.cs index 630ba2c..8f0ee16 100644 --- a/Proxy/SiteMimeActivity.cs +++ b/Proxy/SiteMimeActivity.cs @@ -1,4 +1,5 @@ -using System; +using System.Reflection.Emit; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -82,6 +83,13 @@ namespace UMC.Proxy.Activities } } + var ks = Key.Split('_'); + + var typeKey = String.Empty; + if (ks.Length == 2) + { + typeKey = ks[1].ToUpper(); + } var Model = this.AsyncDialog("Model", g => { @@ -93,18 +101,17 @@ namespace UMC.Proxy.Activities var ui = UISection.Create(title); - if (mainKey.EndsWith("_LOGIN")) - { - title.Title = "登录接口"; - } - else if (mainKey.EndsWith("_UPDATE")) + switch (typeKey) { - title.Title = "密码托管接口"; - } - else if (mainKey.EndsWith("_CHECK")) - { - title.Title = "账户检测接口"; - + case "LOGIN": + title.Title = "登录接口"; + break; + case "UPDATE": + title.Title = "密码托管接口"; + break; + case "CHECK": + title.Title = "账户检测接口"; + break; } var Method = value["Method"] as string; @@ -155,126 +162,134 @@ namespace UMC.Proxy.Activities var content = value["Content"] as string; ui.NewSection().AddCell("提交内容", String.IsNullOrEmpty(content) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Content")).Post(request.Model, request.Command)); - } - else if (mainKey.EndsWith("_LOGIN") == false && mainKey.EndsWith("_UPDATE") == false && mainKey.EndsWith("_CHECK") == false) - { - var content = value["Content"] as string; + // } + // else if (mainKey.EndsWith("_LOGIN") == false && mainKey.EndsWith("_UPDATE") == false && mainKey.EndsWith("_CHECK") == false) + // { + // var content = value["Content"] as string; - ui.NewSection().AddCell("脚本环境", String.IsNullOrEmpty(content) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Content")).Post(request.Model, request.Command)); + // ui.NewSection().AddCell("脚本环境", String.IsNullOrEmpty(content) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Content")).Post(request.Model, request.Command)); } - - if (mainKey.EndsWith("_LOGIN") || mainKey.EndsWith("_UPDATE") || mainKey.EndsWith("_CHECK")) + switch (typeKey) { - var Finish = value["Finish"] as string; - var root = Key.Substring(0, Key.LastIndexOf('_')); + case "LOGIN": + case "UPDATE": + case "CHECK": + var Finish = value["Finish"] as string; + var root = Key.Substring(0, Key.LastIndexOf('_')); - ui.NewSection().AddCell("检测格式", String.IsNullOrEmpty(Finish) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Finish")).Post(request.Model, request.Command)); + ui.NewSection().AddCell("检测格式", String.IsNullOrEmpty(Finish) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Finish")).Post(request.Model, request.Command)); - var fui = ui.NewSection(); - fui.AddCell("扩展字段", "新增", new UIClick(new WebMeta(request.Arguments).Put(g, "Feilds")).Post(request.Model, request.Command)); - var feilds = value["Feilds"] as Hashtable; - if (feilds != null && feilds.Count > 0) - { - var fd = feilds.Keys.Cast().OrderBy(r => r).GetEnumerator(); - - while (fd.MoveNext()) + var fui = ui.NewSection(); + fui.AddCell("扩展字段", "新增", new UIClick(new WebMeta(request.Arguments).Put(g, "Feilds")).Post(request.Model, request.Command)); + var feilds = value["Feilds"] as Hashtable; + if (feilds != null && feilds.Count > 0) { - var cell = new WebMeta().Put("value", fd.Current).Put("text", feilds[fd.Current]); + var fd = feilds.Keys.Cast().OrderBy(r => r).GetEnumerator(); - cell.Put("click", new UIClick(new WebMeta().Put("Key", Key + "_" + fd.Current)).Post(request.Model, request.Command)); + while (fd.MoveNext()) + { + var cell = new WebMeta().Put("value", fd.Current).Put("text", feilds[fd.Current]); + cell.Put("click", new UIClick(new WebMeta().Put("Key", Key + "_" + fd.Current)).Post(request.Model, request.Command)); + var uICell = UICell.Create("Cell", cell); + if (fd.Current == "LoginAfter") + { + uICell.Style.Name("value").Color(0xff4949); + // uICell.Style.Name("text").Color(0xff4949); + } + fui.Delete(uICell, new UIEventText("移除").Click(new UIClick(new WebMeta(request.Arguments).Put(g, fd.Current)).Post(request.Model, request.Command))); - fui.Delete(UICell.Create("Cell", cell), new UIEventText("移除").Click(new UIClick(new WebMeta(request.Arguments).Put(g, fd.Current)).Post(request.Model, request.Command))); + } } - - } - if (mainKey.EndsWith("_LOGIN")) - { - - ui.NewSection().AddCell("登录清空会话", value.ContainsKey("IsNotCookieClear") ? "不清空" : "清空", new UIClick(new WebMeta(request.Arguments).Put(g, "IsNotCookieClear")).Post(request.Model, request.Command)); - - - if (value.ContainsKey("IsLoginHTML")) + switch (typeKey) { + case "LOGIN": + { + ui.NewSection().AddCell("登录清空会话", value.ContainsKey("IsNotCookieClear") ? "不清空" : "清空", new UIClick(new WebMeta(request.Arguments).Put(g, "IsNotCookieClear")).Post(request.Model, request.Command)); - ui.NewSection() - .AddCell("内容转化配置", new UIClick(new WebMeta(request.Arguments).Put(g, "Script")).Post(request.Model, request.Command)) - .NewSection().AddCell("前端页面登录", "已启用", new UIClick(new WebMeta(request.Arguments).Put(g, "IsLoginHTML")).Post(request.Model, request.Command)) - .AddCell("前端页面内容配置", new UIClick(String.Format("{0}_HTML", mainKey).ToUpper()).Post(request.Model, "Conf")); + if (value.ContainsKey("IsLoginHTML")) + { + ui.NewSection() + .AddCell("内容转化配置", new UIClick(new WebMeta(request.Arguments).Put(g, "Script")).Post(request.Model, request.Command)) + .NewSection().AddCell("前端页面登录", "已启用", new UIClick(new WebMeta(request.Arguments).Put(g, "IsLoginHTML")).Post(request.Model, request.Command)) - } - else - { - ui.NewSection().AddCell("前端页面登录", "未启用", new UIClick(new WebMeta(request.Arguments).Put(g, "IsLoginHTML")).Post(request.Model, request.Command)); - } + .AddCell("前端页面内容配置", new UIClick(String.Format("{0}_HTML", mainKey).ToUpper()).Post(request.Model, "Conf")); - var Callback = value["Callback"] as string; - ui.NewSection().AddCell("跳转参数", String.IsNullOrEmpty(Callback) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Callback")).Post(request.Model, request.Command)); + } + else + { + ui.NewSection().AddCell("前端页面登录", "未启用", new UIClick(new WebMeta(request.Arguments).Put(g, "IsLoginHTML")).Post(request.Model, request.Command)); + } - } - else if (mainKey.EndsWith("_UPDATE")) - { - var UpdateModel = value["UpdateModel"] as String ?? "Selected"; - switch (UpdateModel) - { - case "Selected": - UpdateModel = "默认选中"; - break; - case "Select": - UpdateModel = "默认不选中"; - break; - case "Compel": - UpdateModel = "强制托管"; - break; - case "Disable": - UpdateModel = "禁用托管"; - break; + var Callback = value["Callback"] as string; + ui.NewSection().AddCell("跳转参数", String.IsNullOrEmpty(Callback) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "Callback")).Post(request.Model, request.Command)); - } - ui.NewSection().AddCell("密码托管模式", UpdateModel, new UIClick(new WebMeta(request.Arguments).Put(g, "UpdateModel")).Post(request.Model, request.Command)); + } + break; + case "UPDATE": + { + var UpdateModel = value["UpdateModel"] as String ?? "Selected"; + switch (UpdateModel) + { + case "Selected": + UpdateModel = "默认选中"; + break; + case "Select": + UpdateModel = "默认不选中"; + break; + case "Compel": + UpdateModel = "强制托管"; + break; + case "Disable": + UpdateModel = "禁用托管"; + break; - } - else if (mainKey.EndsWith("_CHECK")) - { - var site = DataFactory.Instance().Site(root.ToLower()); - if (site != null) - { - var userM = "未启用"; - switch (site.UserModel ?? UserModel.Standard) - { - case UserModel.Check: - userM = "自主选择"; - break; - case UserModel.Checked: - userM = "自动检测"; - break; + } + ui.NewSection().AddCell("密码托管模式", UpdateModel, new UIClick(new WebMeta(request.Arguments).Put(g, "UpdateModel")).Post(request.Model, request.Command)); - } - ui.NewSection() - .AddCell("功能启用", userM, new UIClick(new WebMeta(request.Arguments).Put(g, "UserModel")).Post(request.Model, request.Command)) - .AddCell("检测账户", String.IsNullOrEmpty(site.Account) ? "未设置" : site.Account, new UIClick("Key", site.Root, "Model", "Account").Post(request.Model, "Site")) - .AddCell("检测登录", value.ContainsKey("IsNotLoginApi") ? "不是" : "是", new UIClick(new WebMeta(request.Arguments).Put(g, "IsNotLoginApi")).Post(request.Model, request.Command)); + } + break; + case "CHECK": + { + var site = DataFactory.Instance().Site(root.ToLower()); + if (site != null) + { + var userM = "未启用"; + switch (site.UserModel ?? UserModel.Standard) + { + case UserModel.Check: + userM = "自主选择"; + break; + case UserModel.Checked: + userM = "自动检测"; + break; + + } + ui.NewSection() + .AddCell("功能启用", userM, new UIClick(new WebMeta(request.Arguments).Put(g, "UserModel")).Post(request.Model, request.Command)) + .AddCell("检测账户", String.IsNullOrEmpty(site.Account) ? "未设置" : site.Account, new UIClick("Key", site.Root, "Model", "Account").Post(request.Model, "Site")) + .AddCell("检测登录", value.ContainsKey("IsNotLoginApi") ? "不是" : "是", new UIClick(new WebMeta(request.Arguments).Put(g, "IsNotLoginApi")).Post(request.Model, request.Command)); + } + } + break; } + break; + default: + ui.NewSection().AddCell("内容转化配置", new UIClick(new WebMeta(request.Arguments).Put(g, "Script")).Post(request.Model, request.Command)); - } - } - else - { - ui.NewSection().AddCell("内容转化配置", new UIClick(new WebMeta(request.Arguments).Put(g, "Script")).Post(request.Model, request.Command)); - - - ui.NewSection().AddCell("记住选择内容", value.ContainsKey("RememberValue") ? "记住" : "不记住", new UIClick(new WebMeta(request.Arguments).Put(g, "RememberValue")).Post(request.Model, request.Command)); - var defautValue = value["DefautValue"] as string; - ui.NewSection().AddCell("内容默认值", String.IsNullOrEmpty(defautValue) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "DefautValue")).Post(request.Model, request.Command)); + ui.NewSection().AddCell("记住选择内容", value.ContainsKey("RememberValue") ? "记住" : "不记住", new UIClick(new WebMeta(request.Arguments).Put(g, "RememberValue")).Post(request.Model, request.Command)); + var defautValue = value["DefautValue"] as string; + ui.NewSection().AddCell("内容默认值", String.IsNullOrEmpty(defautValue) ? "未设置" : "已设置", new UIClick(new WebMeta(request.Arguments).Put(g, "DefautValue")).Post(request.Model, request.Command)); + break; } @@ -329,6 +344,7 @@ namespace UMC.Proxy.Activities from4.AddText("字段标题", "Value", ""); from4.AddText("字段标识", "Name", ""); from4.Submit("确认", "Mime.Config"); + from4.AddFooter("当标识为“LoginAfter”,表示登录之后请求的网络配置"); return from4; }); var feilds = value["Feilds"] as Hashtable ?? new Hashtable();