From f65e4f1900829b835ba1c5c804e0d1a66e1df896 Mon Sep 17 00:00:00 2001 From: PopSlime Date: Tue, 4 Jul 2023 11:12:27 +0800 Subject: [PATCH] Cleanup network module. --- Assets/Cryville/Common/Network/Http11.meta | 8 +++ .../{HttpClient.cs => Http11/Http11Client.cs} | 69 ++++++++----------- .../Http11Client.cs.meta} | 5 +- .../Http11Response.cs} | 20 +++--- .../Http11Response.cs.meta} | 5 +- .../Http11ResponseStream.cs} | 22 +++--- .../Http11ResponseStream.cs.meta} | 5 +- .../Https11Client.cs} | 6 +- .../Https11Client.cs.meta} | 5 +- Assets/Cryville/Common/Network/TlsClient.cs | 15 ---- Assets/Cryville/Crtr/Console.cs | 6 +- Assets/Cryville/Crtr/Network/UpdateChecker.cs | 4 +- 12 files changed, 71 insertions(+), 99 deletions(-) create mode 100644 Assets/Cryville/Common/Network/Http11.meta rename Assets/Cryville/Common/Network/{HttpClient.cs => Http11/Http11Client.cs} (70%) rename Assets/Cryville/Common/Network/{HttpResponseStream.cs.meta => Http11/Http11Client.cs.meta} (69%) rename Assets/Cryville/Common/Network/{HttpResponse.cs => Http11/Http11Response.cs} (73%) rename Assets/Cryville/Common/Network/{HttpClient.cs.meta => Http11/Http11Response.cs.meta} (69%) rename Assets/Cryville/Common/Network/{HttpResponseStream.cs => Http11/Http11ResponseStream.cs} (79%) rename Assets/Cryville/Common/Network/{HttpsClient.cs.meta => Http11/Http11ResponseStream.cs.meta} (69%) rename Assets/Cryville/Common/Network/{HttpsClient.cs => Http11/Https11Client.cs} (76%) rename Assets/Cryville/Common/Network/{HttpResponse.cs.meta => Http11/Https11Client.cs.meta} (69%) diff --git a/Assets/Cryville/Common/Network/Http11.meta b/Assets/Cryville/Common/Network/Http11.meta new file mode 100644 index 0000000..d8ed674 --- /dev/null +++ b/Assets/Cryville/Common/Network/Http11.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1a624371d4108614b9cdc4acca1499e2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Cryville/Common/Network/HttpClient.cs b/Assets/Cryville/Common/Network/Http11/Http11Client.cs similarity index 70% rename from Assets/Cryville/Common/Network/HttpClient.cs rename to Assets/Cryville/Common/Network/Http11/Http11Client.cs index 3f4dc67..74228ef 100644 --- a/Assets/Cryville/Common/Network/HttpClient.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11Client.cs @@ -4,12 +4,11 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Linq; using System.Net.Sockets; using System.Text; -namespace Cryville.Common.Network { - public class HttpClient { +namespace Cryville.Common.Network.Http11 { + public class Http11Client { private readonly string _directHost; protected string DirectHost { get { return _directHost; } } @@ -19,29 +18,17 @@ namespace Cryville.Common.Network { readonly Uri _baseUri; readonly int origPort; - protected string Version = "HTTP/1.1"; + protected const string Version = "HTTP/1.1"; protected TcpClient TcpClient { get; private set; } - protected Stream RawTcpStream { - get { - return TcpClient.GetStream(); - } - } - protected virtual Stream Stream { - get { - return TcpClient.GetStream(); - } - } - protected virtual string WindowsProxyProtocolName { - get { - return "http"; - } - } + protected Stream RawTcpStream { get { return TcpClient.GetStream(); } } + protected virtual Stream Stream { get { return TcpClient.GetStream(); } } + protected virtual string WindowsProxyProtocolName { get { return "http"; } } private readonly bool _proxied = false; public Dictionary Headers { get; set; } - public HttpClient(Uri baseUri, int port = 80) { + public Http11Client(Uri baseUri, int port = 80) { _directHost = baseUri.Host; _directPort = port; _baseUri = baseUri; @@ -62,17 +49,17 @@ namespace Cryville.Common.Network { TcpClient.Close(); } - public HttpResponse Request(string method, Uri uri, string body = null, Encoding encoding = null) { + public Http11Response Request(string method, Uri uri, string body = null, Encoding encoding = null) { string struri = GetUri(uri).PathAndQuery; return Request(Stream, method, struri, body, encoding); } - public HttpResponse Request(Stream stream, string method, string uri, string body = null, Encoding encoding = null) { - var headers = new Dictionary(); + public Http11Response Request(Stream stream, string method, string uri, string body = null, Encoding encoding = null) { + var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var h in Headers) headers.Add(h.Key, h.Value); headers["Host"] = _baseUri.Host; - byte[] payload = new byte[0]; + byte[] payload = null; if (body != null) { if (encoding == null) encoding = Encoding.UTF8; @@ -80,22 +67,24 @@ namespace Cryville.Common.Network { headers.Add("Content-Encoding", encoding.EncodingName); headers.Add("Content-Length", payload.Length.ToString(CultureInfo.InvariantCulture)); } - string request_line = string.Format( - "{0} {1} {2}\r\n", method, uri, Version - ); - string header_fields = string.Concat(( - from h in headers select h.Key + ":" + h.Value + "\r\n" - ).ToArray()); - byte[] buffer0 = Encoding.ASCII.GetBytes(string.Format( - "{0}{1}\r\n", request_line, header_fields - )); - byte[] buffer1 = new byte[buffer0.Length + payload.Length]; - Array.Copy(buffer0, buffer1, buffer0.Length); - Array.Copy(payload, 0, buffer1, buffer0.Length, payload.Length); - Logger.Log("main", 0, "Network", Encoding.UTF8.GetString(buffer1)); - stream.Write(buffer1, 0, buffer1.Length); - stream.Flush(); - var response = new HttpResponse(stream); + using (var writer = new StreamWriter(stream, Encoding.ASCII, 1024, true)) { + writer.Write(method); + writer.Write(' '); + writer.Write(uri); + writer.Write(' '); + writer.Write(Version); + writer.Write("\r\n"); + foreach (var header in headers) { + writer.Write(header.Key); + writer.Write(':'); + writer.Write(header.Value); + writer.Write("\r\n"); + } + writer.Write("\r\n"); + if (payload != null) writer.Write(payload); + writer.Flush(); + } + var response = new Http11Response(stream); Logger.Log("main", 0, "Network", "{0}", response); return response; } diff --git a/Assets/Cryville/Common/Network/HttpResponseStream.cs.meta b/Assets/Cryville/Common/Network/Http11/Http11Client.cs.meta similarity index 69% rename from Assets/Cryville/Common/Network/HttpResponseStream.cs.meta rename to Assets/Cryville/Common/Network/Http11/Http11Client.cs.meta index ee4deb4..d88686b 100644 --- a/Assets/Cryville/Common/Network/HttpResponseStream.cs.meta +++ b/Assets/Cryville/Common/Network/Http11/Http11Client.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: f191de447a708da4f9d230e6545ce0a6 -timeCreated: 1635470462 -licenseType: Free +guid: 5a795e416e54c69418de1a3c27a88932 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Assets/Cryville/Common/Network/HttpResponse.cs b/Assets/Cryville/Common/Network/Http11/Http11Response.cs similarity index 73% rename from Assets/Cryville/Common/Network/HttpResponse.cs rename to Assets/Cryville/Common/Network/Http11/Http11Response.cs index ae74ce9..c049e9f 100644 --- a/Assets/Cryville/Common/Network/HttpResponse.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11Response.cs @@ -1,31 +1,30 @@ -using Cryville.Common.Logging; +using System; using System.Collections.Generic; using System.IO; using System.Text; -namespace Cryville.Common.Network { - public class HttpResponse { +namespace Cryville.Common.Network.Http11 { + public class Http11Response { static readonly char[] spchar = new char[]{ ' ' }; public string HttpVersion { get; private set; } public string StatusCode { get; private set; } public string ReasonPhase { get; private set; } public Dictionary Headers { get; private set; } - public HttpResponseStream MessageBody { get; private set; } - internal HttpResponse(Stream stream) { + public Http11ResponseStream MessageBody { get; private set; } + internal Http11Response(Stream stream) { var reader = new BinaryReader(stream, Encoding.ASCII); var statu_line = ReadLine(reader).Split(spchar, 3); HttpVersion = statu_line[0]; StatusCode = statu_line[1]; ReasonPhase = statu_line[2]; - Logger.Log("main", 0, "Network", "Receive Response: {0} {1} {2}", HttpVersion, StatusCode, ReasonPhase); - Headers = new Dictionary(); + Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); while (ParseHeader(reader, Headers)) ; if (Headers.ContainsKey("content-length")) { int length = int.Parse(Headers["content-length"]); - MessageBody = new HttpResponseBlockStream(reader, length); + MessageBody = new Http11ResponseBlockStream(reader, length); } else if (Headers.ContainsKey("transfer-encoding") && Headers["transfer-encoding"] == "chunked") { - MessageBody = new HttpResponseChunkedStream(reader); + MessageBody = new Http11ResponseChunkedStream(reader); } } @@ -37,12 +36,11 @@ namespace Cryville.Common.Network { // TODO Multiline header var header = ReadLine(reader); if (header == "") return false; - var s = header.Split(':'); + var s = header.Split(':', 2); string field_name = s[0].Trim().ToLower(); string field_value = s[1].Trim(); if (headers.ContainsKey(field_name)) headers[field_name] += "," + field_value; else headers.Add(field_name, field_value); - Logger.Log("main", 0, "Network", "Receive Header {0}: {1}", field_name, field_value); return true; } diff --git a/Assets/Cryville/Common/Network/HttpClient.cs.meta b/Assets/Cryville/Common/Network/Http11/Http11Response.cs.meta similarity index 69% rename from Assets/Cryville/Common/Network/HttpClient.cs.meta rename to Assets/Cryville/Common/Network/Http11/Http11Response.cs.meta index 0b11648..dd03744 100644 --- a/Assets/Cryville/Common/Network/HttpClient.cs.meta +++ b/Assets/Cryville/Common/Network/Http11/Http11Response.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 5ea931bf5488011468f3d1243a038874 -timeCreated: 1622589817 -licenseType: Free +guid: 71234dd1c93d47b4893750686b2333a3 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Assets/Cryville/Common/Network/HttpResponseStream.cs b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs similarity index 79% rename from Assets/Cryville/Common/Network/HttpResponseStream.cs rename to Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs index c453d5e..b4cb956 100644 --- a/Assets/Cryville/Common/Network/HttpResponseStream.cs +++ b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs @@ -1,12 +1,11 @@ -using Cryville.Common.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -namespace Cryville.Common.Network { - public abstract class HttpResponseStream : Stream { +namespace Cryville.Common.Network.Http11 { + public abstract class Http11ResponseStream : Stream { public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } @@ -37,11 +36,11 @@ namespace Cryville.Common.Network { } } - internal sealed class HttpResponseBlockStream : HttpResponseStream { + internal sealed class Http11ResponseBlockStream : Http11ResponseStream { readonly BinaryReader _reader; readonly int _length; int _pos = 0; - internal HttpResponseBlockStream(BinaryReader reader, int length) { + internal Http11ResponseBlockStream(BinaryReader reader, int length) { _reader = reader; _length = length; } @@ -51,7 +50,6 @@ namespace Cryville.Common.Network { if (recv_len == 0) return 0; while (recv < recv_len) { recv += _reader.Read(buffer, offset + recv, count - recv); - Logger.Log("main", 0, "Network", "Message body received: {0}/{1}/{2}", recv, recv_len, _length); } _pos += recv_len; return recv_len; @@ -63,18 +61,17 @@ namespace Cryville.Common.Network { } } - internal sealed class HttpResponseChunkedStream : HttpResponseStream { + internal sealed class Http11ResponseChunkedStream : Http11ResponseStream { readonly BinaryReader _reader; byte[] _chunk = null; int _pos = 0; - internal HttpResponseChunkedStream(BinaryReader reader) { + internal Http11ResponseChunkedStream(BinaryReader reader) { _reader = reader; ReadChunk(); } public void ReadChunk() { if (_chunk != null && _chunk.Length == 0) return; - string[] chunkHeader = HttpResponse.ReadLine(_reader).Split(';'); - // int chunkSize = Array.IndexOf(LEN, chunkHeader[0].ToLower()[0]); + string[] chunkHeader = Http11Response.ReadLine(_reader).Split(';'); int chunkSize = int.Parse(chunkHeader[0], NumberStyles.HexNumber); if (chunkSize == -1) throw new IOException("Corrupted chunk received"); @@ -82,17 +79,16 @@ namespace Cryville.Common.Network { _chunk = new byte[0]; // TODO TE Header, now just discard var headers = new Dictionary(); - while (HttpResponse.ParseHeader(_reader, headers)) ; + while (Http11Response.ParseHeader(_reader, headers)) ; return; } _chunk = new byte[chunkSize]; int recv = 0; while (recv < chunkSize) { recv += _reader.Read(_chunk, recv, chunkSize - recv); - Logger.Log("main", 0, "Network", "Message chunk received: {0}/{1}", recv, chunkSize); } _pos = 0; - if (HttpResponse.ReadLine(_reader) != "") + if (Http11Response.ReadLine(_reader) != "") throw new IOException("Corrupted chunk received"); } public override int Read(byte[] buffer, int offset, int count) { diff --git a/Assets/Cryville/Common/Network/HttpsClient.cs.meta b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs.meta similarity index 69% rename from Assets/Cryville/Common/Network/HttpsClient.cs.meta rename to Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs.meta index 37b119e..d1bb4c6 100644 --- a/Assets/Cryville/Common/Network/HttpsClient.cs.meta +++ b/Assets/Cryville/Common/Network/Http11/Http11ResponseStream.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 9b35290e0e147a342acc29a20c8fceaf -timeCreated: 1622503538 -licenseType: Free +guid: 49a8d5b9869e5bb42bafbe71f84fecc5 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Assets/Cryville/Common/Network/HttpsClient.cs b/Assets/Cryville/Common/Network/Http11/Https11Client.cs similarity index 76% rename from Assets/Cryville/Common/Network/HttpsClient.cs rename to Assets/Cryville/Common/Network/Http11/Https11Client.cs index 35f6010..864462f 100644 --- a/Assets/Cryville/Common/Network/HttpsClient.cs +++ b/Assets/Cryville/Common/Network/Http11/Https11Client.cs @@ -1,8 +1,8 @@ using System; using System.IO; -namespace Cryville.Common.Network { - public class HttpsClient : HttpClient { +namespace Cryville.Common.Network.Http11 { + public class Https11Client : Http11Client { readonly TlsClient _tlsClient; protected override Stream Stream { @@ -16,7 +16,7 @@ namespace Cryville.Common.Network { } } - public HttpsClient(Uri baseUri) : base(baseUri, 443) { + public Https11Client(Uri baseUri) : base(baseUri, 443) { _tlsClient = new TlsClient(RawTcpStream, baseUri.Host); } diff --git a/Assets/Cryville/Common/Network/HttpResponse.cs.meta b/Assets/Cryville/Common/Network/Http11/Https11Client.cs.meta similarity index 69% rename from Assets/Cryville/Common/Network/HttpResponse.cs.meta rename to Assets/Cryville/Common/Network/Http11/Https11Client.cs.meta index 672fcee..df743c1 100644 --- a/Assets/Cryville/Common/Network/HttpResponse.cs.meta +++ b/Assets/Cryville/Common/Network/Http11/Https11Client.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 07e8215a93e3eb1418685009f0c58dcd -timeCreated: 1622596274 -licenseType: Free +guid: c5c233e6228ce204fa1a9724c48ac8fe MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Assets/Cryville/Common/Network/TlsClient.cs b/Assets/Cryville/Common/Network/TlsClient.cs index 4bae190..40241ff 100644 --- a/Assets/Cryville/Common/Network/TlsClient.cs +++ b/Assets/Cryville/Common/Network/TlsClient.cs @@ -1,4 +1,3 @@ -using Cryville.Common.Logging; using Org.BouncyCastle.Security; using Org.BouncyCastle.Tls; using Org.BouncyCastle.Tls.Crypto; @@ -72,20 +71,6 @@ namespace Cryville.Common.Network { public override TlsAuthentication GetAuthentication() { return new NullTlsAuthentication(); } - - public override void NotifyAlertReceived(short alertLevel, short alertDescription) { - Logger.Log("main", 0, "Network/TLS", "TLS Alert {0} {1}", alertLevel, alertDescription); - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) { - base.NotifyServerVersion(serverVersion); - Logger.Log("main", 0, "Network/TLS", "NotifyServerVersion {0}", serverVersion); - } - - public override void NotifySelectedCipherSuite(int selectedCipherSuite) { - base.NotifySelectedCipherSuite(selectedCipherSuite); - Logger.Log("main", 0, "Network/TLS", "NotifySelectedCipherSuite {0}", selectedCipherSuite); - } } private class NullTlsAuthentication : TlsAuthentication { diff --git a/Assets/Cryville/Crtr/Console.cs b/Assets/Cryville/Crtr/Console.cs index a4d2d4f..5b8eb7b 100644 --- a/Assets/Cryville/Crtr/Console.cs +++ b/Assets/Cryville/Crtr/Console.cs @@ -1,4 +1,4 @@ -using Cryville.Common.Network; +using Cryville.Common.Network.Http11; using System; using System.Collections.Generic; using System.Threading; @@ -123,13 +123,13 @@ namespace Cryville.Crtr { try { switch (p[0]) { case "!http": - var httpcl = new HttpClient(new Uri(p[1])); + var httpcl = new Http11Client(new Uri(p[1])); httpcl.Connect(); httpcl.Request("GET", new Uri(p[1])).MessageBody.ReadToEnd(); httpcl.Close(); break; case "!https": - var httpscl = new HttpsClient(new Uri(p[1])); + var httpscl = new Https11Client(new Uri(p[1])); httpscl.Connect(); httpscl.Request("GET", new Uri(p[1])).MessageBody.ReadToEnd(); httpscl.Close(); diff --git a/Assets/Cryville/Crtr/Network/UpdateChecker.cs b/Assets/Cryville/Crtr/Network/UpdateChecker.cs index a9e4d35..d8a448f 100644 --- a/Assets/Cryville/Crtr/Network/UpdateChecker.cs +++ b/Assets/Cryville/Crtr/Network/UpdateChecker.cs @@ -1,4 +1,4 @@ -using Cryville.Common.Network; +using Cryville.Common.Network.Http11; using Cryville.Common.Unity; using Newtonsoft.Json; using System; @@ -21,7 +21,7 @@ namespace Cryville.Crtr.Network { List _versions; public void CheckVersion() { try { - var client = new HttpsClient(BaseUri); + var client = new Https11Client(BaseUri); client.Connect(); var response = client.Request("GET", new Uri(BaseUri, "versions")); var data = Encoding.UTF8.GetString(response.MessageBody.ReadToEnd());