From b69e3b6c928b203927bd1f8eae2a36dbf2b42855 Mon Sep 17 00:00:00 2001 From: Ruslan Alekperov <54377741+trusthat@users.noreply.github.com> Date: Tue, 1 Aug 2023 08:30:42 -0700 Subject: [PATCH 1/3] Update .Net target --- CANAPE.Cli/CANAPE.Cli.csproj | 2 +- README.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CANAPE.Cli/CANAPE.Cli.csproj b/CANAPE.Cli/CANAPE.Cli.csproj index e86d4f4..62628a1 100644 --- a/CANAPE.Cli/CANAPE.Cli.csproj +++ b/CANAPE.Cli/CANAPE.Cli.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp3.0; netcoreapp2.0; net471 + netcoreapp7.0; net48 true James Forshaw Command Line Interface CANAPE.Core network library. diff --git a/README.md b/README.md index 669fcbc..8df6790 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # CANAPE.Core - (c) James Forshaw 2017 A network proxy library written in C# for .NET Core based on CANAPE. Licensed under GPLv3. -It should work on any platform with .NET Standard support 2.0, so .NET Core 2.0.5 and .NET Framework 4.7.1 on Windows, Linux and +It should work on any platform with .NET Standard support 2.0, so .NET Core 7.0 and .NET Framework 4.8 on Windows, Linux and macOS should be suitable as well as recompiling for .NET framework and Mono. -To use either compile with Visual Studio 2017 with .NET Core support or from the command line do the -following (replace netcoreapp3.0 with netcoreapp2.0 if using 2.X framework): +To use either compile with Visual Studio 2022 with .NET Core support or from the command line do the +following: ```cd CANAPE.Core -dotnet build CANAPE.Cli/CANAPE.Cli.csproj -c Release -f netcoreapp3.0 -cd CANAPE.Cli/bin/Release/netcoreapp3.0 +dotnet build CANAPE.Cli/CANAPE.Cli.csproj -c Release -f netcoreapp7.0 +cd CANAPE.Cli/bin/Release/netcoreapp7.0 dotnet exec CANAPE.Cli.dll Examples/SocksProxy.csx --color ``` \ No newline at end of file From f2ca994884b45953d58e09686cd11fb5b4f57ddd Mon Sep 17 00:00:00 2001 From: rusal <54377741+trusthat@users.noreply.github.com> Date: Sat, 5 Aug 2023 17:34:01 +0300 Subject: [PATCH 2/3] Fix Code Analysis --- CANAPE.Cli.Lib/ConsoleUtils.cs | 24 ++-- CANAPE.Cli.Lib/EntryPoint.cs | 18 +-- CANAPE.Cli.Lib/NetGraphUtils.cs | 2 +- CANAPE.Cli.Lib/PacketUtils.cs | 11 +- CANAPE.Cli/Program.cs | 1 - .../Endpoint/EchoDataEndpoint.cs | 9 +- CANAPE.Net.Protocols/Parser/DNSPacket.cs | 23 ++- CANAPE.Net.Protocols/Parser/HttpDataChunk.cs | 6 +- CANAPE.Net.Protocols/Parser/HttpParser.cs | 43 +++--- .../Parser/HttpParserConfig.cs | 21 ++- .../Parser/HttpRequestDataChunk.cs | 11 +- .../Parser/HttpRequestHeader.cs | 30 ++-- .../Parser/HttpResponseDataChunk.cs | 6 +- .../Parser/HttpResponseHeader.cs | 38 ++--- CANAPE.Net.Protocols/Parser/HttpVersion.cs | 12 +- .../Server/BaseHttpDataServer.cs | 2 +- .../Server/BaseHttpDataServerRef.cs | 22 +-- CANAPE.Net.Protocols/Server/DnsDataServer.cs | 4 +- CANAPE.Net.Protocols/Server/HttpDataServer.cs | 18 +-- .../Server/HttpServerResponseData.cs | 8 +- CANAPE.Net.Templates/DnsServerTemplate.cs | 1 - .../Factories/BaseNetworkLayerFactory.cs | 1 - .../Factories/BaseProxyClientFactory.cs | 1 - .../Factories/IProxyListenerFactory.cs | 1 - CANAPE.Net.Templates/NetClientTemplate.cs | 10 +- .../UnixSocketProxyTemplate.cs | 2 +- CANAPE.Net/Clients/ChainProxyClient.cs | 7 +- CANAPE.Net/Clients/FilteredIpProxyClient.cs | 3 +- CANAPE.Net/Clients/FixedIpProxyClient.cs | 6 +- .../Clients/FixedStreamSocketProxyClient.cs | 4 +- CANAPE.Net/Clients/IpProxyClient.cs | 12 +- CANAPE.Net/Clients/ProxyClient.cs | 3 +- CANAPE.Net/Clients/SocksProxyClient.cs | 36 ++--- CANAPE.Net/DataAdapters/BoundDataAdapter.cs | 6 +- .../FixHttpConnectionDataAdapter.cs | 16 +-- CANAPE.Net/DataAdapters/IpBoundDataAdapter.cs | 4 - .../DataAdapters/StreamSocketDataAdapter.cs | 2 +- .../DataAdapters/TcpClientDataAdapter.cs | 4 +- .../DataAdapters/TcpListenerDataAdapter.cs | 4 +- .../DataAdapters/UdpClientDataAdapter.cs | 4 +- .../DataAdapters/UdpServerDataAdapter.cs | 3 +- CANAPE.Net/Filters/IpProxyFilter.cs | 6 +- CANAPE.Net/Filters/LayerMergePolicy.cs | 4 - CANAPE.Net/Filters/ProxyFilter.cs | 6 +- CANAPE.Net/Layers/BaseNetworkLayer.cs | 4 +- CANAPE.Net/Layers/DataParserNetworkLayer.cs | 26 ++-- CANAPE.Net/Layers/DynamicNetworkLayer.cs | 8 +- .../Layers/DynamicStreamNetworkLayer.cs | 4 +- CANAPE.Net/Layers/HttpLayerConfigEntry.cs | 22 +-- CANAPE.Net/Layers/HttpNetworkLayer.cs | 74 +++++----- CANAPE.Net/Layers/HttpNetworkLayerConfig.cs | 9 +- CANAPE.Net/Layers/INetworkLayer.cs | 6 +- .../Layers/NetworkLayerFactoryExtensions.cs | 4 +- CANAPE.Net/Layers/TlsNetworkLayer.cs | 32 ++--- CANAPE.Net/Layers/TlsNetworkLayerConfig.cs | 2 +- CANAPE.Net/Layers/WrappedNetworkLayer.cs | 6 +- .../Listeners/AggregateNetworkListener.cs | 1 - CANAPE.Net/Listeners/INetworkListener.cs | 3 +- CANAPE.Net/Listeners/ManualNetworkListener.cs | 4 +- CANAPE.Net/Listeners/TcpNetworkListener.cs | 6 +- CANAPE.Net/Listeners/UdpNetworkListener.cs | 6 +- CANAPE.Net/NetServiceException.cs | 4 +- CANAPE.Net/PacketLogEventArgs.cs | 2 +- CANAPE.Net/Servers/FixedProxyServer.cs | 10 +- CANAPE.Net/Servers/FullHttpProxyServer.cs | 135 +++++++++--------- CANAPE.Net/Servers/HttpProxyServerConfig.cs | 2 +- CANAPE.Net/Servers/ReverseHttpProxyServer.cs | 40 +++--- CANAPE.Net/Servers/SocksProxyServer.cs | 42 +++--- CANAPE.Net/Tokens/FullHttpProxyToken.cs | 6 +- CANAPE.Net/Tokens/HttpProxyToken.cs | 7 +- CANAPE.Net/Tokens/IpProxyToken.cs | 2 +- CANAPE.Net/Tokens/SocksProxyToken.cs | 14 +- CANAPE.Net/Utils/ConnectionHistoryEntry.cs | 3 - CANAPE.Net/Utils/CredentialsEntry.cs | 1 - CANAPE.Net/Utils/LogPacketCollection.cs | 26 ++-- CANAPE.Net/Utils/NetGraphBuilder.cs | 4 +- CANAPE.Net/Utils/NetUtils.cs | 6 +- CANAPE.Security/CertificateBuilder.cs | 2 +- CANAPE.Security/CertificateUtils.cs | 12 +- CANAPE/DataAdapters/BaseDataAdapter.cs | 10 +- CANAPE/DataAdapters/CoupledDataAdapter.cs | 4 +- CANAPE/DataAdapters/DataAdapterToStream.cs | 12 +- CANAPE/DataAdapters/DelegateDataAdapter.cs | 2 +- CANAPE/DataAdapters/EnumerableDataAdapter.cs | 11 +- CANAPE/DataAdapters/NullDataAdapter.cs | 4 +- CANAPE/DataAdapters/PrefixedDataAdapter.cs | 2 - CANAPE/DataAdapters/QueuedDataAdapter.cs | 8 +- CANAPE/DataAdapters/StreamDataAdapter.cs | 4 +- .../BasicDataFrameEqualityComparer.cs | 2 +- CANAPE/DataFrames/ByteArrayDataFrame.cs | 78 +++++----- CANAPE/DataFrames/ComplexDataFrame.cs | 76 +++++----- CANAPE/DataFrames/DataFrame.cs | 20 +-- CANAPE/DataFrames/DataFrameExtensions.cs | 60 ++++---- CANAPE/DataFrames/StringDataFrame.cs | 114 +++++++-------- CANAPE/NodeFactories/BaseNodeFactory.cs | 6 +- CANAPE/NodeFactories/ClientEndpointFactory.cs | 2 +- CANAPE/NodeFactories/DelayNodeFactory.cs | 2 +- CANAPE/NodeFactories/DirectNodeFactory.cs | 4 +- CANAPE/NodeFactories/EditPacketNodeFactory.cs | 6 +- CANAPE/NodeFactories/LogPacketNodeFactory.cs | 4 +- .../NetGraphContainerNodeFactory.cs | 8 +- CANAPE/NodeFactories/NetGraphFactory.cs | 28 ++-- .../NodeFactories/PipelineEndpointFactory.cs | 2 +- CANAPE/NodeFactories/ServerEndpointFactory.cs | 2 +- CANAPE/Nodes/BaseDataEndpoint.cs | 2 +- CANAPE/Nodes/BaseDecoupledPipelineNode.cs | 10 +- CANAPE/Nodes/BasePersistDataEndpoint.cs | 2 +- CANAPE/Nodes/BasePersistDataEndpointRef.cs | 2 +- CANAPE/Nodes/BasePipelineNode.cs | 42 +++--- CANAPE/Nodes/BaseStreamPipelineNode.cs | 8 +- CANAPE/Nodes/DataEndpointAdapter.cs | 5 +- CANAPE/Nodes/DelayPipelineNode.cs | 2 +- CANAPE/Nodes/DirectPipelineNode.cs | 7 +- CANAPE/Nodes/EditPacketPipelineNode.cs | 8 +- CANAPE/Nodes/IPersistNode.cs | 6 +- CANAPE/Nodes/IPipelineEndpoint.cs | 4 +- CANAPE/Nodes/LogPacketPipelineNode.cs | 12 +- CANAPE/Nodes/MetaDictionary.cs | 4 +- CANAPE/Nodes/NetGraph.cs | 40 +++--- CANAPE/Nodes/NetGraphContainerNode.cs | 18 +-- CANAPE/Nodes/PipelineEndpoint.cs | 12 +- CANAPE/Utils/BinaryEncoding.cs | 21 ++- CANAPE/Utils/ColorValue.cs | 10 +- CANAPE/Utils/DataReader.cs | 56 ++++---- CANAPE/Utils/DataWriter.cs | 32 ++--- CANAPE/Utils/DiffItem.cs | 4 +- CANAPE/Utils/DynamicConfigObject.cs | 2 +- CANAPE/Utils/GeneralUtils.cs | 37 +++-- CANAPE/Utils/LockedQueue.cs | 6 +- CANAPE/Utils/LogPacket.cs | 14 +- CANAPE/Utils/Logger.cs | 7 +- CANAPE/Utils/PipelineStream.cs | 12 +- CANAPE/Utils/PropertyBag.cs | 6 +- CANAPE/Utils/TextLineEnding.cs | 2 +- CANAPE/Utils/TwentyFourBitIntegers.cs | 1 - 135 files changed, 901 insertions(+), 954 deletions(-) diff --git a/CANAPE.Cli.Lib/ConsoleUtils.cs b/CANAPE.Cli.Lib/ConsoleUtils.cs index 7844ec4..318b993 100644 --- a/CANAPE.Cli.Lib/ConsoleUtils.cs +++ b/CANAPE.Cli.Lib/ConsoleUtils.cs @@ -15,11 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataFrames; using CANAPE.Utils; using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using CANAPE.DataFrames; namespace CANAPE.Cli { @@ -96,7 +96,7 @@ private static bool GetEffectiveColorMode() { return _supports_ansi_color && EnableColor; } - + public static void WritePacket(LogPacket packet) { Console.Out.WriteLine(PacketUtils.ConvertPacketToString(packet, GetEffectiveColorMode())); @@ -110,17 +110,17 @@ public static void WritePackets(IEnumerable packets) } } - public static void WritePacket(DataFrame frame) - { - Console.Out.WriteLine(PacketUtils.ConvertPacketToString(frame)); - } + public static void WritePacket(DataFrame frame) + { + Console.Out.WriteLine(PacketUtils.ConvertPacketToString(frame)); + } - public static void WritePackets(IEnumerable packets) - { + public static void WritePackets(IEnumerable packets) + { foreach (DataFrame packet in packets) - { - WritePacket(packet); - } - } + { + WritePacket(packet); + } + } } } diff --git a/CANAPE.Cli.Lib/EntryPoint.cs b/CANAPE.Cli.Lib/EntryPoint.cs index d013b0c..a135e76 100644 --- a/CANAPE.Cli.Lib/EntryPoint.cs +++ b/CANAPE.Cli.Lib/EntryPoint.cs @@ -17,10 +17,10 @@ // along with this program. If not, see . using CANAPE.Net.Templates; using CANAPE.Utils; +using McMaster.Extensions.CommandLineUtils; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; -using McMaster.Extensions.CommandLineUtils; using System; using System.Collections.Generic; using System.IO; @@ -70,7 +70,7 @@ private static ScriptOptions CreateScriptOptions(string filename, IEnumerable include_dirs, IEnumerab var options = CreateScriptOptions(null, include_dirs, metadata_dirs); var state = await CSharpScript.RunAsync("static void quit() { Environment.Exit(0); }", options); Console.WriteLine("Type quit() to exit the console"); - + while (true) { StringBuilder current_line = new StringBuilder(); @@ -124,7 +124,7 @@ private async static Task RunConsole(IEnumerable include_dirs, IEnumerab } } - private static ScriptRunner CompileScript(string filename, + private static ScriptRunner CompileScript(string filename, IEnumerable include_dirs, IEnumerable metadata_dirs) { @@ -141,8 +141,8 @@ private static ScriptRunner CompileScript(string filename, } } - private async static Task RunScript(string filename, - IEnumerable include_dirs, + private async static Task RunScript(string filename, + IEnumerable include_dirs, IEnumerable metadata_dirs, IEnumerable args) { @@ -169,7 +169,7 @@ public static int Main(string[] args) Logger.SystemLogger = LogUtils.GetLogger(Console.Error); Console.Error.WriteLine("CANAPE.Cli (c) 2017 James Forshaw, 2014 Context Information Security."); CommandLineApplication app = new CommandLineApplication(false); - + CommandArgument script = app.Argument("script", "Specify a script file to run."); CommandOption compile = app.Option( "-c | --compile", "Compile script file only.", @@ -193,7 +193,7 @@ public static int Main(string[] args) IEnumerable include_dirs = include.HasValue() ? include.Values.Select(p => Path.GetFullPath(p)) : new string[0]; IEnumerable metadata_dirs = libs.HasValue() ? libs.Values.Select(p => Path.GetFullPath(p)) : new string[0]; - ConsoleUtils.EnableColor = color.HasValue(); + ConsoleUtils.EnableColor = color.HasValue(); if (verbose.HasValue()) { Logger.SystemLogger.LogLevel = Logger.LogEntryType.All; diff --git a/CANAPE.Cli.Lib/NetGraphUtils.cs b/CANAPE.Cli.Lib/NetGraphUtils.cs index c9e0a89..da283d9 100644 --- a/CANAPE.Cli.Lib/NetGraphUtils.cs +++ b/CANAPE.Cli.Lib/NetGraphUtils.cs @@ -71,7 +71,7 @@ public static string ToDot(NetGraphFactory netgraph) if (!node.Enabled) { attrs.Add("style=dotted"); - } + } if (attrs.Count > 0) { diff --git a/CANAPE.Cli.Lib/PacketUtils.cs b/CANAPE.Cli.Lib/PacketUtils.cs index d377e26..b1114ff 100644 --- a/CANAPE.Cli.Lib/PacketUtils.cs +++ b/CANAPE.Cli.Lib/PacketUtils.cs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using CANAPE.DataFrames; -using CANAPE.Nodes; using CANAPE.Utils; using System; using System.Collections.Generic; @@ -151,7 +150,7 @@ private static string GetHeader(LogPacket p) return String.Format("Time {0} - Tag '{1}' - Network '{2}'", p.Timestamp.ToString(), p.Tag, p.Network); } - + /// /// Convert a packet to a hex string format /// @@ -188,10 +187,10 @@ public static string ConvertPacketToString(DataFrame p) return ConvertTextPacketToString(p); } else - { - return ConvertBinaryPacketToString(p); - } - } + { + return ConvertBinaryPacketToString(p); + } + } private static ColorValue PickContrastingColor(ColorValue color) { diff --git a/CANAPE.Cli/Program.cs b/CANAPE.Cli/Program.cs index 0dacc83..13c8ff6 100644 --- a/CANAPE.Cli/Program.cs +++ b/CANAPE.Cli/Program.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; namespace CANAPE.Cli { diff --git a/CANAPE.Net.Protocols/Endpoint/EchoDataEndpoint.cs b/CANAPE.Net.Protocols/Endpoint/EchoDataEndpoint.cs index 6b037bb..eec8e74 100644 --- a/CANAPE.Net.Protocols/Endpoint/EchoDataEndpoint.cs +++ b/CANAPE.Net.Protocols/Endpoint/EchoDataEndpoint.cs @@ -18,7 +18,6 @@ using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Nodes; -using CANAPE.Utils; namespace CANAPE.Net.Protocols.Endpoint { @@ -39,7 +38,7 @@ public class EchoDataEndpointConfig /// Echo data endpoint. /// public class EchoDataEndpoint : BasePersistDataEndpoint - { + { /// /// Run the specified adapter. /// @@ -49,8 +48,8 @@ public override void Run(IDataAdapter adapter) { DataFrame frame = adapter.Read(); - while(frame != null) - { + while (frame != null) + { if (Config.ConvertToBasic) { frame = frame.ToArray().ToDataFrame(); @@ -59,7 +58,7 @@ public override void Run(IDataAdapter adapter) adapter.Write(frame); frame = adapter.Read(); - } + } } /// diff --git a/CANAPE.Net.Protocols/Parser/DNSPacket.cs b/CANAPE.Net.Protocols/Parser/DNSPacket.cs index 8b33a00..a8fef23 100644 --- a/CANAPE.Net.Protocols/Parser/DNSPacket.cs +++ b/CANAPE.Net.Protocols/Parser/DNSPacket.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using CANAPE.DataFrames; using CANAPE.Utils; using System; using System.Collections.Generic; @@ -307,7 +306,7 @@ public class CNameDNSRR : DNSRRBase /// /// The CNAME /// - public string CName { get; set; } + public string CName { get; set; } /// /// Constructor @@ -334,7 +333,7 @@ public CNameDNSRR() /// The string cache public override void WriteData(DataWriter writer, Dictionary stringCache) { - WriteString(CName, writer, stringCache); + WriteString(CName, writer, stringCache); } } @@ -426,7 +425,7 @@ public AAAADNSRR() /// The writer /// The string cache public override void WriteData(DataWriter writer, Dictionary stringCache) - { + { if (Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) { throw new ArgumentException("Must provide a IPv6 address for a AAAA record"); @@ -629,7 +628,7 @@ private static DNSRRBase ReadResourceRecord(byte[] data, DataReader reader) rr.Class = cls; rr.Type = type; rr.TimeToLive = ttl; - + return rr; } @@ -647,12 +646,12 @@ private static DNSRRBase[] ReadResourceRecords(byte[] data, DataReader reader, i private static bool GetBooleanFlag(ushort flags, int pos) { - return ((flags >> (15-pos)) & 1) == 1; + return ((flags >> (15 - pos)) & 1) == 1; } private static int GetFlagValue(ushort flags, int pos) { - return (flags >> (15-pos-3)) & 0xF; + return (flags >> (15 - pos - 3)) & 0xF; } private static ushort SetBooleanFlag(ushort flags, int pos, bool value) @@ -669,7 +668,7 @@ private static ushort SetBooleanFlag(ushort flags, int pos, bool value) private static ushort SetFlagValue(ushort flags, int pos, int val) { - return (ushort)(flags | (val << (15 - pos - 3))); + return (ushort)(flags | (val << (15 - pos - 3))); } /// @@ -703,7 +702,7 @@ public static DNSPacket FromArray(byte[] data) if (qdcount > 0) { DNSQuestion[] questions = new DNSQuestion[qdcount]; - + for (int i = 0; i < qdcount; i++) { questions[i] = ReadQuestion(data, reader); @@ -713,7 +712,7 @@ public static DNSPacket FromArray(byte[] data) } if (ancount > 0) - { + { ret.Answers = ReadResourceRecords(data, reader, ancount); } @@ -767,7 +766,7 @@ private static void WriteStringPart(string value, DataWriter writer, Dictionary< { WriteStringPart(null, writer, stringCache); } - } + } } } @@ -842,5 +841,5 @@ public byte[] ToArray() return stm.ToArray(); } - } + } } diff --git a/CANAPE.Net.Protocols/Parser/HttpDataChunk.cs b/CANAPE.Net.Protocols/Parser/HttpDataChunk.cs index bcb9738..507d31e 100644 --- a/CANAPE.Net.Protocols/Parser/HttpDataChunk.cs +++ b/CANAPE.Net.Protocols/Parser/HttpDataChunk.cs @@ -187,14 +187,14 @@ private bool FilterHeader(string name, string value) if (!CanSendBody() || FinalChunk) { return true; - } + } } return false; } private void WriteHeaders(DataWriter writer) - { + { string writeHeader = OnWriteHeader(); // null indicates that a response has no headers @@ -233,7 +233,7 @@ private byte[] GetBody() } private void WriteBody(DataWriter writer) - { + { byte[] body = GetBody(); if (ChunkedEncoding) diff --git a/CANAPE.Net.Protocols/Parser/HttpParser.cs b/CANAPE.Net.Protocols/Parser/HttpParser.cs index 1760207..8eb45be 100644 --- a/CANAPE.Net.Protocols/Parser/HttpParser.cs +++ b/CANAPE.Net.Protocols/Parser/HttpParser.cs @@ -27,15 +27,15 @@ namespace CANAPE.Net.Protocols.Parser /// public static class HttpParser { - - /// - /// Check if has a header. - /// - /// The list of headers - /// The header to find - /// Optional list of values to match - /// True if the header exists and contains at least one of these values - public static bool HasHeader(this IEnumerable headers, string header, params string[] values) + + /// + /// Check if has a header. + /// + /// The list of headers + /// The header to find + /// Optional list of values to match + /// True if the header exists and contains at least one of these values + public static bool HasHeader(this IEnumerable headers, string header, params string[] values) { bool ret = false; @@ -90,7 +90,7 @@ private static void CheckLineEnding(string line) } private static IEnumerable ReadHeaders(DataReader reader, bool strictParsing, Logger logger) - { + { while (true) { string line = reader.ReadLine(); @@ -122,10 +122,10 @@ private static IEnumerable ReadHeaders(DataReader reader, bool stric } else { - if(values.Length > 0) + if (values.Length > 0) { name = values[0]; - if(values.Length > 1) + if (values.Length > 1) { value = values[1]; } @@ -133,7 +133,7 @@ private static IEnumerable ReadHeaders(DataReader reader, bool stric } yield return new HttpHeader(name.Trim(), value.Trim()); - } + } } /// @@ -161,8 +161,8 @@ public static HttpRequestHeader ReadRequestHeader(DataReader reader, bool strict public static HttpRequestHeader ReadRequestHeader(DataReader reader, bool strictParsing, Logger logger, char[] prefix) { string header; - - if(prefix != null) + + if (prefix != null) { header = new string(prefix) + reader.ReadLine(); } @@ -171,7 +171,8 @@ public static HttpRequestHeader ReadRequestHeader(DataReader reader, bool strict header = reader.ReadLine(); } - if (header.Length == 0) { + if (header.Length == 0) + { throw new EndOfStreamException(); } @@ -179,14 +180,14 @@ public static HttpRequestHeader ReadRequestHeader(DataReader reader, bool strict { CheckLineEnding(header); } - + // Let us default to version unknown HttpVersion ver = HttpVersion.VersionUnknown; List headers = new List(); string[] values = header.Trim().Split(new char[] { ' ' }, 3); if (values.Length < 2) - { + { throw new HttpStreamParserException(String.Format(Properties.Resources.HttpParser_RequestHeaderInvalid, header)); } @@ -252,8 +253,8 @@ public static HttpResponseHeader ReadResponseHeader(DataReader reader, bool stri { // Case where server probably responded with simple response even when we sent a full one return new HttpResponseHeader(reader, header); - } - } + } + } internal static long GetContentLength(IEnumerable headers) { @@ -277,7 +278,7 @@ internal static bool IsChunkedEncoding(IEnumerable headers) { foreach (var pair in headers) { - if (pair.Name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase) + if (pair.Name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase) && pair.Value.Equals("chunked", StringComparison.OrdinalIgnoreCase)) { return true; diff --git a/CANAPE.Net.Protocols/Parser/HttpParserConfig.cs b/CANAPE.Net.Protocols/Parser/HttpParserConfig.cs index 73991d4..51bc8b7 100644 --- a/CANAPE.Net.Protocols/Parser/HttpParserConfig.cs +++ b/CANAPE.Net.Protocols/Parser/HttpParserConfig.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; namespace CANAPE.Net.Protocols.Parser { @@ -24,16 +23,16 @@ namespace CANAPE.Net.Protocols.Parser /// public class HttpParserConfig { - /// - /// Default chunk size - /// - public const int DEFAULT_CHUNK_SIZE = 8 * 1024; + /// + /// Default chunk size + /// + public const int DEFAULT_CHUNK_SIZE = 8 * 1024; + + /// + /// If true body will be streamed rather than buffered up + /// + public bool StreamBody { get; set; } - /// - /// If true body will be streamed rather than buffered up - /// - public bool StreamBody { get; set; } - /// /// Specify how big a chunk to read in per chunk when in streaming mode, set to 0 to disable which /// will send data with no buffering, this is advisory, it won't work in chunked encoding, @@ -62,7 +61,7 @@ public class HttpParserConfig /// public HttpParserConfig() { - StreamChunkSize = DEFAULT_CHUNK_SIZE; + StreamChunkSize = DEFAULT_CHUNK_SIZE; } } } diff --git a/CANAPE.Net.Protocols/Parser/HttpRequestDataChunk.cs b/CANAPE.Net.Protocols/Parser/HttpRequestDataChunk.cs index e144f29..84a49bc 100644 --- a/CANAPE.Net.Protocols/Parser/HttpRequestDataChunk.cs +++ b/CANAPE.Net.Protocols/Parser/HttpRequestDataChunk.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using System; using System.Globalization; -using System.Runtime.InteropServices; namespace CANAPE.Net.Protocols.Parser { @@ -26,17 +25,17 @@ namespace CANAPE.Net.Protocols.Parser /// public sealed class HttpRequestDataChunk : HttpDataChunk { - internal HttpRequestDataChunk(HttpRequestHeader header) + internal HttpRequestDataChunk(HttpRequestHeader header) : base(header.Headers, header.Version) { Method = header.Method; - Path = header.Path; + Path = header.Path; } /// /// Public constructor /// - public HttpRequestDataChunk() + public HttpRequestDataChunk() { Method = "GET"; Path = "/"; @@ -75,7 +74,7 @@ protected override string OnWriteHeader() if (!Version.IsVersionUnknown) { ret = String.Format(CultureInfo.InvariantCulture, "{0} {1}", ret, Version); - } + } } else { @@ -101,7 +100,7 @@ public override bool CloseAfterBody() protected override bool CanSendBody() { // These methods cannot send a body - if (Method.Equals("GET", StringComparison.OrdinalIgnoreCase) + if (Method.Equals("GET", StringComparison.OrdinalIgnoreCase) || Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { return false; diff --git a/CANAPE.Net.Protocols/Parser/HttpRequestHeader.cs b/CANAPE.Net.Protocols/Parser/HttpRequestHeader.cs index 74c0080..fdb15c6 100644 --- a/CANAPE.Net.Protocols/Parser/HttpRequestHeader.cs +++ b/CANAPE.Net.Protocols/Parser/HttpRequestHeader.cs @@ -79,7 +79,7 @@ public bool IsConnect // Create a default header internal HttpRequestHeader() : this(null, new HttpHeader[0], "GET", "/", HttpVersion.Version10) { - } + } internal HttpRequestHeader(DataReader reader, IEnumerable headers, string method, string path, HttpVersion version) { @@ -88,9 +88,9 @@ internal HttpRequestHeader(DataReader reader, IEnumerable headers, s Method = method; Path = path; Version = version; - + // These methods can't have a content length - if(IsGet || IsHead) + if (IsGet || IsHead) { ContentLength = 0; } @@ -123,7 +123,7 @@ private IEnumerable ReadChunksStreamed(HttpParserConfig co chunk.ChunkNumber = chunkNumber++; yield return chunk; - } + } while (length > 0) { @@ -134,7 +134,7 @@ private IEnumerable ReadChunksStreamed(HttpParserConfig co // While we are reading we wouldn't expect no data to be returned if (data.Length == 0) { - throw new EndOfStreamException(); + throw new EndOfStreamException(); } length -= data.Length; @@ -152,13 +152,13 @@ private IEnumerable ReadChunksStreamed(HttpParserConfig co } private IEnumerable ReadChunksConnect(HttpParserConfig config) - { - int chunkNumber = 0; + { + int chunkNumber = 0; - while(true) + while (true) { byte[] data = _reader.ReadBytes(HttpParserConfig.DEFAULT_CHUNK_SIZE, false); - + if (data.Length == 0) { throw new EndOfStreamException(); @@ -171,14 +171,14 @@ private IEnumerable ReadChunksConnect(HttpParserConfig con if (chunkNumber < int.MaxValue) { chunkNumber++; - } + } // Cast to length, really should just ignore any data set greater than a set amount chunk.Body = data; yield return chunk; } - + } private IEnumerable ReadChunksBuffered(HttpParserConfig config) @@ -191,13 +191,13 @@ private IEnumerable ReadChunksBuffered(HttpParserConfig co // If we are expecting 100 continue then we have to // send the header first otherwise this will block if we have a length if (Headers.HasHeader("Expect", "100-continue") && (length > 0)) - { + { chunk.ChunkNumber = chunkNumber++; yield return chunk; chunk = new HttpRequestDataChunk(this); - } + } chunk.ChunkNumber = chunkNumber; chunk.FinalChunk = true; @@ -216,7 +216,7 @@ private IEnumerable ReadChunksBuffered(HttpParserConfig co /// /// An enumerable list of chunks public IEnumerable ReadChunks(HttpParserConfig config) - { + { if (IsConnect) { return ReadChunksConnect(config); @@ -228,7 +228,7 @@ public IEnumerable ReadChunks(HttpParserConfig config) else { return ReadChunksBuffered(config); - } + } } /// diff --git a/CANAPE.Net.Protocols/Parser/HttpResponseDataChunk.cs b/CANAPE.Net.Protocols/Parser/HttpResponseDataChunk.cs index 30cfab1..086412b 100644 --- a/CANAPE.Net.Protocols/Parser/HttpResponseDataChunk.cs +++ b/CANAPE.Net.Protocols/Parser/HttpResponseDataChunk.cs @@ -49,7 +49,7 @@ public sealed class HttpResponseDataChunk : HttpDataChunk /// connect response. /// /// true if connect response; otherwise, false. - public bool ConnectResponse { get; set; } + public bool ConnectResponse { get; set; } /// /// Initializes a new instance of the class. @@ -75,7 +75,7 @@ protected override string OnWriteHeader() string ret = null; if (!Version.IsVersionUnknown) - { + { if (!String.IsNullOrWhiteSpace(Message)) { ret = String.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", Version, ResponseCode, Message); @@ -102,7 +102,7 @@ protected override bool CanSendBody() return true; } - + /// /// Filters the length of the content. /// diff --git a/CANAPE.Net.Protocols/Parser/HttpResponseHeader.cs b/CANAPE.Net.Protocols/Parser/HttpResponseHeader.cs index c86ff87..b58165c 100644 --- a/CANAPE.Net.Protocols/Parser/HttpResponseHeader.cs +++ b/CANAPE.Net.Protocols/Parser/HttpResponseHeader.cs @@ -41,7 +41,7 @@ public class HttpResponseHeader /// /// /// - public HttpVersion Version { get; private set; } + public HttpVersion Version { get; private set; } /// /// /// @@ -53,7 +53,7 @@ public class HttpResponseHeader /// /// /// - public bool ChunkedEncoding { get; private set; } + public bool ChunkedEncoding { get; private set; } /// /// /// @@ -93,18 +93,18 @@ public void SetConnectRequest(bool connect) private DataReader _reader; private string _initialData; - internal HttpResponseHeader(DataReader reader, string initialData) + internal HttpResponseHeader(DataReader reader, string initialData) : this(reader, new HttpHeader[0], 200, String.Empty, HttpVersion.VersionUnknown) - { + { _initialData = initialData; } - internal HttpResponseHeader(DataReader reader, IEnumerable headers, + internal HttpResponseHeader(DataReader reader, IEnumerable headers, int responseCode, string message, HttpVersion version) { _reader = reader; Headers = new List(headers); - ResponseCode = responseCode; + ResponseCode = responseCode; Message = message; Version = version; @@ -114,13 +114,13 @@ internal HttpResponseHeader(DataReader reader, IEnumerable headers, ChunkedEncoding = HttpParser.IsChunkedEncoding(Headers); HasBody = true; } - + // Always trust a content-length if it exists if (Headers.Count(p => p.Name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) == 0) { // Otherwise if version unknown, 1.0 or connection will close set then indicate we will read to the end if (Version.IsVersionUnknown || Version.IsVersion10 || (Headers.Count(p => p.Name.Equals("Connection", StringComparison.OrdinalIgnoreCase) && p.Value.Equals("close", StringComparison.OrdinalIgnoreCase)) > 0)) - { + { ReadToEnd = true; } } @@ -205,8 +205,8 @@ private HttpResponseDataChunk CreateChunk(byte[] body, int chunkNumber, bool fin // Remove any content-length and existing Transfer-Encoding chunked foreach (HttpHeader pair in ret.Headers) { - if (!(pair.Name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) - || (pair.Name.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase) + if (!(pair.Name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) + || (pair.Name.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase) && pair.Value.Equals("chunked", StringComparison.OrdinalIgnoreCase)))) { headers.Add(pair); @@ -218,7 +218,7 @@ private HttpResponseDataChunk CreateChunk(byte[] body, int chunkNumber, bool fin } - return ret; + return ret; } private IEnumerable ReadChunksStreamedLength(HttpParserConfig config) @@ -229,7 +229,7 @@ private IEnumerable ReadChunksStreamedLength(HttpParserCo int chunkNumber = 0; // Can only convert if returning HTTP/1.1 - bool convertToChunked = config.ConvertToChunked && Version.IsVersion11; + bool convertToChunked = config.ConvertToChunked && Version.IsVersion11; if (chunkSize <= 0) { @@ -243,7 +243,7 @@ private IEnumerable ReadChunksStreamedLength(HttpParserCo { List block = new List(BinaryEncoding.Instance.GetBytes(_initialData)); - if(!_reader.Eof) + if (!_reader.Eof) { // Worst case you will get chunkSize + 4 block.AddRange(waitForAll ? _reader.ReadToEnd(chunkSize) : _reader.ReadBytes(chunkSize, false)); @@ -252,7 +252,7 @@ private IEnumerable ReadChunksStreamedLength(HttpParserCo yield return CreateChunk(block.ToArray(), chunkNumber++, _reader.Eof, convertToChunked); } - while(!_reader.Eof) + while (!_reader.Eof) { byte[] block = waitForAll ? _reader.ReadToEnd(chunkSize) : _reader.ReadBytes(chunkSize, false); @@ -311,7 +311,7 @@ private IEnumerable ReadChunksConnect(HttpParserConfig co } private IEnumerable ReadChunksStreamedChunked(HttpParserConfig config) - { + { string extension; int chunkNumber = 0; @@ -320,7 +320,7 @@ private IEnumerable ReadChunksStreamedChunked(HttpParserC if (config.DowngradeChunkedToHttp10) { int i = 0; - while(i < headers.Count) + while (i < headers.Count) { if (headers[i].Name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase) && headers[i].Value.Equals("chunked", StringComparison.OrdinalIgnoreCase)) @@ -345,7 +345,7 @@ private IEnumerable ReadChunksStreamedChunked(HttpParserC if (config.DowngradeChunkedToHttp10) { chunk.Headers = headers.ToArray(); - chunk.Version = HttpVersion.Version10; + chunk.Version = HttpVersion.Version10; } else { @@ -355,12 +355,12 @@ private IEnumerable ReadChunksStreamedChunked(HttpParserC chunk.ChunkExtension = extension; ret = ReadChunkedEncoding(_reader, out extension); chunk.FinalChunk = ret.Length == 0; - + yield return chunk; } while (ret.Length > 0); } - + private IEnumerable ReadChunksBuffered(HttpParserConfig config) { HttpResponseDataChunk chunk = new HttpResponseDataChunk(this); diff --git a/CANAPE.Net.Protocols/Parser/HttpVersion.cs b/CANAPE.Net.Protocols/Parser/HttpVersion.cs index 84422c6..336d1a0 100644 --- a/CANAPE.Net.Protocols/Parser/HttpVersion.cs +++ b/CANAPE.Net.Protocols/Parser/HttpVersion.cs @@ -36,7 +36,7 @@ public static HttpVersion Parse(string version) { HttpVersion ret; - if(TryParse(version, out ret)) + if (TryParse(version, out ret)) { return ret; } @@ -60,7 +60,7 @@ public static bool TryParse(string version, out HttpVersion ret) bool success = false; if (m.Success) - { + { int major; int minor; @@ -68,7 +68,7 @@ public static bool TryParse(string version, out HttpVersion ret) { ret = new HttpVersion(major, minor); success = true; - } + } } return success; @@ -130,14 +130,14 @@ public override bool Equals(object obj) public override int GetHashCode() { return Major.GetHashCode() ^ Minor.GetHashCode(); - } - + } + /// /// Constructor /// /// The major version /// The minor version - public HttpVersion(int major, int minor) + public HttpVersion(int major, int minor) { Major = major; Minor = minor; diff --git a/CANAPE.Net.Protocols/Server/BaseHttpDataServer.cs b/CANAPE.Net.Protocols/Server/BaseHttpDataServer.cs index da2933d..bfe7c29 100644 --- a/CANAPE.Net.Protocols/Server/BaseHttpDataServer.cs +++ b/CANAPE.Net.Protocols/Server/BaseHttpDataServer.cs @@ -21,7 +21,7 @@ namespace CANAPE.Net.Protocols.Server /// Base HTTP server /// /// The configuration type - public abstract class BaseHttpDataServer : BaseHttpDataServerRef where T : class, new() + public abstract class BaseHttpDataServer : BaseHttpDataServerRef where T : class, new() { } } diff --git a/CANAPE.Net.Protocols/Server/BaseHttpDataServerRef.cs b/CANAPE.Net.Protocols/Server/BaseHttpDataServerRef.cs index 36da1e9..0ef0c0a 100644 --- a/CANAPE.Net.Protocols/Server/BaseHttpDataServerRef.cs +++ b/CANAPE.Net.Protocols/Server/BaseHttpDataServerRef.cs @@ -30,8 +30,8 @@ namespace CANAPE.Net.Protocols.Server /// /// Type of configuration class to persist /// Reference type to access the configuration - public abstract class BaseHttpDataServerRef : BasePersistDataEndpointRef where R : class where T : class, R, new() - { + public abstract class BaseHttpDataServerRef : BasePersistDataEndpointRef where R : class where T : class, R, new() + { /// /// Handle a HTTP request /// @@ -42,7 +42,7 @@ namespace CANAPE.Net.Protocols.Server /// HTTP version /// A logger to log data to /// A HTTP response data object, or null if no response - protected abstract HttpServerResponseData HandleRequest(string method, string path, byte[] body, + protected abstract HttpServerResponseData HandleRequest(string method, string path, byte[] body, Dictionary headers, HttpVersion version, Logger logger); /// @@ -50,16 +50,16 @@ protected abstract HttpServerResponseData HandleRequest(string method, string pa /// /// The data adapter public sealed override void Run(IDataAdapter adapter) - { + { DataReader reader = new DataReader(new DataAdapterToStream(adapter)); while (true) { HttpRequestHeader request = HttpParser.ReadRequestHeader(reader, false, Logger); - HttpRequestDataChunk req = request.ReadRequest(); + HttpRequestDataChunk req = request.ReadRequest(); - Dictionary headers = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach(HttpHeader pair in req.Headers) + Dictionary headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (HttpHeader pair in req.Headers) { headers[pair.Name] = pair.Value; } @@ -67,16 +67,16 @@ public sealed override void Run(IDataAdapter adapter) HttpServerResponseData data = HandleRequest(req.Method, req.Path, req.Body, headers, req.Version, Logger); HttpResponseDataChunk response = new HttpResponseDataChunk(); - + response.Version = request.Version; response.ResponseCode = data.ResponseCode; response.Message = data.Message; - + List newHeaders = new List(); foreach (KeyValuePair pair in data.Headers) { - newHeaders.Add(new HttpHeader(pair.Key, pair.Value)); + newHeaders.Add(new HttpHeader(pair.Key, pair.Value)); } if (!data.Headers.ContainsKey("content-length")) @@ -84,7 +84,7 @@ public sealed override void Run(IDataAdapter adapter) newHeaders.Add(new HttpHeader("Content-Length", data.Body.Length.ToString())); } - response.Headers = newHeaders.ToArray(); + response.Headers = newHeaders.ToArray(); response.FinalChunk = true; if (request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) diff --git a/CANAPE.Net.Protocols/Server/DnsDataServer.cs b/CANAPE.Net.Protocols/Server/DnsDataServer.cs index 014e9c1..88c00b3 100644 --- a/CANAPE.Net.Protocols/Server/DnsDataServer.cs +++ b/CANAPE.Net.Protocols/Server/DnsDataServer.cs @@ -36,7 +36,7 @@ private static IPAddress VerifyIPAddress(IPAddress address, AddressFamily family { if (address.AddressFamily != family) { - throw new ArgumentException(String.Format("Address must be {0} family", + throw new ArgumentException(String.Format("Address must be {0} family", family == AddressFamily.InterNetwork ? "IPv4" : "IPv6"), "family"); } return address; @@ -182,7 +182,7 @@ public override void Run(IDataAdapter adapter) /// Validates the config. /// /// Config. - protected override void ValidateConfig(DnsDataServerConfig config) + protected override void ValidateConfig(DnsDataServerConfig config) { if (config.ResponseAddress.AddressFamily != AddressFamily.InterNetwork) { diff --git a/CANAPE.Net.Protocols/Server/HttpDataServer.cs b/CANAPE.Net.Protocols/Server/HttpDataServer.cs index 5550b2f..5e39c08 100644 --- a/CANAPE.Net.Protocols/Server/HttpDataServer.cs +++ b/CANAPE.Net.Protocols/Server/HttpDataServer.cs @@ -31,21 +31,21 @@ public class HttpDataServerConfig /// /// A HTTP path to match against /// - + public string HttpPath { get; set; } /// /// Gets or sets the valid response data. /// /// The valid response data. - + public byte[] ValidResponseData { get; set; } /// /// Gets or sets the not found response data. /// /// The not found response data. - + public byte[] NotFoundResponseData { get; set; } /// @@ -53,14 +53,14 @@ public class HttpDataServerConfig /// close after sending. /// /// true if close after sending; otherwise, false. - + public bool CloseAfterSending { get; set; } /// /// Gets or sets the type of the content. /// /// The type of the content. - + public string ContentType { get; set; } /// @@ -80,7 +80,7 @@ public HttpDataServerConfig() /// Http data server. /// public class HttpDataServer : BaseHttpDataServer - { + { /// /// Handles the request. /// @@ -91,7 +91,7 @@ public class HttpDataServer : BaseHttpDataServer /// Headers. /// Version. /// Logger. - protected override HttpServerResponseData HandleRequest(string method, string path, byte[] body, + protected override HttpServerResponseData HandleRequest(string method, string path, byte[] body, Dictionary headers, HttpVersion version, Logger logger) { Regex pathRegex = GeneralUtils.GlobToRegex(Config.HttpPath); @@ -106,7 +106,7 @@ protected override HttpServerResponseData HandleRequest(string method, string pa if (Config.ValidResponseData != null) { data.Body = Config.ValidResponseData; - } + } } else { @@ -115,7 +115,7 @@ protected override HttpServerResponseData HandleRequest(string method, string pa if (Config.NotFoundResponseData != null) { data.Body = Config.NotFoundResponseData; - } + } } data.Headers["Content-Type"] = Config.ContentType ?? "text/html"; diff --git a/CANAPE.Net.Protocols/Server/HttpServerResponseData.cs b/CANAPE.Net.Protocols/Server/HttpServerResponseData.cs index 880e5c9..740a29b 100644 --- a/CANAPE.Net.Protocols/Server/HttpServerResponseData.cs +++ b/CANAPE.Net.Protocols/Server/HttpServerResponseData.cs @@ -24,7 +24,7 @@ namespace CANAPE.Net.Protocols.Server /// Response data for HTTP server implementation /// public class HttpServerResponseData - { + { /// /// Response code /// @@ -81,9 +81,9 @@ public HttpServerResponseData() /// Constructor /// /// Dictionary of headers - public HttpServerResponseData(IDictionary headers) + public HttpServerResponseData(IDictionary headers) : this(new byte[0], headers) - { + { } /// @@ -121,7 +121,7 @@ public HttpServerResponseData(byte[] body) /// Dictionary of headers public HttpServerResponseData(string body, IDictionary headers) : this(BinaryEncoding.Instance.GetBytes(body), headers) - { + { } /// diff --git a/CANAPE.Net.Templates/DnsServerTemplate.cs b/CANAPE.Net.Templates/DnsServerTemplate.cs index abc8db2..443c107 100644 --- a/CANAPE.Net.Templates/DnsServerTemplate.cs +++ b/CANAPE.Net.Templates/DnsServerTemplate.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using CANAPE.Net.Templates.Factories; using CANAPE.NodeLibrary.Server; using System.Net; diff --git a/CANAPE.Net.Templates/Factories/BaseNetworkLayerFactory.cs b/CANAPE.Net.Templates/Factories/BaseNetworkLayerFactory.cs index 191297b..079c19e 100644 --- a/CANAPE.Net.Templates/Factories/BaseNetworkLayerFactory.cs +++ b/CANAPE.Net.Templates/Factories/BaseNetworkLayerFactory.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using CANAPE.Net.Layers; using CANAPE.Utils; -using System; namespace CANAPE.Net.Templates.Factories { diff --git a/CANAPE.Net.Templates/Factories/BaseProxyClientFactory.cs b/CANAPE.Net.Templates/Factories/BaseProxyClientFactory.cs index e554afb..3779186 100644 --- a/CANAPE.Net.Templates/Factories/BaseProxyClientFactory.cs +++ b/CANAPE.Net.Templates/Factories/BaseProxyClientFactory.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using CANAPE.Net.Clients; using CANAPE.Utils; -using System; namespace CANAPE.Net.Templates.Factories { diff --git a/CANAPE.Net.Templates/Factories/IProxyListenerFactory.cs b/CANAPE.Net.Templates/Factories/IProxyListenerFactory.cs index abc85af..1897b8c 100644 --- a/CANAPE.Net.Templates/Factories/IProxyListenerFactory.cs +++ b/CANAPE.Net.Templates/Factories/IProxyListenerFactory.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using CANAPE.Net.Listeners; using CANAPE.Utils; -using System; namespace CANAPE.Net.Templates.Factories { diff --git a/CANAPE.Net.Templates/NetClientTemplate.cs b/CANAPE.Net.Templates/NetClientTemplate.cs index cc3f447..ddb17f8 100644 --- a/CANAPE.Net.Templates/NetClientTemplate.cs +++ b/CANAPE.Net.Templates/NetClientTemplate.cs @@ -15,11 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Sockets; using CANAPE.DataAdapters; using CANAPE.Net.Clients; using CANAPE.Net.Layers; @@ -27,6 +22,11 @@ using CANAPE.Net.Tokens; using CANAPE.Nodes; using CANAPE.Utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Sockets; namespace CANAPE.Net.Templates { diff --git a/CANAPE.Net.Templates/UnixSocketProxyTemplate.cs b/CANAPE.Net.Templates/UnixSocketProxyTemplate.cs index 1909b8e..8484c0a 100644 --- a/CANAPE.Net.Templates/UnixSocketProxyTemplate.cs +++ b/CANAPE.Net.Templates/UnixSocketProxyTemplate.cs @@ -136,7 +136,7 @@ public override ProxyNetworkService Create(Logger logger) { throw new NetServiceException(Properties.Resources.UnixSocketProxyTemplate_InvalidConnectPath); } - + try { var server = new PassThroughProxyServer(logger, Layers); diff --git a/CANAPE.Net/Clients/ChainProxyClient.cs b/CANAPE.Net/Clients/ChainProxyClient.cs index ac1fd20..c24363b 100644 --- a/CANAPE.Net/Clients/ChainProxyClient.cs +++ b/CANAPE.Net/Clients/ChainProxyClient.cs @@ -15,12 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; using CANAPE.Net.Tokens; using CANAPE.Nodes; -using CANAPE.Security; using CANAPE.Utils; +using System; namespace CANAPE.Net.Clients { @@ -38,7 +37,7 @@ public class ChainProxyClient : ProxyClient public ChainProxyClient(params ProxyClient[] clients) { if (clients == null) - { + { throw new ArgumentNullException("clients"); } @@ -46,7 +45,7 @@ public ChainProxyClient(params ProxyClient[] clients) { throw new ArgumentException(); } - + _clients = clients; } diff --git a/CANAPE.Net/Clients/FilteredIpProxyClient.cs b/CANAPE.Net/Clients/FilteredIpProxyClient.cs index 854ea6b..7749078 100644 --- a/CANAPE.Net/Clients/FilteredIpProxyClient.cs +++ b/CANAPE.Net/Clients/FilteredIpProxyClient.cs @@ -15,12 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Text.RegularExpressions; using CANAPE.DataAdapters; using CANAPE.Net.Tokens; using CANAPE.Nodes; -using CANAPE.Security; using CANAPE.Utils; +using System.Text.RegularExpressions; namespace CANAPE.Net.Clients { diff --git a/CANAPE.Net/Clients/FixedIpProxyClient.cs b/CANAPE.Net/Clients/FixedIpProxyClient.cs index b7f70af..e8915fb 100644 --- a/CANAPE.Net/Clients/FixedIpProxyClient.cs +++ b/CANAPE.Net/Clients/FixedIpProxyClient.cs @@ -15,12 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; using CANAPE.Net.Tokens; -using CANAPE.Utils; using CANAPE.Nodes; -using CANAPE.Security; +using CANAPE.Utils; namespace CANAPE.Net.Clients { @@ -41,7 +39,7 @@ public class FixedIpProxyClient : IpProxyClient /// The port to connect to /// The type of connection to make /// Indicates whether to use ipv6 - public FixedIpProxyClient(string hostname, int port, IpProxyToken.IpClientType clientType, bool ipv6) + public FixedIpProxyClient(string hostname, int port, IpProxyToken.IpClientType clientType, bool ipv6) { _hostname = hostname; _port = port; diff --git a/CANAPE.Net/Clients/FixedStreamSocketProxyClient.cs b/CANAPE.Net/Clients/FixedStreamSocketProxyClient.cs index 2f66a05..2b2dd28 100644 --- a/CANAPE.Net/Clients/FixedStreamSocketProxyClient.cs +++ b/CANAPE.Net/Clients/FixedStreamSocketProxyClient.cs @@ -56,7 +56,7 @@ public FixedStreamSocketProxyClient(EndPoint endPoint, ProtocolType protocolType /// /// /// - public override IDataAdapter Bind(ProxyToken token, Logger logger, MetaDictionary meta, + public override IDataAdapter Bind(ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties) { throw new NotImplementedException(); @@ -71,7 +71,7 @@ public override IDataAdapter Bind(ProxyToken token, Logger logger, MetaDictionar /// Global meta-data. /// Properties for the connection. /// The connected data adapater. - public override IDataAdapter Connect(ProxyToken token, Logger logger, + public override IDataAdapter Connect(ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties) { IDataAdapter adapter = null; diff --git a/CANAPE.Net/Clients/IpProxyClient.cs b/CANAPE.Net/Clients/IpProxyClient.cs index 79a0079..1fc8dec 100644 --- a/CANAPE.Net/Clients/IpProxyClient.cs +++ b/CANAPE.Net/Clients/IpProxyClient.cs @@ -15,16 +15,16 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.IO; -using System.Net.Sockets; using CANAPE.DataAdapters; +using CANAPE.Net.DataAdapters; using CANAPE.Net.Tokens; -using CANAPE.Utils; +using CANAPE.Net.Utils; using CANAPE.Nodes; +using CANAPE.Utils; +using System; +using System.IO; using System.Net; -using CANAPE.Net.Utils; -using CANAPE.Net.DataAdapters; +using System.Net.Sockets; namespace CANAPE.Net.Clients { diff --git a/CANAPE.Net/Clients/ProxyClient.cs b/CANAPE.Net/Clients/ProxyClient.cs index b069edc..53b29ab 100644 --- a/CANAPE.Net/Clients/ProxyClient.cs +++ b/CANAPE.Net/Clients/ProxyClient.cs @@ -17,9 +17,8 @@ // along with this program. If not, see . using CANAPE.DataAdapters; using CANAPE.Net.Tokens; -using CANAPE.Utils; using CANAPE.Nodes; -using CANAPE.Security; +using CANAPE.Utils; namespace CANAPE.Net.Clients { diff --git a/CANAPE.Net/Clients/SocksProxyClient.cs b/CANAPE.Net/Clients/SocksProxyClient.cs index 8582c74..4924d52 100644 --- a/CANAPE.Net/Clients/SocksProxyClient.cs +++ b/CANAPE.Net/Clients/SocksProxyClient.cs @@ -15,17 +15,17 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; +using CANAPE.Net.Tokens; +using CANAPE.Net.Utils; +using CANAPE.Nodes; +using CANAPE.Utils; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; -using CANAPE.DataAdapters; -using CANAPE.Net.Tokens; -using CANAPE.Utils; -using CANAPE.Nodes; -using CANAPE.Net.Utils; namespace CANAPE.Net.Clients { @@ -34,10 +34,10 @@ namespace CANAPE.Net.Clients /// public class SocksProxyClient : IpProxyClient { - private string _hostname; - private int _port; - private bool _ipv6; - private bool _sendHostName; + private string _hostname; + private int _port; + private bool _ipv6; + private bool _sendHostName; private SupportedVersion _version; /// @@ -97,8 +97,8 @@ private IPAddress GetAddressFromHost(string hostname, bool ipv6) } } } - - if(ret == null) + + if (ret == null) { throw new ArgumentException(CANAPE.Net.Properties.Resources.SocksProxyClient_CouldNotGetHost); } @@ -133,7 +133,7 @@ private void ConnectVersion4(Stream stm, IpProxyToken token, Logger logger) req[5] = addrbytes[1]; req[6] = addrbytes[2]; req[7] = addrbytes[3]; - + stm.Write(req, 0, req.Length); byte[] resp = GeneralUtils.ReadBytes(stm, 8); @@ -150,7 +150,7 @@ private void ConnectVersion4(Stream stm, IpProxyToken token, Logger logger) private void ConnectVersion4a(Stream stm, IpProxyToken token, Logger logger) { - byte[] req = new byte[9+token.Hostname.Length+1]; + byte[] req = new byte[9 + token.Hostname.Length + 1]; req[0] = 4; req[1] = 1; req[2] = (byte)(token.Port >> 8); @@ -198,7 +198,7 @@ private void ConnectVersion5(Stream stm, IpProxyToken token, Logger logger) connect.Add((byte)token.Hostname.Length); connect.AddRange(new BinaryEncoding().GetBytes(token.Hostname)); } - else if(token.Address != null) + else if (token.Address != null) { if (token.Address.AddressFamily == AddressFamily.InterNetwork) { @@ -214,7 +214,7 @@ private void ConnectVersion5(Stream stm, IpProxyToken token, Logger logger) } connect.AddRange(token.Address.GetAddressBytes()); - } + } else { throw new ArgumentException(CANAPE.Net.Properties.Resources.SocksProxyClient_InvalidProxyToken2); @@ -274,7 +274,7 @@ private void ConnectVersion5(Stream stm, IpProxyToken token, Logger logger) token.Status = NetStatusCodes.ConnectFailure; } } - + /// /// Connection to the socks server /// @@ -290,12 +290,12 @@ private void ConnectVersion5(Stream stm, IpProxyToken token, Logger logger) public override IDataAdapter Connect(ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties) { IDataAdapter ret = null; - + if (token is IpProxyToken) { IpProxyToken iptoken = token as IpProxyToken; TcpClient client = new TcpClient(); - + try { client.ConnectAsync(_hostname, _port).Wait(); diff --git a/CANAPE.Net/DataAdapters/BoundDataAdapter.cs b/CANAPE.Net/DataAdapters/BoundDataAdapter.cs index b6aa5f5..00ef097 100644 --- a/CANAPE.Net/DataAdapters/BoundDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/BoundDataAdapter.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; +using System; namespace CANAPE.Net.DataAdapters { @@ -45,7 +45,7 @@ public abstract class BoundDataAdapter : BaseDataAdapter /// Timeout in seconds public void Connect(int timeout) { - _boundAdapter = DoConnect(timeout); + _boundAdapter = DoConnect(timeout); } /// @@ -78,7 +78,7 @@ public override void Write(DataFrames.DataFrame data) { throw new InvalidOperationException(); } - } + } /// /// On dispose diff --git a/CANAPE.Net/DataAdapters/FixHttpConnectionDataAdapter.cs b/CANAPE.Net/DataAdapters/FixHttpConnectionDataAdapter.cs index acd3df9..06b0b99 100644 --- a/CANAPE.Net/DataAdapters/FixHttpConnectionDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/FixHttpConnectionDataAdapter.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.IO; using CANAPE.DataFrames; using CANAPE.Utils; +using System; +using System.IO; namespace CANAPE.DataAdapters { @@ -45,8 +45,8 @@ public FixHttpConnectionDataAdapter(IDataAdapter adapter) /// /// The data frame, null on end of file public DataFrame Read() - { - return _adapter.Read(); + { + return _adapter.Read(); } /// @@ -58,11 +58,11 @@ public void Write(DataFrame frame) if (!fixedConnection) { string s = BinaryEncoding.Instance.GetString(frame.ToArray()); - StringReader reader = new StringReader(s); + StringReader reader = new StringReader(s); string header = reader.ReadLine(); - while(header != null) - { + while (header != null) + { if (header.StartsWith("Connection:")) { s = s.Replace(header, "Connection: close"); @@ -70,7 +70,7 @@ public void Write(DataFrame frame) break; } else if (header.Length == 0) - { + { fixedConnection = true; break; } diff --git a/CANAPE.Net/DataAdapters/IpBoundDataAdapter.cs b/CANAPE.Net/DataAdapters/IpBoundDataAdapter.cs index 1f37755..4e2c84a 100644 --- a/CANAPE.Net/DataAdapters/IpBoundDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/IpBoundDataAdapter.cs @@ -15,11 +15,7 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; namespace CANAPE.Net.DataAdapters { diff --git a/CANAPE.Net/DataAdapters/StreamSocketDataAdapter.cs b/CANAPE.Net/DataAdapters/StreamSocketDataAdapter.cs index 1607762..6569d69 100644 --- a/CANAPE.Net/DataAdapters/StreamSocketDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/StreamSocketDataAdapter.cs @@ -30,7 +30,7 @@ public class StreamSocketDataAdapter : StreamDataAdapter /// /// The socket client. /// The description for the data adapter. - public StreamSocketDataAdapter(Socket client, string description) + public StreamSocketDataAdapter(Socket client, string description) : base(new NetworkStream(client, true), description) { } diff --git a/CANAPE.Net/DataAdapters/TcpClientDataAdapter.cs b/CANAPE.Net/DataAdapters/TcpClientDataAdapter.cs index a70f79a..a2d1eec 100644 --- a/CANAPE.Net/DataAdapters/TcpClientDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/TcpClientDataAdapter.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.Utils; using System; using System.Net.Sockets; -using CANAPE.Utils; namespace CANAPE.DataAdapters { @@ -25,7 +25,7 @@ namespace CANAPE.DataAdapters /// Data adapter for a TCP client object /// public class TcpClientDataAdapter : StreamDataAdapter - { + { TcpClient _clientSocket; /// diff --git a/CANAPE.Net/DataAdapters/TcpListenerDataAdapter.cs b/CANAPE.Net/DataAdapters/TcpListenerDataAdapter.cs index eae905f..832fd66 100644 --- a/CANAPE.Net/DataAdapters/TcpListenerDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/TcpListenerDataAdapter.cs @@ -15,11 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using CANAPE.DataAdapters; namespace CANAPE.Net.DataAdapters { @@ -76,7 +76,7 @@ protected override IDataAdapter DoConnect(int timeout) { ret = new TcpClientDataAdapter(_listener.AcceptTcpClientAsync().GetAwaiter().GetResult()); } - else + else { throw new TimeoutException(); } diff --git a/CANAPE.Net/DataAdapters/UdpClientDataAdapter.cs b/CANAPE.Net/DataAdapters/UdpClientDataAdapter.cs index ec867cc..12b0715 100644 --- a/CANAPE.Net/DataAdapters/UdpClientDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/UdpClientDataAdapter.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Net.Sockets; using CANAPE.DataFrames; +using System; using System.Net; +using System.Net.Sockets; namespace CANAPE.DataAdapters { diff --git a/CANAPE.Net/DataAdapters/UdpServerDataAdapter.cs b/CANAPE.Net/DataAdapters/UdpServerDataAdapter.cs index 8f6576e..328c9b0 100644 --- a/CANAPE.Net/DataAdapters/UdpServerDataAdapter.cs +++ b/CANAPE.Net/DataAdapters/UdpServerDataAdapter.cs @@ -15,11 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Net; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Net.Listeners; -using CANAPE.Utils; +using System.Net; namespace CANAPE.Net.DataAdapters { diff --git a/CANAPE.Net/Filters/IpProxyFilter.cs b/CANAPE.Net/Filters/IpProxyFilter.cs index 5269b00..d506368 100644 --- a/CANAPE.Net/Filters/IpProxyFilter.cs +++ b/CANAPE.Net/Filters/IpProxyFilter.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Text.RegularExpressions; using CANAPE.Net.Tokens; using CANAPE.Utils; +using System; +using System.Text.RegularExpressions; namespace CANAPE.Net.Filters { @@ -63,7 +63,7 @@ public override void Apply(ProxyToken token, Logger logger) IpProxyToken t = token as IpProxyToken; if (t != null) - { + { if (!String.IsNullOrWhiteSpace(RedirectAddress)) { t.Hostname = RedirectAddress; diff --git a/CANAPE.Net/Filters/LayerMergePolicy.cs b/CANAPE.Net/Filters/LayerMergePolicy.cs index e625b72..dade485 100644 --- a/CANAPE.Net/Filters/LayerMergePolicy.cs +++ b/CANAPE.Net/Filters/LayerMergePolicy.cs @@ -15,10 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace CANAPE.Net.Filters { diff --git a/CANAPE.Net/Filters/ProxyFilter.cs b/CANAPE.Net/Filters/ProxyFilter.cs index 17de921..ec95c61 100644 --- a/CANAPE.Net/Filters/ProxyFilter.cs +++ b/CANAPE.Net/Filters/ProxyFilter.cs @@ -15,14 +15,12 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; using CANAPE.Net.Clients; using CANAPE.Net.Layers; using CANAPE.Net.Tokens; using CANAPE.NodeFactories; using CANAPE.Utils; +using System.Collections.Generic; namespace CANAPE.Net.Filters { @@ -73,7 +71,7 @@ public class ProxyFilter /// public virtual bool Match(ProxyToken token) { - return token.Bind == Bound; + return token.Bind == Bound; } /// diff --git a/CANAPE.Net/Layers/BaseNetworkLayer.cs b/CANAPE.Net/Layers/BaseNetworkLayer.cs index 9133037..f28dd46 100644 --- a/CANAPE.Net/Layers/BaseNetworkLayer.cs +++ b/CANAPE.Net/Layers/BaseNetworkLayer.cs @@ -25,7 +25,7 @@ namespace CANAPE.Net.Layers /// ///Base network layer class, makes implementation slightly simpler /// - public abstract class BaseNetworkLayer : PersistNodeImpl, INetworkLayer where R : class where T : class, R, new() + public abstract class BaseNetworkLayer : PersistNodeImpl, INetworkLayer where R : class where T : class, R, new() { /// /// Proxy token for this connection @@ -76,7 +76,7 @@ namespace CANAPE.Net.Layers /// The assocaited global meta dictionary /// Property bag /// Default layer binding mode - public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, + public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties, NetworkLayerBinding defaultBinding) { Token = token; diff --git a/CANAPE.Net/Layers/DataParserNetworkLayer.cs b/CANAPE.Net/Layers/DataParserNetworkLayer.cs index c648281..4d9263f 100644 --- a/CANAPE.Net/Layers/DataParserNetworkLayer.cs +++ b/CANAPE.Net/Layers/DataParserNetworkLayer.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.IO; using CANAPE.DataFrames; using CANAPE.Utils; +using System.IO; namespace CANAPE.Net.Layers { @@ -118,7 +118,7 @@ protected sealed override DataFrame ClientRead() { return ReadInbound(new DataReader(_client_stream)); } - catch(EndOfStreamException) + catch (EndOfStreamException) { return null; } @@ -154,19 +154,19 @@ protected virtual bool NegotiateProtocol(Stream outboundStream, Stream inboundSt return true; } - /// - /// Negotiates the protocol. - /// - /// true, if protocol was negotiated, false otherwise. - /// Outbound stream. - /// Inbound stream. + /// + /// Negotiates the protocol. + /// + /// true, if protocol was negotiated, false otherwise. + /// Outbound stream. + /// Inbound stream. /// Binding. - protected virtual bool NegotiateProtocol(Stream outboundStream, - Stream inboundStream, + protected virtual bool NegotiateProtocol(Stream outboundStream, + Stream inboundStream, NetworkLayerBinding binding) - { + { return NegotiateProtocol(outboundStream, inboundStream); - } + } /// /// Ons the connect. @@ -225,7 +225,7 @@ protected override sealed DataFrame ServerRead() { return ReadOutbound(new DataReader(_server_stream)); } - catch(EndOfStreamException) + catch (EndOfStreamException) { return null; } diff --git a/CANAPE.Net/Layers/DynamicNetworkLayer.cs b/CANAPE.Net/Layers/DynamicNetworkLayer.cs index 9dc1319..96a26c9 100644 --- a/CANAPE.Net/Layers/DynamicNetworkLayer.cs +++ b/CANAPE.Net/Layers/DynamicNetworkLayer.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Collections.Generic; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Utils; +using System.Collections.Generic; namespace CANAPE.Net.Layers { @@ -157,9 +157,9 @@ protected override void ServerClose() /// /// protected override sealed bool OnConnect(IDataAdapter client, IDataAdapter server, NetworkLayerBinding binding) - { - _clientEnum = ReadClientFrames(client).GetEnumerator(); - _serverEnum = ReadServerFrames(server).GetEnumerator(); + { + _clientEnum = ReadClientFrames(client).GetEnumerator(); + _serverEnum = ReadServerFrames(server).GetEnumerator(); _client = client; _server = server; diff --git a/CANAPE.Net/Layers/DynamicStreamNetworkLayer.cs b/CANAPE.Net/Layers/DynamicStreamNetworkLayer.cs index da37c7a..8dd74bf 100644 --- a/CANAPE.Net/Layers/DynamicStreamNetworkLayer.cs +++ b/CANAPE.Net/Layers/DynamicStreamNetworkLayer.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.IO; using CANAPE.DataAdapters; using CANAPE.Utils; +using System.IO; namespace CANAPE.Net.Layers { @@ -25,7 +25,7 @@ namespace CANAPE.Net.Layers /// A network layer based on a streams /// public abstract class DynamicStreamNetworkLayer : WrappedNetworkLayer - { + { /// /// Method to implement for taking stream data /// diff --git a/CANAPE.Net/Layers/HttpLayerConfigEntry.cs b/CANAPE.Net/Layers/HttpLayerConfigEntry.cs index b4b4176..44738d9 100644 --- a/CANAPE.Net/Layers/HttpLayerConfigEntry.cs +++ b/CANAPE.Net/Layers/HttpLayerConfigEntry.cs @@ -52,25 +52,25 @@ public class HttpMatchEntry { private string _match; private MatchMode _mode; - private bool _ignoreCase; + private bool _ignoreCase; /// /// The match string /// - public string Match + public string Match { get { return _match; } set - { - _match = value ?? String.Empty; + { + _match = value ?? String.Empty; } } /// /// The mode of the match /// - public MatchMode Mode - { + public MatchMode Mode + { get { return _mode; } set { _mode = value; } } @@ -98,7 +98,7 @@ public HttpMatchEntry(string match, MatchMode mode) /// /// Constructor /// - public HttpMatchEntry() + public HttpMatchEntry() : this(String.Empty, MatchMode.None) { } @@ -126,7 +126,7 @@ public bool IsMatch(string value) case MatchMode.Regex: return new Regex(_match, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None).IsMatch(value); case MatchMode.Equal: - return value.Equals(_match, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + return value.Equals(_match, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); default: return true; } @@ -162,7 +162,7 @@ public class HttpLayerConfigEntry /// If true response body will be streamed rather than buffered up /// public bool ResponseStreamBody { get; set; } - + /// /// Convert HTTP/1.1 content-length format response to chunked encoding (for easier manipulation) /// Only applicable if StreamBody has been set, otherwise the entire body is buffered anyway @@ -202,12 +202,12 @@ public bool IsMatch(HttpRequestHeader request) /// public bool IsMatch(HttpRequestHeader request, HttpResponseHeader response) { - + if (IsMatch(request)) { foreach (var pair in response.Headers) { - if(pair.Name.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) + if (pair.Name.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) { return ContentTypeMatch.IsMatch(pair.Value); } diff --git a/CANAPE.Net/Layers/HttpNetworkLayer.cs b/CANAPE.Net/Layers/HttpNetworkLayer.cs index 646ec85..7ffe879 100644 --- a/CANAPE.Net/Layers/HttpNetworkLayer.cs +++ b/CANAPE.Net/Layers/HttpNetworkLayer.cs @@ -15,16 +15,16 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Net.Protocols.Parser; using CANAPE.Net.Tokens; using CANAPE.Nodes; using CANAPE.Utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; namespace CANAPE.Net.Layers { @@ -33,8 +33,8 @@ namespace CANAPE.Net.Layers /// public class HttpNetworkLayer : INetworkLayer { - private HttpNetworkLayerConfig _config; - private string _upgradeType; + private HttpNetworkLayerConfig _config; + private string _upgradeType; private bool _upgrading; /// @@ -42,7 +42,7 @@ public class HttpNetworkLayer : INetworkLayer /// public HttpNetworkLayer() : this(new HttpNetworkLayerConfig()) - { + { } /// @@ -51,24 +51,24 @@ public HttpNetworkLayer() /// Layer configuration public HttpNetworkLayer(HttpNetworkLayerConfig config) { - _config = config; - _upgradeType = null; + _config = config; + _upgradeType = null; } internal abstract class BaseHttpDataAdapter : BaseDataAdapter - { - private int _isDisposed; - protected Logger _logger; + { + private int _isDisposed; + protected Logger _logger; protected HttpNetworkLayer _layer; protected IDataAdapter _adapter; protected BaseHttpDataAdapter(IDataAdapter adapter, Logger logger, HttpNetworkLayer layer) { _adapter = adapter; - Description = _adapter.Description; + Description = _adapter.Description; _logger = logger; - _layer = layer; - } + _layer = layer; + } protected override void OnDispose(bool disposing) { @@ -125,8 +125,8 @@ internal sealed class HttpRequestDataAdapter : BaseHttpDataAdapter MemoryStream _responseStream = new MemoryStream(); bool _isTransparent; - public HttpRequestDataAdapter(IDataAdapter adapter, Logger logger, HttpNetworkLayer layer) - : base(adapter, logger,layer) + public HttpRequestDataAdapter(IDataAdapter adapter, Logger logger, HttpNetworkLayer layer) + : base(adapter, logger, layer) { _reader = new DataReader(adapter); } @@ -154,15 +154,15 @@ public override DataFrame Read() DataFrame frame = null; try - { + { if (_chunks == null || !_chunks.MoveNext()) - { + { char firstChar = _reader.ReadChar(); // Check whether we need to upgrade the connection to raw data, could even at this point actually implement // TLS upgrade (and put back the HTTP parser on top?) if (_isTransparent) - { + { // If transparent send the first chunk along and don't increment enumerator _chunks = BaseHttpDataAdapter.ReadFrames(new byte[] { (byte)firstChar }.ToDataFrame(), _reader).GetEnumerator(); } @@ -176,7 +176,7 @@ public override DataFrame Read() int i = 0; - while(i < _currentHeader.Headers.Count) + while (i < _currentHeader.Headers.Count) { var header = _currentHeader.Headers[i]; @@ -199,8 +199,8 @@ public override DataFrame Read() } _chunks = _currentHeader.ReadFrames(CreateConfig(_currentHeader)).GetEnumerator(); - } - + } + // Increment to next chunk if (!_chunks.MoveNext()) { @@ -210,7 +210,7 @@ public override DataFrame Read() frame = _chunks.Current; } - catch(EndOfStreamException) + catch (EndOfStreamException) { frame = null; } @@ -224,7 +224,7 @@ public override void Write(DataFrame data) if (!_isTransparent && _layer._upgrading) { // Wait for upgrade header - + byte[] buf = data.ToArray(); lock (_responseStream) @@ -259,15 +259,15 @@ public override void Write(DataFrame data) catch (HttpStreamParserException) { } - } + } } - - _adapter.Write(data); + + _adapter.Write(data); } } internal sealed class HttpResponseDataAdapter : BaseHttpDataAdapter - { + { HttpResponseHeader _currentHeader; IEnumerator _chunks; Queue _requests; @@ -288,10 +288,10 @@ private HttpParserConfig CreateConfig(HttpResponseHeader response, HttpRequestHe HttpLayerConfigEntry entry = _layer._config.GetEntry(request, response); - config.ConvertToChunked = entry.ConvertToChunked; + config.ConvertToChunked = entry.ConvertToChunked; config.StreamBody = entry.ResponseStreamBody; config.StreamChunkSize = _layer._config.ResponseStreamChunkSize; - config.StrictParsing = _layer._config.ResponseStrictParsing; + config.StrictParsing = _layer._config.ResponseStrictParsing; if (_layer._config.BufferedResponseMaxLength != 0 && (response.ContentLength > _layer._config.BufferedResponseMaxLength)) { @@ -307,7 +307,7 @@ public override DataFrame Read() DataFrame frame = null; try - { + { if (_chunks == null || !_chunks.MoveNext()) { if (_isTransparent) @@ -377,7 +377,7 @@ public override DataFrame Read() _chunks = _currentHeader.ReadFrames(CreateConfig(_currentHeader, request)).GetEnumerator(); } - + if (!_chunks.MoveNext()) { throw new EndOfStreamException(); @@ -393,9 +393,9 @@ public override DataFrame Read() return frame; } - + public override void Write(DataFrame frame) - { + { if (!_isTransparent) { var chunk = frame.GetValueNoThrow(); @@ -447,7 +447,7 @@ public override void Write(DataFrame frame) /// /// /// - public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, + public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties, NetworkLayerBinding defaultBinding) { if (defaultBinding == NetworkLayerBinding.Default) @@ -476,7 +476,7 @@ public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyTok /// public NetworkLayerBinding Binding { - get ; set; + get; set; } } } diff --git a/CANAPE.Net/Layers/HttpNetworkLayerConfig.cs b/CANAPE.Net/Layers/HttpNetworkLayerConfig.cs index 89f85e6..342b3d1 100644 --- a/CANAPE.Net/Layers/HttpNetworkLayerConfig.cs +++ b/CANAPE.Net/Layers/HttpNetworkLayerConfig.cs @@ -15,11 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using CANAPE.Net.Protocols.Parser; +using System; namespace CANAPE.Net.Layers { @@ -83,11 +80,11 @@ public class HttpNetworkLayerConfig public HttpNetworkLayerConfig() { ConfigEntries = new HttpLayerConfigEntry[0]; - DefaultEntry = new HttpLayerConfigEntry(); + DefaultEntry = new HttpLayerConfigEntry(); } private HttpLayerConfigEntry GetEntry(Func matcher) - { + { foreach (HttpLayerConfigEntry entry in ConfigEntries) { if (matcher(entry)) diff --git a/CANAPE.Net/Layers/INetworkLayer.cs b/CANAPE.Net/Layers/INetworkLayer.cs index d356cd7..f2baf0c 100644 --- a/CANAPE.Net/Layers/INetworkLayer.cs +++ b/CANAPE.Net/Layers/INetworkLayer.cs @@ -16,9 +16,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using CANAPE.DataAdapters; -using CANAPE.Utils; -using CANAPE.Nodes; using CANAPE.Net.Tokens; +using CANAPE.Nodes; +using CANAPE.Utils; namespace CANAPE.Net.Layers { @@ -38,7 +38,7 @@ public interface INetworkLayer /// Meta dictionary /// The property bag to add any connection information to /// Indicates the current default binding mode, layers are free to ignore (at their peril) - void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, + void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties, NetworkLayerBinding defaultBinding); /// diff --git a/CANAPE.Net/Layers/NetworkLayerFactoryExtensions.cs b/CANAPE.Net/Layers/NetworkLayerFactoryExtensions.cs index 429ad0f..e6258c2 100644 --- a/CANAPE.Net/Layers/NetworkLayerFactoryExtensions.cs +++ b/CANAPE.Net/Layers/NetworkLayerFactoryExtensions.cs @@ -15,11 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; +using CANAPE.Utils; using System.Collections.Generic; using System.Linq; -using System.Text; -using CANAPE.Utils; namespace CANAPE.Net.Layers { diff --git a/CANAPE.Net/Layers/TlsNetworkLayer.cs b/CANAPE.Net/Layers/TlsNetworkLayer.cs index cba5a76..182e90e 100644 --- a/CANAPE.Net/Layers/TlsNetworkLayer.cs +++ b/CANAPE.Net/Layers/TlsNetworkLayer.cs @@ -15,17 +15,17 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; +using CANAPE.Net.Tokens; +using CANAPE.Nodes; +using CANAPE.Security.Cryptography.X509Certificates; +using CANAPE.Utils; using System; using System.Collections.Concurrent; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; -using CANAPE.DataAdapters; -using CANAPE.Net.Tokens; -using CANAPE.Nodes; -using CANAPE.Security.Cryptography.X509Certificates; -using CANAPE.Utils; namespace CANAPE.Net.Layers { @@ -33,11 +33,11 @@ namespace CANAPE.Net.Layers /// A layer class to implement a SSL network /// public class TlsNetworkLayer : INetworkLayer - { + { TlsNetworkLayerConfig _config; X509Certificate _remoteCert; - - private static ConcurrentDictionary _certCache = + + private static ConcurrentDictionary _certCache = new ConcurrentDictionary(); /// @@ -93,7 +93,7 @@ SslPolicyErrors sslPolicyErrors private static int nameCounter = 0; private static void PopulateSslMeta(PropertyBag properties, SslStream stm) - { + { properties.AddValue("SslProtocol", stm.SslProtocol); properties.AddValue("IsSigned", stm.IsSigned); properties.AddValue("IsMutallyAuthenticated", stm.IsMutuallyAuthenticated); @@ -102,8 +102,8 @@ private static void PopulateSslMeta(PropertyBag properties, SslStream stm) properties.AddValue("CipherStrength", stm.CipherStrength); properties.AddValue("HashAlgorithm", stm.HashAlgorithm); properties.AddValue("HashStrength", stm.HashStrength); - - if(stm.LocalCertificate != null) + + if (stm.LocalCertificate != null) { properties.AddValue("LocalCertificate", stm.LocalCertificate); } @@ -121,7 +121,7 @@ private IDataAdapter ConnectClient(IDataAdapter adapter, Logger logger, Property SslStream sslStream = new SslStream(new DataAdapterToStream(adapter), false, ValidateRemoteClientConnection); if (serverName == null) - { + { // Just generate something serverName = Interlocked.Increment(ref nameCounter).ToString(); } @@ -130,7 +130,7 @@ private IDataAdapter ConnectClient(IDataAdapter adapter, Logger logger, Property bool setReadTimeout = false; int oldTimeout = -1; - foreach(X509Certificate2 clientCert in _config.ClientCertificates) + foreach (X509Certificate2 clientCert in _config.ClientCertificates) { clientCerts.Add(clientCert); } @@ -225,7 +225,7 @@ private IDataAdapter ConnectServer(IDataAdapter adapter, Logger logger, Property sslStream.ReadTimeout = oldTimeout; } - logger.LogVerbose(Properties.Resources.SslNetworkLayer_ClientLogString, + logger.LogVerbose(Properties.Resources.SslNetworkLayer_ClientLogString, sslStream.SslProtocol, sslStream.IsSigned, sslStream.IsMutuallyAuthenticated, sslStream.IsEncrypted); PopulateSslMeta(properties.AddBag("SslServer"), sslStream); @@ -244,7 +244,7 @@ private IDataAdapter ConnectServer(IDataAdapter adapter, Logger logger, Property /// /// /// - public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, + public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties, NetworkLayerBinding defaultBinding) { if (_config.Enabled) @@ -296,7 +296,7 @@ public void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyTok /// public NetworkLayerBinding Binding { - get; set; + get; set; } } } diff --git a/CANAPE.Net/Layers/TlsNetworkLayerConfig.cs b/CANAPE.Net/Layers/TlsNetworkLayerConfig.cs index 90baabd..120d1b5 100644 --- a/CANAPE.Net/Layers/TlsNetworkLayerConfig.cs +++ b/CANAPE.Net/Layers/TlsNetworkLayerConfig.cs @@ -105,7 +105,7 @@ public string ServerCertificateSubject /// Should default to false as this is for testing only /// public bool VerifyServerCertificate { get; set; } - + /// /// The client protocol, if SslProtocols.None then doesn't enable SSL /// diff --git a/CANAPE.Net/Layers/WrappedNetworkLayer.cs b/CANAPE.Net/Layers/WrappedNetworkLayer.cs index a9c91fd..45b7f52 100644 --- a/CANAPE.Net/Layers/WrappedNetworkLayer.cs +++ b/CANAPE.Net/Layers/WrappedNetworkLayer.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; using CANAPE.DataFrames; +using System; namespace CANAPE.Net.Layers { @@ -29,10 +29,10 @@ namespace CANAPE.Net.Layers public abstract class WrappedNetworkLayer : BaseNetworkLayer where R : class where T : class, R, new() - { + { private class WrapperServerDataAdapter : IDataAdapter { - WrappedNetworkLayer _networkLayer; + WrappedNetworkLayer _networkLayer; string _description; public WrapperServerDataAdapter(WrappedNetworkLayer networkLayer, string description) diff --git a/CANAPE.Net/Listeners/AggregateNetworkListener.cs b/CANAPE.Net/Listeners/AggregateNetworkListener.cs index 195cbc8..5a91ef1 100644 --- a/CANAPE.Net/Listeners/AggregateNetworkListener.cs +++ b/CANAPE.Net/Listeners/AggregateNetworkListener.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using System; using System.Collections.Generic; -using System.Text; namespace CANAPE.Net.Listeners { diff --git a/CANAPE.Net/Listeners/INetworkListener.cs b/CANAPE.Net/Listeners/INetworkListener.cs index 128afc7..50f2435 100644 --- a/CANAPE.Net/Listeners/INetworkListener.cs +++ b/CANAPE.Net/Listeners/INetworkListener.cs @@ -15,10 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; -using System.Collections.Generic; using CANAPE.Utils; +using System; namespace CANAPE.Net.Listeners { diff --git a/CANAPE.Net/Listeners/ManualNetworkListener.cs b/CANAPE.Net/Listeners/ManualNetworkListener.cs index fbcaf88..9ad4b2a 100644 --- a/CANAPE.Net/Listeners/ManualNetworkListener.cs +++ b/CANAPE.Net/Listeners/ManualNetworkListener.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; using CANAPE.Utils; +using System; namespace CANAPE.Net.Listeners { @@ -86,7 +86,7 @@ public void CreateConnection(IDataAdapter da) _logger.LogVerbose(Properties.Resources.ManualNetworkListener_CreateLogString); ClientConnected.Invoke(this, new ClientConnectedEventArgs(da)); - } + } } /// diff --git a/CANAPE.Net/Listeners/TcpNetworkListener.cs b/CANAPE.Net/Listeners/TcpNetworkListener.cs index 49e7d81..24fa4b0 100644 --- a/CANAPE.Net/Listeners/TcpNetworkListener.cs +++ b/CANAPE.Net/Listeners/TcpNetworkListener.cs @@ -15,13 +15,13 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; +using CANAPE.Net.Utils; +using CANAPE.Utils; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using CANAPE.DataAdapters; -using CANAPE.Net.Utils; -using CANAPE.Utils; using System.Threading.Tasks; namespace CANAPE.Net.Listeners diff --git a/CANAPE.Net/Listeners/UdpNetworkListener.cs b/CANAPE.Net/Listeners/UdpNetworkListener.cs index d2066dc..d5b2844 100644 --- a/CANAPE.Net/Listeners/UdpNetworkListener.cs +++ b/CANAPE.Net/Listeners/UdpNetworkListener.cs @@ -15,13 +15,13 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.Net.DataAdapters; +using CANAPE.Net.Utils; +using CANAPE.Utils; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using CANAPE.Net.DataAdapters; -using CANAPE.Utils; -using CANAPE.Net.Utils; using System.Threading.Tasks; namespace CANAPE.Net.Listeners diff --git a/CANAPE.Net/NetServiceException.cs b/CANAPE.Net/NetServiceException.cs index 60a7ba6..28c446e 100644 --- a/CANAPE.Net/NetServiceException.cs +++ b/CANAPE.Net/NetServiceException.cs @@ -29,7 +29,7 @@ public class NetServiceException : Exception /// public NetServiceException() : base() - { + { } /// @@ -38,7 +38,7 @@ public NetServiceException() /// Message public NetServiceException(string message) : base(message) - { + { } /// diff --git a/CANAPE.Net/PacketLogEventArgs.cs b/CANAPE.Net/PacketLogEventArgs.cs index 480f5f1..2329141 100644 --- a/CANAPE.Net/PacketLogEventArgs.cs +++ b/CANAPE.Net/PacketLogEventArgs.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; namespace CANAPE.Net { diff --git a/CANAPE.Net/Servers/FixedProxyServer.cs b/CANAPE.Net/Servers/FixedProxyServer.cs index 68af812..90fc7c6 100644 --- a/CANAPE.Net/Servers/FixedProxyServer.cs +++ b/CANAPE.Net/Servers/FixedProxyServer.cs @@ -15,13 +15,13 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Net; using CANAPE.DataAdapters; using CANAPE.Net.Layers; using CANAPE.Net.Tokens; using CANAPE.Nodes; using CANAPE.Utils; +using System; +using System.Net; namespace CANAPE.Net.Servers { @@ -35,7 +35,7 @@ private class FixedProxyToken : IpProxyToken public IDataAdapter Adapter { get; set; } public FixedProxyToken(IPAddress address, string hostname, int port, - IpClientType clientType, bool ipv6, IDataAdapter adapter) + IpClientType clientType, bool ipv6, IDataAdapter adapter) : base(address, hostname, port, clientType, ipv6) { Adapter = adapter; @@ -98,7 +98,7 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met public override IDataAdapter Complete(ProxyToken token, MetaDictionary meta, MetaDictionary globalMeta, ProxyNetworkService service, IDataAdapter client) { FixedProxyToken passToken = (FixedProxyToken)token; - + IDataAdapter adapter = passToken.Adapter; if (token.Status != NetStatusCodes.Success) { @@ -121,7 +121,7 @@ public override IDataAdapter Complete(ProxyToken token, MetaDictionary meta, Met /// /// /// - public FixedProxyServer(Logger logger, string hostName, int port, IpProxyToken.IpClientType clientType, + public FixedProxyServer(Logger logger, string hostName, int port, IpProxyToken.IpClientType clientType, bool ipv6, INetworkLayerFactory[] layers) : base(logger) { _hostName = hostName; diff --git a/CANAPE.Net/Servers/FullHttpProxyServer.cs b/CANAPE.Net/Servers/FullHttpProxyServer.cs index a644dbe..0d5a81d 100644 --- a/CANAPE.Net/Servers/FullHttpProxyServer.cs +++ b/CANAPE.Net/Servers/FullHttpProxyServer.cs @@ -15,11 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Net.Clients; @@ -29,8 +24,12 @@ using CANAPE.Net.Utils; using CANAPE.NodeFactories; using CANAPE.Nodes; -using CANAPE.Security; using CANAPE.Utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; namespace CANAPE.Net.Servers { @@ -49,8 +48,8 @@ public class FullHttpProxyServer : ProxyServer private const string DATA_NAME = "Data"; HttpProxyServerConfig _config; - NetGraphFactory _factory; - + NetGraphFactory _factory; + /// /// Constructor /// @@ -66,11 +65,11 @@ public FullHttpProxyServer(HttpProxyServerConfig config, Logger logger) ClientEndpointFactory client = builder.AddClient("Client", Guid.NewGuid()); ServerEndpointFactory server = builder.AddServer("Server", Guid.NewGuid()); - DirectNodeFactory nop = builder.AddNode(new DirectNodeFactory("NOP", Guid.NewGuid())); + DirectNodeFactory nop = builder.AddNode(new DirectNodeFactory("NOP", Guid.NewGuid())); builder.AddLines(client, nop, server, client); - _factory = builder.Factory; + _factory = builder.Factory; } /// @@ -78,7 +77,7 @@ public FullHttpProxyServer(HttpProxyServerConfig config, Logger logger) /// private class HttpProxyDataAdapter : CoupledDataAdapter { - public HttpProxyDataAdapter(Uri url, CancellationToken token) + public HttpProxyDataAdapter(Uri url, CancellationToken token) : base(token) { Url = url; @@ -94,10 +93,10 @@ class ProxyConnection { public NetGraph Graph { get; set; } public HttpProxyDataAdapter DataAdapter { get; set; } - public IEnumerable ResponseReader { get; set; } + public IEnumerable ResponseReader { get; set; } } - FullHttpProxyServer _server; + FullHttpProxyServer _server; LockedQueue _conns; List _graphs; Logger _logger; @@ -107,10 +106,10 @@ class ProxyConnection public HttpProxyClientDataAdapter(FullHttpProxyServer server, ProxyNetworkService service, Logger logger) { - _server = server; + _server = server; _service = service; _cancellationSource = new CancellationTokenSource(); - _conns = new LockedQueue(-1, _cancellationSource.Token); + _conns = new LockedQueue(-1, _cancellationSource.Token); _logger = logger; _graphs = new List(); Description = "HTTP Proxy Server"; @@ -143,7 +142,7 @@ private HttpResponseDataChunk BuildError(int error, string message, string metho return response; } - private IEnumerable GetResponse(ProxyConnection conn, Uri url, bool headRequest) + private IEnumerable GetResponse(ProxyConnection conn, Uri url, bool headRequest) { try { @@ -214,24 +213,24 @@ private IEnumerable GetResponse(ProxyConnection conn, Uri } } } - } + } protected override IEnumerable GetFrames() - { - ProxyConnection conn = _conns.Dequeue(); - + { + ProxyConnection conn = _conns.Dequeue(); + while (conn != null) { bool receivedFinal = false; - + foreach (HttpResponseDataChunk chunk in conn.ResponseReader) { receivedFinal = chunk.FinalChunk; yield return chunk.ToDataFrame(); } - + // If we didn't receive final chunk we have an error, start shutdown - if(!receivedFinal) + if (!receivedFinal) { _conns.Stop(); break; @@ -265,7 +264,7 @@ private NetGraph ConnectClient(IDataAdapter adapter) } break; - } + } } return graph; @@ -276,7 +275,7 @@ private NetGraph ConnectClient(IDataAdapter adapter) /// /// The frame to write. public override void Write(DataFrame frame) - { + { Uri currUri = null; var chunk = frame.GetValue().Clone(); @@ -315,7 +314,7 @@ public override void Write(DataFrame frame) } else { - _currOutConn.ResponseReader = GetResponse(_currOutConn, + _currOutConn.ResponseReader = GetResponse(_currOutConn, currUri, chunk.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)); _conns.Enqueue(_currOutConn); } @@ -335,9 +334,9 @@ public override void Write(DataFrame frame) } } } - + if (_currOutConn != null) - { + { DataWriter writer = new DataWriter(new DataAdapterToStream(_currOutConn.DataAdapter.Coupling)); chunk.WriteChunk(writer); @@ -414,12 +413,12 @@ public HttpProxyServerAdapter(FullHttpProxyServer server, DataAdapterToStream st _logger = logger; _requestQueue = new Queue(); _requestQueue.Enqueue(_request); - + Description = stm.Description; } private void ProcessProxyRequestHeaders(HttpRequestHeader request) - { + { int i = 0; // If we have a request for a client version which will close then ensure the job is done @@ -427,8 +426,8 @@ private void ProcessProxyRequestHeaders(HttpRequestHeader request) { _closeConnection = true; } - - while(i < request.Headers.Count) + + while (i < request.Headers.Count) { HttpHeader pair = request.Headers[i]; @@ -437,7 +436,7 @@ private void ProcessProxyRequestHeaders(HttpRequestHeader request) { request.Headers.RemoveAt(i); } - else if (pair.Name.Equals("Connection", StringComparison.OrdinalIgnoreCase) + else if (pair.Name.Equals("Connection", StringComparison.OrdinalIgnoreCase) || pair.Name.Equals("Proxy-Connection", StringComparison.OrdinalIgnoreCase)) { // If sender wants the connection close then signal it for next response @@ -446,7 +445,7 @@ private void ProcessProxyRequestHeaders(HttpRequestHeader request) _closeConnection = true; } - request.Headers.RemoveAt(i); + request.Headers.RemoveAt(i); } else { @@ -480,8 +479,8 @@ private void ProcessProxyResponseHeaders(HttpResponseDataChunk response) public override DataFrame Read() { try - { - if(_request == null) + { + if (_request == null) { _request = HttpParser.ReadRequestHeader(new DataReader(_stm), false, _logger); @@ -490,7 +489,7 @@ public override DataFrame Read() _requestQueue.Enqueue(_request); } - ProcessProxyRequestHeaders(_request); + ProcessProxyRequestHeaders(_request); } if (_chunks == null) @@ -536,7 +535,7 @@ private void Write(HttpResponseDataChunk chunk) chunk.Version = HttpVersion.Version10; } else - { + { chunk.Version = request.Version; } @@ -547,7 +546,7 @@ private void Write(HttpResponseDataChunk chunk) _closeConnection = true; } else - { + { // If not chunk encoding and no content-length then set close of end if (!chunk.ChunkedEncoding) { @@ -637,7 +636,7 @@ private void ReturnResponse(HttpRequestHeader request, int responseCode, string HttpResponseDataChunk response = new HttpResponseDataChunk(); - if(_config.Version10Proxy && !version.IsVersionUnknown) + if (_config.Version10Proxy && !version.IsVersionUnknown) { response.Version = HttpVersion.Version10; } @@ -647,7 +646,7 @@ private void ReturnResponse(HttpRequestHeader request, int responseCode, string } response.ResponseCode = responseCode; - response.Message = message; + response.Message = message; response.FinalChunk = true; response.Body = new byte[0]; @@ -663,10 +662,10 @@ private void ReturnResponse(HttpRequestHeader request, int responseCode, string response.Headers = headers.ToArray(); if (method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) - { + { response.HeadResponse = true; - } - else if(method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase)) + } + else if (method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase)) { response.ConnectResponse = true; } @@ -696,13 +695,13 @@ private IpProxyToken HandleConnect(HttpRequestHeader header, DataAdapterToStream if (port > 0) { ret = new IpProxyToken(null, hostName, port, IpProxyToken.IpClientType.Tcp, false); - + ret.State.Add("stm", stm); - ret.State.Add("header", header); + ret.State.Add("header", header); } else - { - ReturnResponse(null, 400, "Bad Request", header.Method, header.Version, stm); + { + ReturnResponse(null, 400, "Bad Request", header.Method, header.Version, stm); } } @@ -717,11 +716,11 @@ private ProxyToken HandleOtherRequest(HttpRequestHeader header, DataAdapterToStr { // Use generic token so filters don't get used ProxyToken ret = new ProxyToken(); - + ret.State.Add("url", url); ret.State.Add("stm", stm); ret.State.Add("header", header); - + ret.Client = new HttpProxyDummyClient(this, service); ret.Graph = _factory; @@ -732,7 +731,7 @@ private ProxyToken HandleOtherRequest(HttpRequestHeader header, DataAdapterToStr _logger.LogError(CANAPE.Net.Properties.Resources.HttpProxyServer_InvalidUrl, header.Path); // TODO: Put in some decent error codes - ReturnResponse(null, 400, "Bad Request", header.Method, header.Version, stm); + ReturnResponse(null, 400, "Bad Request", header.Method, header.Version, stm); return null; } @@ -764,7 +763,7 @@ private bool ProcessProxyAuth(HttpRequestHeader request) else { // Username case-insensitive, password case sensitive - ret = vs[0].Equals(_config.ProxyUsername, StringComparison.OrdinalIgnoreCase) + ret = vs[0].Equals(_config.ProxyUsername, StringComparison.OrdinalIgnoreCase) && _config.ProxyPassword.Equals(vs.Length > 1 ? vs[1] : String.Empty); } } @@ -808,23 +807,23 @@ private void FlushRequest(HttpRequestHeader request) private bool MustCloseConnection(HttpRequestHeader request) { - return request.Version.IsVersion10 - || request.Version.IsVersionUnknown - || _config.Version10Proxy - || request.Headers.HasHeader("Connection", "close") + return request.Version.IsVersion10 + || request.Version.IsVersionUnknown + || _config.Version10Proxy + || request.Headers.HasHeader("Connection", "close") || request.Headers.HasHeader("Proxy-Connection", "close"); } - + private bool HandleProxyAuthentication(DataReader reader, DataAdapterToStream stm, ref HttpRequestHeader request) { if (_config.RequireAuth) - { + { bool auth = ProcessProxyAuth(request); if (!auth) { ReturnResponse(request, 407, "Proxy Authentication Required", request.Method, request.Version, - new HttpHeader[] { new HttpHeader("Proxy-Authenticate", + new HttpHeader[] { new HttpHeader("Proxy-Authenticate", String.Format("Basic realm=\"{0}\"", _config.AuthRealm ?? "canape.local")) }, stm); if (!MustCloseConnection(request)) @@ -836,7 +835,7 @@ private bool HandleProxyAuthentication(DataReader reader, DataAdapterToStream st auth = ProcessProxyAuth(request); } } - + return auth; } else @@ -858,12 +857,12 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met ProxyToken token = null; if (_config.SslConfig.Enabled) - { + { IDataAdapter client = null; INetworkLayer ssl = new TlsNetworkLayer(_config.SslConfig); ssl.Negotiate(ref adapter, ref client, null, _logger, null, null, - new PropertyBag("Root"), NetworkLayerBinding.Server); + new PropertyBag("Root"), NetworkLayerBinding.Server); } if (adapter is HttpProxyDataAdapter) @@ -872,7 +871,7 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met token = new FullHttpProxyToken(proxyAdapter.Url.Host, proxyAdapter.Url.Port); - token.State.Add("adapter", adapter); + token.State.Add("adapter", adapter); } else { @@ -923,16 +922,16 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met /// public override IDataAdapter Complete(ProxyToken token, MetaDictionary meta, MetaDictionary globalMeta, ProxyNetworkService service, IDataAdapter client) { - IDataAdapter ret = null; - + IDataAdapter ret = null; + // An empty initial request indicates we are a full connection if (token.State.ContainsKey("header")) - { + { HttpRequestHeader initialRequest = (HttpRequestHeader)token.State["header"]; DataAdapterToStream stm = (DataAdapterToStream)token.State["stm"]; if (token.Status == NetStatusCodes.Success) - { + { if (initialRequest.IsConnect) { ReturnResponse(null, 200, "Connection established", initialRequest.Method, initialRequest.Version, stm); @@ -944,7 +943,7 @@ public override IDataAdapter Complete(ProxyToken token, MetaDictionary meta, Met { // Use a proxy adapter ret = new HttpProxyServerAdapter(this, stm, initialRequest, _logger); - } + } } else { diff --git a/CANAPE.Net/Servers/HttpProxyServerConfig.cs b/CANAPE.Net/Servers/HttpProxyServerConfig.cs index 8ed2c04..eb1d7d1 100644 --- a/CANAPE.Net/Servers/HttpProxyServerConfig.cs +++ b/CANAPE.Net/Servers/HttpProxyServerConfig.cs @@ -23,7 +23,7 @@ namespace CANAPE.Net.Servers /// Configuration for HTTP proxy /// public class HttpProxyServerConfig - { + { /// /// Gets or sets a value indicating whether this /// version10 proxy. diff --git a/CANAPE.Net/Servers/ReverseHttpProxyServer.cs b/CANAPE.Net/Servers/ReverseHttpProxyServer.cs index efbe06e..d6f2473 100644 --- a/CANAPE.Net/Servers/ReverseHttpProxyServer.cs +++ b/CANAPE.Net/Servers/ReverseHttpProxyServer.cs @@ -15,9 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.IO; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Net.Layers; @@ -25,6 +22,9 @@ using CANAPE.Net.Tokens; using CANAPE.Nodes; using CANAPE.Utils; +using System; +using System.Collections.Generic; +using System.IO; namespace CANAPE.Net.Servers { @@ -65,8 +65,8 @@ private void ReturnResponse(HttpRequestHeader request, int responseCode, string ReturnResponse(request, responseCode, message, method, version, new HttpHeader[0], stm); } - private void ReturnResponse(HttpRequestHeader request, int responseCode, string message, - string method, HttpVersion version, IEnumerable sendHeaders, + private void ReturnResponse(HttpRequestHeader request, int responseCode, string message, + string method, HttpVersion version, IEnumerable sendHeaders, DataAdapterToStream stm) { if (request != null) @@ -125,7 +125,7 @@ private Uri GetUri(string host, TcpClientDataAdapter tcpAdapter) // port = ((System.Net.IPEndPoint)tcpAdapter.Socket.Client.LocalEndPoint).Port; //} - if(!String.IsNullOrWhiteSpace(host)) + if (!String.IsNullOrWhiteSpace(host)) { try { @@ -143,7 +143,7 @@ private Uri GetUri(string host, TcpClientDataAdapter tcpAdapter) ret = new Uri("http://" + host); } } - catch(UriFormatException) + catch (UriFormatException) { } } @@ -163,19 +163,19 @@ private ProxyToken HandleOtherRequest(HttpRequestHeader header, DataAdapterToStr } } - Uri url = GetUri(host, tcpAdapter); + Uri url = GetUri(host, tcpAdapter); if (url != null) { // Use generic token so filters don't get used IpProxyToken ret = new IpProxyToken(null, url.Host, url.Port, IpProxyToken.IpClientType.Tcp, false); - if(_config.SslConfig.Enabled) + if (_config.SslConfig.Enabled) { ret.Layers = new INetworkLayer[1]; ret.Layers[0] = new TlsNetworkLayer(new TlsNetworkLayerConfig(false, true) { Enabled = true }); } - + ret.State.Add("url", url); ret.State.Add("stm", stm); ret.State.Add("header", header); @@ -185,7 +185,7 @@ private ProxyToken HandleOtherRequest(HttpRequestHeader header, DataAdapterToStr else { _logger.LogError(CANAPE.Net.Properties.Resources.HttpProxyServer_InvalidUrl, header.Path); - + ReturnResponse(null, 400, "Bad Request", header.Method, header.Version, stm); return null; @@ -201,7 +201,7 @@ private ProxyToken HandleOtherRequest(HttpRequestHeader header, DataAdapterToStr /// /// public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, MetaDictionary globalMeta, ProxyNetworkService service) - { + { ProxyToken token = null; TcpClientDataAdapter tcpAdapter = adapter as TcpClientDataAdapter; @@ -216,13 +216,13 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met } DataAdapterToStream stm = new DataAdapterToStream(adapter); - DataReader reader = new DataReader(stm); + DataReader reader = new DataReader(stm); try { HttpRequestHeader header = HttpParser.ReadRequestHeader(reader, false, _logger); - - token = HandleOtherRequest(header, stm, tcpAdapter); + + token = HandleOtherRequest(header, stm, tcpAdapter); } catch (HttpStreamParserException ex) { @@ -246,17 +246,17 @@ private class HttpProxyServerAdapter : BaseDataAdapter private HttpRequestHeader _request; private IEnumerator _chunks; private HttpParserConfig _config; - private Logger _logger; + private Logger _logger; public HttpProxyServerAdapter(DataAdapterToStream stm, HttpRequestHeader initialRequest, Logger logger) { _stm = stm; _writer = new DataWriter(_stm); - _request = initialRequest; + _request = initialRequest; _config = new HttpParserConfig(); _config.StreamBody = true; _logger = logger; - + Description = stm.Description; } @@ -266,7 +266,7 @@ public override DataFrame Read() { if (_request == null) { - _request = HttpParser.ReadRequestHeader(new DataReader(_stm), false, _logger); + _request = HttpParser.ReadRequestHeader(new DataReader(_stm), false, _logger); } if (_chunks == null) @@ -303,7 +303,7 @@ public override DataFrame Read() public override void Write(DataFrame data) { - _writer.WriteBytes(data.ToArray()); + _writer.WriteBytes(data.ToArray()); } protected override void OnDispose(bool disposing) diff --git a/CANAPE.Net/Servers/SocksProxyServer.cs b/CANAPE.Net/Servers/SocksProxyServer.cs index e3a1809..d1f3c09 100644 --- a/CANAPE.Net/Servers/SocksProxyServer.cs +++ b/CANAPE.Net/Servers/SocksProxyServer.cs @@ -15,15 +15,15 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; +using CANAPE.Net.Tokens; +using CANAPE.Nodes; +using CANAPE.Utils; using System; using System.IO; using System.Linq; using System.Net; using System.Text; -using CANAPE.DataAdapters; -using CANAPE.Net.Tokens; -using CANAPE.Utils; -using CANAPE.Nodes; namespace CANAPE.Net.Servers { @@ -36,7 +36,7 @@ public class SocksProxyServer : ProxyServer /// /// public enum SupportedVersion - { + { /// /// /// @@ -48,7 +48,7 @@ public enum SupportedVersion /// /// /// - Version5, + Version5, } /// @@ -67,9 +67,9 @@ public SocksProxyServer(Logger logger, SupportedVersion supportedVersion) : base /// public SocksProxyServer(Logger logger) : this(logger, SupportedVersion.All) - { + { } - + const byte REQUEST_SUCCEEDED = 0x5A; const byte REQUEST_FAILED = 0x5B; @@ -110,7 +110,7 @@ private string ReadZString(Stream stm) private ProxyToken HandleSocksv4Request(DataAdapterToStream stm) { - SocksProxyToken ret = null; + SocksProxyToken ret = null; int req = stm.ReadByte(); ushort port = ReadUShort(stm); @@ -119,7 +119,7 @@ private ProxyToken HandleSocksv4Request(DataAdapterToStream stm) string addrName = addr.ToString(); // Discard username - ReadZString(stm); + ReadZString(stm); if ((addrBytes[0] == 0) && (addrBytes[1] == 0) && (addrBytes[2] == 0) && (addrBytes[3] != 0)) { @@ -146,7 +146,7 @@ private IDataAdapter HandleSocksV4Response(SocksProxyToken token) stm.Write(resp, 0, resp.Length); - if(token.Status == NetStatusCodes.Success) + if (token.Status == NetStatusCodes.Success) { // Clear adapter value so it wont get disposed token.Adapter = null; @@ -178,14 +178,14 @@ private bool HandleV5Auth(DataAdapterToStream stm) byte[] ret = new byte[2]; - ret[0] = 5; + ret[0] = 5; if (foundAuth) { - ret[1] = 0; + ret[1] = 0; } else { - ret[1] = 0xFF; + ret[1] = 0xFF; } stm.Write(ret, 0, ret.Length); @@ -199,7 +199,7 @@ private ProxyToken HandleV5RequestData(DataAdapterToStream stm) IPAddress addr = null; string addrName = null; bool ipv6 = false; - ushort port = 0; + ushort port = 0; int ver = stm.ReadByte(); int code = stm.ReadByte(); @@ -216,7 +216,7 @@ private ProxyToken HandleV5RequestData(DataAdapterToStream stm) { data = GeneralUtils.ReadBytes(stm, 4); addr = new IPAddress(data); - addrName = addr.ToString(); + addrName = addr.ToString(); } break; case 3: // Domain name @@ -254,10 +254,10 @@ private ProxyToken HandleV5RequestData(DataAdapterToStream stm) private IDataAdapter HandleSocksV5Response(SocksProxyToken token) { DataAdapterToStream stm = token.Adapter; - byte[] returnData = new byte[10]; + byte[] returnData = new byte[10]; returnData[0] = 5; - if(token.Status == NetStatusCodes.Success) + if (token.Status == NetStatusCodes.Success) { returnData[1] = 0; } @@ -285,7 +285,7 @@ private IDataAdapter HandleSocksV5Response(SocksProxyToken token) } private ProxyToken HandleSocksv5Request(DataAdapterToStream stm) - { + { if (HandleV5Auth(stm)) { return HandleV5RequestData(stm); @@ -302,7 +302,7 @@ private bool IsSupported(int version) } else if ((version == 4) && (_supportedVersion == SupportedVersion.Version4)) { - return true; + return true; } else if ((version == 5) && (_supportedVersion == SupportedVersion.Version5)) { @@ -352,7 +352,7 @@ public override ProxyToken Accept(IDataAdapter adapter, MetaDictionary meta, Met return HandleConnectRequest(stm); } - + /// /// /// diff --git a/CANAPE.Net/Tokens/FullHttpProxyToken.cs b/CANAPE.Net/Tokens/FullHttpProxyToken.cs index 32b37df..97b4da6 100644 --- a/CANAPE.Net/Tokens/FullHttpProxyToken.cs +++ b/CANAPE.Net/Tokens/FullHttpProxyToken.cs @@ -15,16 +15,14 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using CANAPE.DataAdapters; -using CANAPE.Net.Protocols.Parser; namespace CANAPE.Net.Tokens { internal class FullHttpProxyToken : IpProxyToken - { + { public FullHttpProxyToken(string hostname, int port) : base(null, hostname, port, IpClientType.Tcp, false) - { + { } } } diff --git a/CANAPE.Net/Tokens/HttpProxyToken.cs b/CANAPE.Net/Tokens/HttpProxyToken.cs index a7991e7..3f0cc5a 100644 --- a/CANAPE.Net/Tokens/HttpProxyToken.cs +++ b/CANAPE.Net/Tokens/HttpProxyToken.cs @@ -15,10 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; -using CANAPE.Net.Protocols.Parser; using CANAPE.Utils; +using System; namespace CANAPE.Net.Tokens { @@ -41,7 +40,7 @@ internal class HttpProxyToken : IpProxyToken /// The original HTTP request headers (minus request line) /// public string[] Headers { get; private set; } - + /// /// The URL associated with this connection /// @@ -59,7 +58,7 @@ internal class HttpProxyToken : IpProxyToken public HttpProxyToken(string hostname, int port, bool connect, string[] headers, Uri url, DataAdapterToStream adapter) : base(null, hostname, port, IpClientType.Tcp, false) - { + { Connect = connect; Headers = headers; Url = url; diff --git a/CANAPE.Net/Tokens/IpProxyToken.cs b/CANAPE.Net/Tokens/IpProxyToken.cs index e431e55..c2ea168 100644 --- a/CANAPE.Net/Tokens/IpProxyToken.cs +++ b/CANAPE.Net/Tokens/IpProxyToken.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Net; using CANAPE.Utils; +using System.Net; namespace CANAPE.Net.Tokens { diff --git a/CANAPE.Net/Tokens/SocksProxyToken.cs b/CANAPE.Net/Tokens/SocksProxyToken.cs index 019c017..3b965aa 100644 --- a/CANAPE.Net/Tokens/SocksProxyToken.cs +++ b/CANAPE.Net/Tokens/SocksProxyToken.cs @@ -15,22 +15,22 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Net; using CANAPE.DataAdapters; using CANAPE.Utils; +using System; +using System.Net; namespace CANAPE.Net.Tokens -{ +{ internal class SocksProxyToken : IpProxyToken { public DataAdapterToStream Adapter { get; set; } public int Version { get; private set; } - public SocksProxyToken(IPAddress address, string hostname, - int port, IpClientType clientType, bool ipv6, - DataAdapterToStream adapter, int version) + public SocksProxyToken(IPAddress address, string hostname, + int port, IpClientType clientType, bool ipv6, + DataAdapterToStream adapter, int version) : base(address, hostname, port, clientType, ipv6) { Adapter = adapter; @@ -42,7 +42,7 @@ protected override void OnDispose(bool finalize) base.OnDispose(finalize); if (Adapter != null) - { + { try { Adapter.Dispose(); diff --git a/CANAPE.Net/Utils/ConnectionHistoryEntry.cs b/CANAPE.Net/Utils/ConnectionHistoryEntry.cs index 71f8767..ca33a00 100644 --- a/CANAPE.Net/Utils/ConnectionHistoryEntry.cs +++ b/CANAPE.Net/Utils/ConnectionHistoryEntry.cs @@ -17,9 +17,6 @@ // along with this program. If not, see . using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using CANAPE.Utils; namespace CANAPE.Net.Utils { diff --git a/CANAPE.Net/Utils/CredentialsEntry.cs b/CANAPE.Net/Utils/CredentialsEntry.cs index e1154c9..2f277b0 100644 --- a/CANAPE.Net/Utils/CredentialsEntry.cs +++ b/CANAPE.Net/Utils/CredentialsEntry.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; namespace CANAPE.Net.Templates { diff --git a/CANAPE.Net/Utils/LogPacketCollection.cs b/CANAPE.Net/Utils/LogPacketCollection.cs index c90522f..8970196 100644 --- a/CANAPE.Net/Utils/LogPacketCollection.cs +++ b/CANAPE.Net/Utils/LogPacketCollection.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.Utils; using System; using System.Collections.Generic; using System.Linq; -using CANAPE.Utils; namespace CANAPE.Net.Utils { @@ -43,14 +43,15 @@ public LogPacketCollection(IEnumerable packets) { } - private static bool EqualTag(LogPacket packet, string tag) { + private static bool EqualTag(LogPacket packet, string tag) + { if (packet.Tag == null) { return false; } return packet.Tag.Equals(tag, StringComparison.CurrentCultureIgnoreCase); } - + /// /// Get a list of packets for a tag name /// @@ -148,18 +149,19 @@ public void WriteToFile(string filename, Func predicate) /// /// Filename. /// Tag. - public void WriteToFile(string filename, string tag) { + public void WriteToFile(string filename, string tag) + { WriteToFile(filename, p => EqualTag(p, tag)); } - /// - /// Writes to file only a specific tag. - /// - /// Filename. - public void WriteToFile(string filename) - { - GeneralUtils.WritePacketsToFile(filename, this); - } + /// + /// Writes to file only a specific tag. + /// + /// Filename. + public void WriteToFile(string filename) + { + GeneralUtils.WritePacketsToFile(filename, this); + } /// /// Reads from file. diff --git a/CANAPE.Net/Utils/NetGraphBuilder.cs b/CANAPE.Net/Utils/NetGraphBuilder.cs index 290b7de..620187c 100644 --- a/CANAPE.Net/Utils/NetGraphBuilder.cs +++ b/CANAPE.Net/Utils/NetGraphBuilder.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; using CANAPE.NodeFactories; using CANAPE.Utils; +using System; +using System.Collections.Generic; namespace CANAPE.Net.Utils { diff --git a/CANAPE.Net/Utils/NetUtils.cs b/CANAPE.Net/Utils/NetUtils.cs index febc3f2..a842f4c 100644 --- a/CANAPE.Net/Utils/NetUtils.cs +++ b/CANAPE.Net/Utils/NetUtils.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.Utils; using System.Net; using System.Net.Sockets; -using CANAPE.Utils; namespace CANAPE.Net.Utils { @@ -31,7 +31,7 @@ private static void AddEndpoint(string name, EndPoint ep, PropertyBag properties IPEndPoint ip = ep as IPEndPoint; properties.AddValue(name, ep); - if(ip != null) + if (ip != null) { properties.AddValue(name + "Address", ip.Address); properties.AddValue(name + "Port", ip.Port); @@ -60,7 +60,7 @@ public static void PopulateBagFromSocket(Socket sock, PropertyBag properties) AddEndpoint("LocalEndpoint", sock.LocalEndPoint, properties); } - + /// /// Method to get whether OS supports IPv4 here for compatibility with Mono /// diff --git a/CANAPE.Security/CertificateBuilder.cs b/CANAPE.Security/CertificateBuilder.cs index f3f38ca..a3b3a63 100644 --- a/CANAPE.Security/CertificateBuilder.cs +++ b/CANAPE.Security/CertificateBuilder.cs @@ -98,7 +98,7 @@ public static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 { throw new ArgumentException("issuer"); } - + X509Name issuerNameObj = issuer == null ? X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)) : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData)); X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)); diff --git a/CANAPE.Security/CertificateUtils.cs b/CANAPE.Security/CertificateUtils.cs index c77bd1c..03a543e 100644 --- a/CANAPE.Security/CertificateUtils.cs +++ b/CANAPE.Security/CertificateUtils.cs @@ -191,7 +191,7 @@ public static string ExportPrivateKeyToPEM(this X509Certificate2 cert, string pa return swriter.ToString(); } - + /// /// Take an existing certificate, clone its details and resign with a new root CA /// @@ -228,7 +228,7 @@ public static X509Certificate2 CloneAndSignCertificate(X509Certificate toClone, /// public static X509Certificate2 CloneAndSignCertificate(X509Certificate toClone, X509Certificate2 rootCert, bool newSerial) { - return CloneAndSignCertificate(toClone, rootCert, + return CloneAndSignCertificate(toClone, rootCert, newSerial, 1024, CertificateHashAlgorithm.Sha1); } @@ -246,7 +246,7 @@ public static X509Certificate2 GenerateCACert(string subject, int rsaKeySize, Ce exts.Add(new X509BasicConstraintsExtension(true, false, 0, false)); - return CertificateBuilder.CreateCert(null, new X500DistinguishedName(subject), + return CertificateBuilder.CreateCert(null, new X500DistinguishedName(subject), null, rsaKeySize, hashAlgorithm, dt, dt.AddYears(10), exts); } @@ -259,7 +259,7 @@ public static X509Certificate2 GenerateCACert(string subject) { return GenerateCACert(subject, 1024, CertificateHashAlgorithm.Sha1); } - + /// /// Create a new certificate /// @@ -320,7 +320,7 @@ public static X509Certificate2 LoadCertFromOpenSslFile(string file) /// The certificate public static X509Certificate2 ImportFromPFX(string file, string password) { - return new X509Certificate2(File.ReadAllBytes(file), + return new X509Certificate2(File.ReadAllBytes(file), password, X509KeyStorageFlags.Exportable); } @@ -408,7 +408,7 @@ public static RSA ImportPrivateKeyFromPEM(string keyFile, string password, bool { throw new CryptographicException("Malformed ASN.1 Sequence"); } - + RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); keyParams = new RsaPrivateCrtKeyParameters( diff --git a/CANAPE/DataAdapters/BaseDataAdapter.cs b/CANAPE/DataAdapters/BaseDataAdapter.cs index fad9393..3e4808e 100644 --- a/CANAPE/DataAdapters/BaseDataAdapter.cs +++ b/CANAPE/DataAdapters/BaseDataAdapter.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataFrames; +using System; namespace CANAPE.DataAdapters { @@ -24,9 +24,9 @@ namespace CANAPE.DataAdapters /// Base class for DataAdapters /// public abstract class BaseDataAdapter : IDataAdapter - { + { private bool _isDisposed; - + #region IDataAdapter Members /// @@ -50,7 +50,7 @@ public abstract class BaseDataAdapter : IDataAdapter /// Get or set the read timeout /// /// Base version always throws InvalidOperationException - public virtual int ReadTimeout + public virtual int ReadTimeout { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } @@ -96,7 +96,7 @@ public virtual void Reconnect() { OnDispose(false); } - catch(Exception) + catch (Exception) { } } diff --git a/CANAPE/DataAdapters/CoupledDataAdapter.cs b/CANAPE/DataAdapters/CoupledDataAdapter.cs index bc3917f..f71119b 100644 --- a/CANAPE/DataAdapters/CoupledDataAdapter.cs +++ b/CANAPE/DataAdapters/CoupledDataAdapter.cs @@ -79,7 +79,7 @@ public override int ReadTimeout /// Constructor /// /// A cancellation token to use - public CoupledDataAdapter(CancellationToken token) + public CoupledDataAdapter(CancellationToken token) : base(token) { Coupling = new QueuingDataAdapter(this); @@ -88,7 +88,7 @@ public CoupledDataAdapter(CancellationToken token) /// /// Constructor /// - public CoupledDataAdapter() + public CoupledDataAdapter() : this(CancellationToken.None) { } diff --git a/CANAPE/DataAdapters/DataAdapterToStream.cs b/CANAPE/DataAdapters/DataAdapterToStream.cs index 182bb96..f03bf19 100644 --- a/CANAPE/DataAdapters/DataAdapterToStream.cs +++ b/CANAPE/DataAdapters/DataAdapterToStream.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataFrames; using System; using System.IO; -using CANAPE.DataFrames; namespace CANAPE.DataAdapters { @@ -28,7 +28,7 @@ public class DataAdapterToStream : Stream { private IDataAdapter _adapter; private byte[] _currBuf; - private int _currPos; + private int _currPos; private bool _endOfStream; /// @@ -108,7 +108,7 @@ private bool CheckDataAvailable() DataFrame frame = _adapter.Read(); byte[] buf = null; - if(frame != null) + if (frame != null) { buf = frame.ToArray(); } @@ -149,8 +149,8 @@ public override int Read(byte[] buffer, int offset, int count) int len = 0; if (!_endOfStream) - { - if(CheckDataAvailable()) + { + if (CheckDataAvailable()) { int left = _currBuf.Length - _currPos; len = left < count ? left : count; @@ -173,7 +173,7 @@ public override int ReadByte() if (!_endOfStream) { - if(CheckDataAvailable()) + if (CheckDataAvailable()) { ret = (int)_currBuf[_currPos++]; } diff --git a/CANAPE/DataAdapters/DelegateDataAdapter.cs b/CANAPE/DataAdapters/DelegateDataAdapter.cs index 06dd5e7..483cace 100644 --- a/CANAPE/DataAdapters/DelegateDataAdapter.cs +++ b/CANAPE/DataAdapters/DelegateDataAdapter.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataFrames; +using System; namespace CANAPE.DataAdapters { diff --git a/CANAPE/DataAdapters/EnumerableDataAdapter.cs b/CANAPE/DataAdapters/EnumerableDataAdapter.cs index 3a28d35..8fec68c 100644 --- a/CANAPE/DataAdapters/EnumerableDataAdapter.cs +++ b/CANAPE/DataAdapters/EnumerableDataAdapter.cs @@ -15,11 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using CANAPE.DataFrames; +using System.Collections.Generic; namespace CANAPE.DataAdapters { @@ -41,13 +38,13 @@ public abstract class EnumerableDataAdapter : BaseDataAdapter /// /// The frame, null on EOS public sealed override DataFrame Read() - { + { if (_enumerator == null) { _enumerator = GetFrames().GetEnumerator(); } - - if(_enumerator.MoveNext()) + + if (_enumerator.MoveNext()) { return _enumerator.Current; } diff --git a/CANAPE/DataAdapters/NullDataAdapter.cs b/CANAPE/DataAdapters/NullDataAdapter.cs index a9201aa..2ff72a6 100644 --- a/CANAPE/DataAdapters/NullDataAdapter.cs +++ b/CANAPE/DataAdapters/NullDataAdapter.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Threading; using CANAPE.DataFrames; +using System.Threading; namespace CANAPE.DataAdapters { @@ -63,7 +63,7 @@ public override void Write(DataFrame data) /// /// protected override void OnDispose(bool disposing) - { + { _exitEvent.Dispose(); } } diff --git a/CANAPE/DataAdapters/PrefixedDataAdapter.cs b/CANAPE/DataAdapters/PrefixedDataAdapter.cs index 735d0ee..0f5a4e1 100644 --- a/CANAPE/DataAdapters/PrefixedDataAdapter.cs +++ b/CANAPE/DataAdapters/PrefixedDataAdapter.cs @@ -16,8 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using CANAPE.DataFrames; -using System; -using CANAPE.Utils; namespace CANAPE.DataAdapters { diff --git a/CANAPE/DataAdapters/QueuedDataAdapter.cs b/CANAPE/DataAdapters/QueuedDataAdapter.cs index 4040df3..f57cb0a 100644 --- a/CANAPE/DataAdapters/QueuedDataAdapter.cs +++ b/CANAPE/DataAdapters/QueuedDataAdapter.cs @@ -15,11 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Threading; using CANAPE.DataFrames; using CANAPE.Utils; +using System; using System.IO; +using System.Threading; namespace CANAPE.DataAdapters { @@ -138,7 +138,7 @@ public DataFrame Dequeue() public DataFrame Dequeue(int readTimeout) { DataFrame ret = null; - + if (!_inputQueue.Dequeue(readTimeout, out ret)) { // Indicates that we hit a timeout, throw an IOException @@ -162,7 +162,7 @@ public override int ReadTimeout } set { - if((value < 0) && (value != Timeout.Infinite)) + if ((value < 0) && (value != Timeout.Infinite)) { throw new ArgumentOutOfRangeException(); } diff --git a/CANAPE/DataAdapters/StreamDataAdapter.cs b/CANAPE/DataAdapters/StreamDataAdapter.cs index f99c08f..70b8bbf 100644 --- a/CANAPE/DataAdapters/StreamDataAdapter.cs +++ b/CANAPE/DataAdapters/StreamDataAdapter.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.IO; using CANAPE.DataFrames; using CANAPE.Utils; +using System; +using System.IO; namespace CANAPE.DataAdapters { diff --git a/CANAPE/DataFrames/BasicDataFrameEqualityComparer.cs b/CANAPE/DataFrames/BasicDataFrameEqualityComparer.cs index 89cf19f..9e41dc5 100644 --- a/CANAPE/DataFrames/BasicDataFrameEqualityComparer.cs +++ b/CANAPE/DataFrames/BasicDataFrameEqualityComparer.cs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Collections.Generic; using CANAPE.Utils; +using System.Collections.Generic; namespace CANAPE.DataFrames { diff --git a/CANAPE/DataFrames/ByteArrayDataFrame.cs b/CANAPE/DataFrames/ByteArrayDataFrame.cs index 7d561b0..bdb3906 100644 --- a/CANAPE/DataFrames/ByteArrayDataFrame.cs +++ b/CANAPE/DataFrames/ByteArrayDataFrame.cs @@ -17,34 +17,34 @@ // along with this program. If not, see . namespace CANAPE.DataFrames { - /// - /// Byte array data frame. - /// - public sealed class ByteArrayDataFrame : DataFrame - { + /// + /// Byte array data frame. + /// + public sealed class ByteArrayDataFrame : DataFrame + { private byte[] _value; - /// - /// Initializes a new instance of the class. - /// - internal ByteArrayDataFrame() - : this(new byte[0]) - { - } + /// + /// Initializes a new instance of the class. + /// + internal ByteArrayDataFrame() + : this(new byte[0]) + { + } - /// - /// Initializes a new instance of the class. - /// - /// Data for frame - internal ByteArrayDataFrame(byte[] data) - { - _value = data; - } + /// + /// Initializes a new instance of the class. + /// + /// Data for frame + internal ByteArrayDataFrame(byte[] data) + { + _value = data; + } - private byte[] CloneData() - { - return (byte[])_value.Clone(); - } + private byte[] CloneData() + { + return (byte[])_value.Clone(); + } /// /// Gets the internal value. @@ -55,21 +55,21 @@ protected override object GetInternalValue() return _value; } - /// - /// Converts to a byte array - /// - /// The byte array. - public override byte[] ToArray() - { - return CloneData(); - } + /// + /// Converts to a byte array + /// + /// The byte array. + public override byte[] ToArray() + { + return CloneData(); + } - /// - /// Called on clone. - /// - protected override void OnClone() - { + /// + /// Called on clone. + /// + protected override void OnClone() + { _value = CloneData(); - } - } + } + } } diff --git a/CANAPE/DataFrames/ComplexDataFrame.cs b/CANAPE/DataFrames/ComplexDataFrame.cs index f78ed1c..7cb1fa7 100644 --- a/CANAPE/DataFrames/ComplexDataFrame.cs +++ b/CANAPE/DataFrames/ComplexDataFrame.cs @@ -15,55 +15,55 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.IO; using CANAPE.Utils; +using System.IO; namespace CANAPE.DataFrames { - /// - /// Complex data frame class. - /// - public sealed class ComplexDataFrame : DataFrame where T : IDataValue - { + /// + /// Complex data frame class. + /// + public sealed class ComplexDataFrame : DataFrame where T : IDataValue + { private T _value; - /// - /// Gets the internal value. - /// - /// The internal value. - protected override object GetInternalValue() - { - return _value; - } + /// + /// Gets the internal value. + /// + /// The internal value. + protected override object GetInternalValue() + { + return _value; + } - /// - /// Method called on clone - /// - protected override void OnClone() - { + /// + /// Method called on clone + /// + protected override void OnClone() + { _value = _value.Clone(); - } + } - /// - /// Convert the frame to a byte array - /// - // The data as an array - public override byte[] ToArray() - { - MemoryStream stm = new MemoryStream(); + /// + /// Convert the frame to a byte array + /// + // The data as an array + public override byte[] ToArray() + { + MemoryStream stm = new MemoryStream(); - _value.ToWriter(new DataWriter(stm)); + _value.ToWriter(new DataWriter(stm)); - return stm.ToArray(); - } + return stm.ToArray(); + } - /// - /// Constructor, creates a basic frame with a known root - /// - internal ComplexDataFrame(T value) - { - _value = value; - } + /// + /// Constructor, creates a basic frame with a known root + /// + internal ComplexDataFrame(T value) + { + _value = value; + } /// /// Returns a that represents the current . @@ -73,5 +73,5 @@ public override string ToString() { return _value.ToString(); } - } + } } diff --git a/CANAPE/DataFrames/DataFrame.cs b/CANAPE/DataFrames/DataFrame.cs index 3bb2f97..16e3529 100644 --- a/CANAPE/DataFrames/DataFrame.cs +++ b/CANAPE/DataFrames/DataFrame.cs @@ -73,21 +73,21 @@ public T GetValue() return (T)GetInternalValue(); } - /// - /// Gets the value but doesn't throw if not valid conversion. Instead returns + /// + /// Gets the value but doesn't throw if not valid conversion. Instead returns /// the default value for the type. - /// - /// The value. - /// The type of the value you want. - public T GetValueNoThrow() - { + /// + /// The value. + /// The type of the value you want. + public T GetValueNoThrow() + { object value = GetInternalValue(); if (value is T) { return (T)value; } return default(T); - } + } /// /// Convert the frame to a byte array @@ -115,7 +115,7 @@ private void UpdateData() catch { _length = 0; - _hash = ""; + _hash = ""; } } @@ -158,7 +158,7 @@ public long Length /// public override string ToString() { - return ToDataString(); + return ToDataString(); } } } diff --git a/CANAPE/DataFrames/DataFrameExtensions.cs b/CANAPE/DataFrames/DataFrameExtensions.cs index 2613db0..18892fb 100644 --- a/CANAPE/DataFrames/DataFrameExtensions.cs +++ b/CANAPE/DataFrames/DataFrameExtensions.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Collections.Generic; -using System.Text; using CANAPE.DataAdapters; using CANAPE.Utils; +using System.Collections.Generic; +using System.Text; namespace CANAPE.DataFrames { @@ -46,36 +46,36 @@ public static IEnumerable ReadFrames(this IDataAdapter adapter) - /// - /// Convert byte array to a data frame. - /// - /// The data frame. - /// The byte array to convert - public static DataFrame ToDataFrame(this byte[] data) - { - return new ByteArrayDataFrame(data); - } + /// + /// Convert byte array to a data frame. + /// + /// The data frame. + /// The byte array to convert + public static DataFrame ToDataFrame(this byte[] data) + { + return new ByteArrayDataFrame(data); + } - /// - /// Convert string a binary string data frame. - /// - /// The data frame. - /// The string to convert - public static DataFrame ToDataFrame(this string data) - { - return ToDataFrame(data, BinaryEncoding.Instance); - } + /// + /// Convert string a binary string data frame. + /// + /// The data frame. + /// The string to convert + public static DataFrame ToDataFrame(this string data) + { + return ToDataFrame(data, BinaryEncoding.Instance); + } - /// - /// Convert string a binary string data frame. - /// - /// The data frame. - /// The string to convert - /// The string encoding - public static DataFrame ToDataFrame(this string data, Encoding encoding) - { - return new StringDataFrame(data, encoding); - } + /// + /// Convert string a binary string data frame. + /// + /// The data frame. + /// The string to convert + /// The string encoding + public static DataFrame ToDataFrame(this string data, Encoding encoding) + { + return new StringDataFrame(data, encoding); + } /// /// Convert a data value to a frame. diff --git a/CANAPE/DataFrames/StringDataFrame.cs b/CANAPE/DataFrames/StringDataFrame.cs index 051d81b..6f58415 100644 --- a/CANAPE/DataFrames/StringDataFrame.cs +++ b/CANAPE/DataFrames/StringDataFrame.cs @@ -15,73 +15,73 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.Utils; using System; using System.Text; -using CANAPE.Utils; namespace CANAPE.DataFrames { - /// - /// String data frame. - /// - public sealed class StringDataFrame : DataFrame - { + /// + /// String data frame. + /// + public sealed class StringDataFrame : DataFrame + { private string _value; - private Encoding _encoding; + private Encoding _encoding; - /// - /// Gets the internal value. - /// - /// The internal value. - protected override object GetInternalValue() - { - return _value; - } + /// + /// Gets the internal value. + /// + /// The internal value. + protected override object GetInternalValue() + { + return _value; + } - /// - /// Initializes a new instance of the class. - /// - internal StringDataFrame() - : this(String.Empty, BinaryEncoding.Instance) - { - } + /// + /// Initializes a new instance of the class. + /// + internal StringDataFrame() + : this(String.Empty, BinaryEncoding.Instance) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The string value for Binary Encoding. - internal StringDataFrame(string value) - : this(value, BinaryEncoding.Instance) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The string value for Binary Encoding. + internal StringDataFrame(string value) + : this(value, BinaryEncoding.Instance) + { + } - /// - /// Initializes a new instance of the class. - /// - /// The string value. - /// Text encoding. - public StringDataFrame(string data, Encoding encoding) - { - _value = data; - _encoding = encoding; - } + /// + /// Initializes a new instance of the class. + /// + /// The string value. + /// Text encoding. + public StringDataFrame(string data, Encoding encoding) + { + _value = data; + _encoding = encoding; + } - /// - /// Convert to a data string. - /// - /// The data string. - public override string ToDataString() - { - return _value; - } + /// + /// Convert to a data string. + /// + /// The data string. + public override string ToDataString() + { + return _value; + } - /// - /// Converts to a byte array - /// - /// The byte array. - public override byte[] ToArray() - { - return _encoding.GetBytes(_value); - } - } + /// + /// Converts to a byte array + /// + /// The byte array. + public override byte[] ToArray() + { + return _encoding.GetBytes(_value); + } + } } diff --git a/CANAPE/NodeFactories/BaseNodeFactory.cs b/CANAPE/NodeFactories/BaseNodeFactory.cs index 7c09d7e..f8cbbf3 100644 --- a/CANAPE/NodeFactories/BaseNodeFactory.cs +++ b/CANAPE/NodeFactories/BaseNodeFactory.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; using CANAPE.Nodes; using CANAPE.Utils; +using System; +using System.Collections.Generic; namespace CANAPE.NodeFactories { @@ -26,7 +26,7 @@ namespace CANAPE.NodeFactories /// Base class for pipe node factories /// public abstract class BaseNodeFactory - { + { /// /// Id of the node /// diff --git a/CANAPE/NodeFactories/ClientEndpointFactory.cs b/CANAPE/NodeFactories/ClientEndpointFactory.cs index 50e76ec..928988e 100644 --- a/CANAPE/NodeFactories/ClientEndpointFactory.cs +++ b/CANAPE/NodeFactories/ClientEndpointFactory.cs @@ -29,7 +29,7 @@ public class ClientEndpointFactory : PipelineEndpointFactory /// /// /// - public ClientEndpointFactory(string label, Guid guid) + public ClientEndpointFactory(string label, Guid guid) : base(label, guid) { } diff --git a/CANAPE/NodeFactories/DelayNodeFactory.cs b/CANAPE/NodeFactories/DelayNodeFactory.cs index 2aa2bbc..f7290e1 100644 --- a/CANAPE/NodeFactories/DelayNodeFactory.cs +++ b/CANAPE/NodeFactories/DelayNodeFactory.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; using System.Collections.Generic; namespace CANAPE.NodeFactories diff --git a/CANAPE/NodeFactories/DirectNodeFactory.cs b/CANAPE/NodeFactories/DirectNodeFactory.cs index de03c63..b7b1f6e 100644 --- a/CANAPE/NodeFactories/DirectNodeFactory.cs +++ b/CANAPE/NodeFactories/DirectNodeFactory.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; using System.Collections.Generic; namespace CANAPE.NodeFactories @@ -41,7 +41,7 @@ public DirectNodeFactory(string label, Guid guid) /// The new instance protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary stateDictionary) { - DirectPipelineNode node = new DirectPipelineNode(); + DirectPipelineNode node = new DirectPipelineNode(); return node; } diff --git a/CANAPE/NodeFactories/EditPacketNodeFactory.cs b/CANAPE/NodeFactories/EditPacketNodeFactory.cs index b2b03d3..3b67222 100644 --- a/CANAPE/NodeFactories/EditPacketNodeFactory.cs +++ b/CANAPE/NodeFactories/EditPacketNodeFactory.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; using System.Collections.Generic; namespace CANAPE.NodeFactories @@ -26,7 +26,7 @@ namespace CANAPE.NodeFactories /// Factory to create an edit packet node /// public class EditPacketNodeFactory : BaseNodeFactory - { + { private ColorValue _color; private string _tag; @@ -39,7 +39,7 @@ public class EditPacketNodeFactory : BaseNodeFactory /// The textual tag to show in an edit window public EditPacketNodeFactory(string label, Guid guid, ColorValue color, string tag) : base(label, guid) - { + { _color = color; _tag = tag; } diff --git a/CANAPE/NodeFactories/LogPacketNodeFactory.cs b/CANAPE/NodeFactories/LogPacketNodeFactory.cs index ca604cb..3edaf16 100644 --- a/CANAPE/NodeFactories/LogPacketNodeFactory.cs +++ b/CANAPE/NodeFactories/LogPacketNodeFactory.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; using System.Collections.Generic; namespace CANAPE.NodeFactories @@ -67,7 +67,7 @@ protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dict node.Color = Color; node.ConvertToBytes = ConvertToBytes; - return node; + return node; } } } diff --git a/CANAPE/NodeFactories/NetGraphContainerNodeFactory.cs b/CANAPE/NodeFactories/NetGraphContainerNodeFactory.cs index 2767461..0f06a76 100644 --- a/CANAPE/NodeFactories/NetGraphContainerNodeFactory.cs +++ b/CANAPE/NodeFactories/NetGraphContainerNodeFactory.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; -using System.Collections.Generic; using CANAPE.Utils; +using System; +using System.Collections.Generic; namespace CANAPE.NodeFactories { @@ -31,7 +31,7 @@ public class NetGraphContainerNodeFactory : BaseNodeFactory /// The direction that this node should bind to /// public NetGraphContainerNode.GraphDirection Direction { get; set; } - + /// /// The graph factory to contain in this node /// @@ -70,7 +70,7 @@ protected override BasePipelineNode OnCreate(Logger logger, Nodes.NetGraph graph } // Check if we have already created this node as part of a pairing - if(stateDictionary.ContainsKey(Id.ToString())) + if (stateDictionary.ContainsKey(Id.ToString())) { return (BasePipelineNode)stateDictionary[Id.ToString()]; } diff --git a/CANAPE/NodeFactories/NetGraphFactory.cs b/CANAPE/NodeFactories/NetGraphFactory.cs index ce77fd4..ce52d20 100644 --- a/CANAPE/NodeFactories/NetGraphFactory.cs +++ b/CANAPE/NodeFactories/NetGraphFactory.cs @@ -72,7 +72,7 @@ public GraphNodeEntry(BaseNodeFactory factory) /// Default constructor /// public GraphNodeEntry() : this(null) - { + { } } @@ -127,7 +127,7 @@ public GraphLineEntry(Guid sourceNode, Guid destNode, bool biDirection, string p private Dictionary _props; private GraphNodeEntry[] _nodes; - private GraphLineEntry[] _lines; + private GraphLineEntry[] _lines; /// /// Default constructor @@ -141,8 +141,8 @@ public NetGraphFactory() Name = String.Empty; } - private static NetGraph CreateGraph(string name, Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, - IEnumerable nodes, IEnumerable lines, Dictionary props, PropertyBag connectionProperties, + private static NetGraph CreateGraph(string name, Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, + IEnumerable nodes, IEnumerable lines, Dictionary props, PropertyBag connectionProperties, Dictionary stateDictionary) { NetGraph netGraph = new NetGraph(logger, parent, globalMeta, meta, connectionProperties); @@ -170,7 +170,7 @@ private static NetGraph CreateGraph(string name, Logger logger, NetGraph parent, if (l.BiDirection) { - netGraph.Nodes[l.DestNode].AddOutput(netGraph.Nodes[l.SourceNode], l.PathName, l.WeakPath); + netGraph.Nodes[l.DestNode].AddOutput(netGraph.Nodes[l.SourceNode], l.PathName, l.WeakPath); } } @@ -185,7 +185,7 @@ private static NetGraph CreateGraph(string name, Logger logger, NetGraph parent, node.SetupShutdownOutputs(); } - + return netGraph; } @@ -206,13 +206,13 @@ public NetGraph CreateFiltered(string name, Logger logger, NetGraph parent, { Dictionary> forwardLines = new Dictionary>(); Dictionary> backwardLines = new Dictionary>(); - Dictionary nodesByGuid = new Dictionary(); + Dictionary nodesByGuid = new Dictionary(); List nodes = new List(); List lines = new List(); lock (_lockObject) { - foreach(GraphNodeEntry n in _nodes) + foreach (GraphNodeEntry n in _nodes) { nodesByGuid[n.Id] = n; } @@ -246,7 +246,7 @@ public NetGraph CreateFiltered(string name, Logger logger, NetGraph parent, forward.Add(l); backward.Add(l); } - + HashSet walkedNodes = new HashSet(); walkedNodes.Add(rootNode); @@ -329,9 +329,9 @@ public NetGraph CreateFiltered(string name, Logger logger, NetGraph parent, /// The constructed NetGraph public NetGraph Create(Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, PropertyBag connectionProperties) { - lock(_lockObject) + lock (_lockObject) { - return CreateGraph(Name, logger, parent, globalMeta, meta, _nodes, _lines, _props, connectionProperties, new Dictionary()); + return CreateGraph(Name, logger, parent, globalMeta, meta, _nodes, _lines, _props, connectionProperties, new Dictionary()); } } @@ -416,7 +416,7 @@ public GraphNodeEntry[] Nodes public GraphLineEntry[] Lines { get { return _lines; } - set + set { lock (_lockObject) { @@ -424,7 +424,7 @@ public GraphLineEntry[] Lines } } } - + /// /// Update the factory from another /// @@ -450,7 +450,7 @@ public void UpdateGraph(NetGraphFactory factory) public Dictionary Properties { get { return _props; } - set + set { lock (_lockObject) { diff --git a/CANAPE/NodeFactories/PipelineEndpointFactory.cs b/CANAPE/NodeFactories/PipelineEndpointFactory.cs index df0fd4e..4bdf72b 100644 --- a/CANAPE/NodeFactories/PipelineEndpointFactory.cs +++ b/CANAPE/NodeFactories/PipelineEndpointFactory.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.Nodes; using CANAPE.Utils; +using System; using System.Collections.Generic; namespace CANAPE.NodeFactories diff --git a/CANAPE/NodeFactories/ServerEndpointFactory.cs b/CANAPE/NodeFactories/ServerEndpointFactory.cs index f98eb99..d20e50e 100644 --- a/CANAPE/NodeFactories/ServerEndpointFactory.cs +++ b/CANAPE/NodeFactories/ServerEndpointFactory.cs @@ -31,6 +31,6 @@ public class ServerEndpointFactory : PipelineEndpointFactory public ServerEndpointFactory(string label, Guid guid) : base(label, guid) { - } + } } } diff --git a/CANAPE/Nodes/BaseDataEndpoint.cs b/CANAPE/Nodes/BaseDataEndpoint.cs index 4a8cf65..61b8ca0 100644 --- a/CANAPE/Nodes/BaseDataEndpoint.cs +++ b/CANAPE/Nodes/BaseDataEndpoint.cs @@ -22,7 +22,7 @@ namespace CANAPE.Nodes /// /// Base data endpoint. /// - public abstract class BaseDataEndpoint + public abstract class BaseDataEndpoint : BasePersistDataEndpoint where C : class, new() { /// diff --git a/CANAPE/Nodes/BaseDecoupledPipelineNode.cs b/CANAPE/Nodes/BaseDecoupledPipelineNode.cs index e575447..42d832a 100644 --- a/CANAPE/Nodes/BaseDecoupledPipelineNode.cs +++ b/CANAPE/Nodes/BaseDecoupledPipelineNode.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Threading; using CANAPE.DataFrames; using CANAPE.Utils; +using System; +using System.Threading; namespace CANAPE.Nodes { @@ -66,11 +66,11 @@ private void ReadThread() // Stop anything more arriving _input.Stop(); - + if (!_isDisposed) { ShutdownOutputs(); - } + } } private void EnsureThreadRunning() @@ -115,7 +115,7 @@ public override void Input(DataFrame frame) catch (OperationCanceledException) { } } - + /// /// Overidden dispose method /// diff --git a/CANAPE/Nodes/BasePersistDataEndpoint.cs b/CANAPE/Nodes/BasePersistDataEndpoint.cs index f590309..1c92578 100644 --- a/CANAPE/Nodes/BasePersistDataEndpoint.cs +++ b/CANAPE/Nodes/BasePersistDataEndpoint.cs @@ -21,7 +21,7 @@ namespace CANAPE.Nodes /// Base persist data endpoint with a single config type /// /// The type of configuration - public abstract class BasePersistDataEndpoint : BasePersistDataEndpointRef + public abstract class BasePersistDataEndpoint : BasePersistDataEndpointRef where T : class, new() { } diff --git a/CANAPE/Nodes/BasePersistDataEndpointRef.cs b/CANAPE/Nodes/BasePersistDataEndpointRef.cs index ca182a8..b0795de 100644 --- a/CANAPE/Nodes/BasePersistDataEndpointRef.cs +++ b/CANAPE/Nodes/BasePersistDataEndpointRef.cs @@ -66,7 +66,7 @@ public MetaDictionary GlobalMeta /// public Logger Logger { - get; set; + get; set; } #endregion diff --git a/CANAPE/Nodes/BasePipelineNode.cs b/CANAPE/Nodes/BasePipelineNode.cs index 7e64ed0..26a4c6f 100644 --- a/CANAPE/Nodes/BasePipelineNode.cs +++ b/CANAPE/Nodes/BasePipelineNode.cs @@ -15,14 +15,14 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataFrames; +using CANAPE.Utils; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; -using CANAPE.DataFrames; -using CANAPE.Utils; namespace CANAPE.Nodes { @@ -72,13 +72,13 @@ public OutputNode(BasePipelineNode node, string pathName, bool weak) private long _byteCount; private bool _breakpointHit; private int _isShutdown; - + /// /// A flag to indicate that the input mechanism should never write to the output /// if disabled, it should just discard it /// protected bool _noWriteOutput; - + /// /// The list of output nodes /// @@ -95,11 +95,11 @@ public OutputNode(BasePipelineNode node, string pathName, bool weak) public BasePipelineNode[] Outputs { get - { + { lock (_output) { return _output.Select(n => n.Node).ToArray(); - } + } } } @@ -109,7 +109,7 @@ internal void SetupShutdownOutputs() { if (!node.WeakPath) { - node.Node._shutdownInputs.Add(this.Uuid); + node.Node._shutdownInputs.Add(this.Uuid); } } } @@ -137,10 +137,10 @@ public virtual void Input(DataFrame frame) { OnInput(frame); } - else if(!_noWriteOutput) + else if (!_noWriteOutput) { WriteOutput(frame); - } + } } /// @@ -255,7 +255,7 @@ public void WriteOutput(byte[] ba) /// The frame to write /// Whether to include named outputs or just default public void WriteOutput(DataFrame frame, bool includeNamed) - { + { OutputNode[] nodes; if (includeNamed) @@ -280,7 +280,7 @@ private OutputNode[] GetNodesByName(string pathName) { lock (_output) { - return _output.FindAll(n => !String.IsNullOrWhiteSpace(n.PathName) + return _output.FindAll(n => !String.IsNullOrWhiteSpace(n.PathName) && n.PathName.Equals(pathName, StringComparison.OrdinalIgnoreCase)).ToArray(); ; } } @@ -319,7 +319,7 @@ private OutputNode[] GetNodesByNameExcluded(string[] pathNames) /// The frame to write /// The path name to write to public void WriteOutput(DataFrame frame, string pathName) - { + { WriteOutput(frame, GetNodesByName(pathName)); } @@ -340,7 +340,7 @@ public void WriteOutputExclude(DataFrame frame, params string[] pathNames) /// True if it has the named output public bool HasOutput(string pathName) { - return GetNodesByName(pathName).Length > 0; + return GetNodesByName(pathName).Length > 0; } /// @@ -451,7 +451,7 @@ protected virtual void ShutdownOutputs() { OutputNode[] nodes; - lock(_output) + lock (_output) { nodes = _output.ToArray(); } @@ -477,7 +477,7 @@ public virtual void Shutdown(BasePipelineNode inputNode) { bool doShutdown = false; - lock(_shutdownInputs) + lock (_shutdownInputs) { if (!IsShuttingdown) { @@ -496,14 +496,14 @@ public virtual void Shutdown(BasePipelineNode inputNode) } if (doShutdown) - { + { // If true is returned we can safely pass along the shutdown if (OnShutdown()) { ShutdownOutputs(); } } - } + } /// /// Indicates the node is shutdown @@ -635,7 +635,7 @@ public long ByteCount /// The args public void Log(Logger.LogEntryType entryType, string format, params object[] args) { - Graph.Logger.Log(entryType, Name, Uuid, format, args); + Graph.Logger.Log(entryType, Name, Uuid, format, args); } /// @@ -674,7 +674,7 @@ public void LogVerbose(object obj) /// The args public void LogInfo(string format, params object[] args) { - Log(Logger.LogEntryType.Info, format, args); + Log(Logger.LogEntryType.Info, format, args); } /// @@ -683,7 +683,7 @@ public void LogInfo(string format, params object[] args) /// The object to log public void LogInfo(object obj) { - Log(Logger.LogEntryType.Info, obj); + Log(Logger.LogEntryType.Info, obj); } /// @@ -693,7 +693,7 @@ public void LogInfo(object obj) /// The args public void LogWarning(string format, params object[] args) { - Log(Logger.LogEntryType.Warning, format, args); + Log(Logger.LogEntryType.Warning, format, args); } /// diff --git a/CANAPE/Nodes/BaseStreamPipelineNode.cs b/CANAPE/Nodes/BaseStreamPipelineNode.cs index 7b729ba..a77781d 100644 --- a/CANAPE/Nodes/BaseStreamPipelineNode.cs +++ b/CANAPE/Nodes/BaseStreamPipelineNode.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Threading; using CANAPE.DataFrames; using CANAPE.Utils; using System; +using System.Threading; namespace CANAPE.Nodes { @@ -26,7 +26,7 @@ namespace CANAPE.Nodes /// Pipeline node which converts incoming data frames into a stream /// public abstract class BaseStreamPipelineNode : BasePipelineNode - { + { private PipelineStream _input; private object _lockObject; private Thread _thread; @@ -81,7 +81,7 @@ private void EnsureThreadRunning() protected override bool OnShutdown() { try - { + { _input.Enqueue(null); } catch (InvalidOperationException) @@ -134,7 +134,7 @@ protected override void Dispose(bool disposing) } catch { - } + } } } } diff --git a/CANAPE/Nodes/DataEndpointAdapter.cs b/CANAPE/Nodes/DataEndpointAdapter.cs index e59ba48..e76afbd 100644 --- a/CANAPE/Nodes/DataEndpointAdapter.cs +++ b/CANAPE/Nodes/DataEndpointAdapter.cs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using CANAPE.DataAdapters; -using CANAPE.Nodes; using CANAPE.Utils; using System; using System.IO; @@ -45,7 +44,7 @@ public DataEndpointAdapter(IDataEndpoint server, Logger logger) this.Description = server.Description; _thread = new Thread(StartEndpoint); - _thread.IsBackground = true; + _thread.IsBackground = true; } /// @@ -85,6 +84,6 @@ private void StartEndpoint() } this.Coupling.Dispose(); - } + } } } diff --git a/CANAPE/Nodes/DelayPipelineNode.cs b/CANAPE/Nodes/DelayPipelineNode.cs index b431191..4ae0ab1 100644 --- a/CANAPE/Nodes/DelayPipelineNode.cs +++ b/CANAPE/Nodes/DelayPipelineNode.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System.Threading; using CANAPE.DataFrames; +using System.Threading; namespace CANAPE.Nodes { diff --git a/CANAPE/Nodes/DirectPipelineNode.cs b/CANAPE/Nodes/DirectPipelineNode.cs index dde4f7d..e4a28b3 100644 --- a/CANAPE/Nodes/DirectPipelineNode.cs +++ b/CANAPE/Nodes/DirectPipelineNode.cs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using CANAPE.DataFrames; -using System.Threading; namespace CANAPE.Nodes { @@ -24,14 +23,14 @@ namespace CANAPE.Nodes /// Simple node which writes input to output with no processing /// public class DirectPipelineNode : BasePipelineNode - { + { /// /// Called when a new frame arrives (just forwards) /// /// protected override void OnInput(DataFrame frame) - { - WriteOutput(frame); + { + WriteOutput(frame); } } } diff --git a/CANAPE/Nodes/EditPacketPipelineNode.cs b/CANAPE/Nodes/EditPacketPipelineNode.cs index a300e30..82f8ecf 100644 --- a/CANAPE/Nodes/EditPacketPipelineNode.cs +++ b/CANAPE/Nodes/EditPacketPipelineNode.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataFrames; using CANAPE.Utils; +using System; namespace CANAPE.Nodes { @@ -53,7 +53,7 @@ public class EditPacketEventArgs : EventArgs /// The sending node /// The colour to show in an edit window /// The textual tag to show in an edit window - public EditPacketEventArgs(DataFrame frame, + public EditPacketEventArgs(DataFrame frame, BasePipelineNode sender, ColorValue color, string tag) { Frame = frame; @@ -77,7 +77,7 @@ public class EditPacketPipelineNode : BasePipelineNode /// The colour to show in an edit window /// The textual tag to show in an edit window public EditPacketPipelineNode(ColorValue color, string tag) - { + { _color = color; _tag = tag; } @@ -89,7 +89,7 @@ public EditPacketPipelineNode(ColorValue color, string tag) protected override void OnInput(DataFrame frame) { frame = EditPacket(frame, _color, _tag); - + if (frame != null) { WriteOutput(frame); diff --git a/CANAPE/Nodes/IPersistNode.cs b/CANAPE/Nodes/IPersistNode.cs index 7470ecb..e846837 100644 --- a/CANAPE/Nodes/IPersistNode.cs +++ b/CANAPE/Nodes/IPersistNode.cs @@ -15,10 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using CANAPE.Utils; namespace CANAPE.Nodes @@ -41,6 +37,6 @@ public interface IPersistNode /// /// The state object /// The logger to use - void SetState(object state, Logger logger); + void SetState(object state, Logger logger); } } diff --git a/CANAPE/Nodes/IPipelineEndpoint.cs b/CANAPE/Nodes/IPipelineEndpoint.cs index 6e9fb8f..eba853d 100644 --- a/CANAPE/Nodes/IPipelineEndpoint.cs +++ b/CANAPE/Nodes/IPipelineEndpoint.cs @@ -15,8 +15,8 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataAdapters; +using System; namespace CANAPE.Nodes { @@ -29,7 +29,7 @@ public interface IPipelineEndpoint /// Get or set the data adapter /// IDataAdapter Adapter { get; set; } - + /// /// Start the node /// diff --git a/CANAPE/Nodes/LogPacketPipelineNode.cs b/CANAPE/Nodes/LogPacketPipelineNode.cs index 49a4d67..2e5c4e9 100644 --- a/CANAPE/Nodes/LogPacketPipelineNode.cs +++ b/CANAPE/Nodes/LogPacketPipelineNode.cs @@ -15,9 +15,9 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using CANAPE.DataFrames; using CANAPE.Utils; +using System; namespace CANAPE.Nodes { @@ -79,7 +79,7 @@ public LogPacketEventArgs(string tag, Guid netId, DataFrame frame, ColorValue co /// Log packet pipeline node /// public class LogPacketPipelineNode : BasePipelineNode - { + { /// /// Color of the log entry /// @@ -94,16 +94,16 @@ public class LogPacketPipelineNode : BasePipelineNode /// If true then all logged frames will be converted to bytes /// public bool ConvertToBytes { get; set; } - + /// /// OnInput method /// /// protected override void OnInput(DataFrame frame) - { + { Graph.DoLogPacket(String.IsNullOrWhiteSpace(Tag) ? Name : Tag, Color, frame, ConvertToBytes); - - WriteOutput(frame); + + WriteOutput(frame); } } diff --git a/CANAPE/Nodes/MetaDictionary.cs b/CANAPE/Nodes/MetaDictionary.cs index ee609f6..ca82611 100644 --- a/CANAPE/Nodes/MetaDictionary.cs +++ b/CANAPE/Nodes/MetaDictionary.cs @@ -53,7 +53,7 @@ public MetaDictionary(MetaDictionary dict) private dynamic GetMetaInternal(string name, dynamic defaultValue) { - dynamic ret = null; + dynamic ret = null; if (!TryGetValue(name, out ret)) { @@ -67,7 +67,7 @@ private dynamic GetMetaInternal(string name, dynamic defaultValue) } private void SetMetaInternal(string name, dynamic value) - { + { if (value != null) { this[name] = value; diff --git a/CANAPE/Nodes/NetGraph.cs b/CANAPE/Nodes/NetGraph.cs index 0da9ead..87eed32 100644 --- a/CANAPE/Nodes/NetGraph.cs +++ b/CANAPE/Nodes/NetGraph.cs @@ -15,12 +15,12 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Utils; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; using System.Threading; namespace CANAPE.Nodes @@ -109,7 +109,7 @@ public sealed class NetGraph : IDisposable /// An event which indicates the graph has been shutdown /// public event EventHandler GraphShutdown; - + /// /// Default constructor /// @@ -159,7 +159,7 @@ public NetGraph(Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaD } #region Meta Data Handling - + /// /// Get a meta value from the public scope /// @@ -263,7 +263,7 @@ public void SetGlobalMeta(string name, dynamic obj, bool privateScope) { string fullName = privateScope ? GeneralUtils.MakePrivateMetaName(Uuid, name) : name; - GlobalMeta.SetMeta(fullName, obj); + GlobalMeta.SetMeta(fullName, obj); } /// @@ -360,7 +360,7 @@ public int GetGlobalCounter(string name, int defaultValue, bool privateScope) { string fullName = privateScope ? GeneralUtils.MakePrivateMetaName(Uuid, name) : name; - return GlobalMeta.GetCounter(fullName, defaultValue); + return GlobalMeta.GetCounter(fullName, defaultValue); } /// @@ -371,7 +371,7 @@ public int GetGlobalCounter(string name, int defaultValue, bool privateScope) /// The current value of the counter public int GetGlobalCounter(string name, int defaultValue) { - return GlobalMeta.GetCounter(name, defaultValue); + return GlobalMeta.GetCounter(name, defaultValue); } /// @@ -417,7 +417,7 @@ public void SetGlobalCounter(string name, int value, bool privateScope) /// The value of the counter public void SetGlobalCounter(string name, int value) { - GlobalMeta.SetCounter(name, value); + GlobalMeta.SetCounter(name, value); } /// @@ -434,7 +434,7 @@ public string GetProperty(string name) if (!Properties.TryGetValue(name, out ret)) { ret = null; - } + } } return ret; @@ -461,7 +461,7 @@ public void SetProperty(string name, string value) } } -#endregion + #endregion /// /// Get a node by name @@ -538,7 +538,7 @@ public bool IsDisposed /// Check if shutdown, all nodes with an inbound connection must be shutdown /// public bool CheckShutdown() - { + { bool ret = true; if (!_isDisposed && _graphShutdown == 0) @@ -555,7 +555,7 @@ public bool CheckShutdown() } } } - + foreach (KeyValuePair pair in Nodes) { if (!pair.Value.IsShutdown && referencedNodes.Contains(pair.Value.Uuid)) @@ -653,12 +653,12 @@ private void OnLogPacket(string tag, ColorValue color, DataFrame frame, bool log if (logPacketEvent != null) { - DataFrame logFrame = logAsBytes ? new ByteArrayDataFrame(frame.ToArray()) + DataFrame logFrame = logAsBytes ? new ByteArrayDataFrame(frame.ToArray()) : frame.Clone(); - - logPacketEvent(this, new LogPacketEventArgs(tag, Uuid, - logFrame, - color, + + logPacketEvent(this, new LogPacketEventArgs(tag, Uuid, + logFrame, + color, NetworkDescription)); } } @@ -703,7 +703,7 @@ public DataFrame DoEditPacket(DataFrame frame, BasePipelineNode sender, ColorVal /// public void Start() { - foreach(var pair in Nodes) + foreach (var pair in Nodes) { try { @@ -731,7 +731,7 @@ public override string ToString() #region IDisposable Members void IDisposable.Dispose() - { + { if (!_isDisposed) { try diff --git a/CANAPE/Nodes/NetGraphContainerNode.cs b/CANAPE/Nodes/NetGraphContainerNode.cs index d334bcc..1158ff1 100644 --- a/CANAPE/Nodes/NetGraphContainerNode.cs +++ b/CANAPE/Nodes/NetGraphContainerNode.cs @@ -15,12 +15,12 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.Collections.Generic; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.NodeFactories; using CANAPE.Utils; +using System; +using System.Collections.Generic; namespace CANAPE.Nodes { @@ -47,7 +47,7 @@ public enum GraphDirection private class EventDataAdapter : IDataAdapter { - NetGraphContainerNode _container; + NetGraphContainerNode _container; bool _isClosed; public EventDataAdapter(NetGraphContainerNode container) @@ -63,7 +63,7 @@ public DataFrame Read() } public void Write(DataFrame frame) - { + { _container.WriteOutput(frame); } @@ -172,8 +172,8 @@ public NetGraphContainerNode(NetGraphContainerNode linkedNode, Logger logger) /// The logger to use /// Forwarded state dictionary /// If true then we are creating a linked master node - public NetGraphContainerNode(string name, NetGraphFactory factory, - GraphDirection direction, NetGraph containerGraph, Logger logger, + public NetGraphContainerNode(string name, NetGraphFactory factory, + GraphDirection direction, NetGraph containerGraph, Logger logger, Dictionary stateDictionary, bool linked) { var clients = factory.GetNodes(); @@ -181,9 +181,9 @@ public NetGraphContainerNode(string name, NetGraphFactory factory, if ((clients.Length > 0) && (servers.Length > 0)) { - Guid outputNode = direction == GraphDirection.ClientToServer + Guid outputNode = direction == GraphDirection.ClientToServer ? servers[0].Id : clients[0].Id; - Guid inputNode = direction == GraphDirection.ClientToServer + Guid inputNode = direction == GraphDirection.ClientToServer ? clients[0].Id : servers[0].Id; if (linked) @@ -197,7 +197,7 @@ public NetGraphContainerNode(string name, NetGraphFactory factory, containerGraph.Meta, inputNode, containerGraph.ConnectionProperties, stateDictionary); } - _graph.BindEndpoint(outputNode, new EventDataAdapter(this)); + _graph.BindEndpoint(outputNode, new EventDataAdapter(this)); _inputNode = (PipelineEndpoint)_graph.Nodes[inputNode]; _inputNode.Hidden = true; diff --git a/CANAPE/Nodes/PipelineEndpoint.cs b/CANAPE/Nodes/PipelineEndpoint.cs index 107fc11..8c8d670 100644 --- a/CANAPE/Nodes/PipelineEndpoint.cs +++ b/CANAPE/Nodes/PipelineEndpoint.cs @@ -38,7 +38,7 @@ public class PipelineEndpoint : BasePipelineNode, IPipelineEndpoint public PipelineEndpoint() { _noWriteOutput = true; - } + } /// /// Allows the reading of frames to be overriden @@ -66,7 +66,7 @@ protected virtual DataFrame ReadDataFrame() done = false; } } - } + } } while (!done); @@ -195,7 +195,7 @@ protected override bool OnShutdown() { Logger.SystemLogger.LogException(ex); } - + return shutdown; } @@ -219,9 +219,9 @@ protected override void Dispose(bool disposing) } } catch - { - } - + { + } + _thread = null; } } diff --git a/CANAPE/Utils/BinaryEncoding.cs b/CANAPE/Utils/BinaryEncoding.cs index 8e1f7c9..29b78ac 100644 --- a/CANAPE/Utils/BinaryEncoding.cs +++ b/CANAPE/Utils/BinaryEncoding.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; using System.Text; namespace CANAPE.Utils @@ -24,7 +23,7 @@ namespace CANAPE.Utils /// Encoding class to convert to and from binary data /// public sealed class BinaryEncoding : Encoding - { + { private bool _encodeControl; /// @@ -32,8 +31,8 @@ public sealed class BinaryEncoding : Encoding /// public static readonly BinaryEncoding Instance = new BinaryEncoding(); - static char[] BinaryMapTable = { '\x2302', '\x263a', '\x263b', '\x2665', '\x2666', '\x2663', '\x2660', '\x2022', '\x25d8', '\x25cb', '\x25d9', '\x2642', '\x2640', - '\x266a', '\x266b', '\x263c', '\x25ba', '\x25c4', '\x2195', '\x203c', '\x2591', '\x2593', '\x25ac', '\x21a8', '\x2191', '\x2193', + static char[] BinaryMapTable = { '\x2302', '\x263a', '\x263b', '\x2665', '\x2666', '\x2663', '\x2660', '\x2022', '\x25d8', '\x25cb', '\x25d9', '\x2642', '\x2640', + '\x266a', '\x266b', '\x263c', '\x25ba', '\x25c4', '\x2195', '\x203c', '\x2591', '\x2593', '\x25ac', '\x21a8', '\x2191', '\x2193', '\x2192', '\x2190', '\x221f', '\x2194', '\x25b2', '\x25bc'}; /// @@ -41,14 +40,14 @@ public sealed class BinaryEncoding : Encoding /// public BinaryEncoding() : this(false) - { + { } /// /// Constructor /// /// Indicates control characters are changed - public BinaryEncoding(bool encodeControl) + public BinaryEncoding(bool encodeControl) { _encodeControl = encodeControl; } @@ -97,16 +96,16 @@ public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] { int j = 0; - for(j = 0; j < 32; ++j) + for (j = 0; j < 32; ++j) { - if(BinaryMapTable[j] == c) + if (BinaryMapTable[j] == c) { bytes[byteIndex + i] = (byte)j; break; } } - if(j == 32) + if (j == 32) { bytes[byteIndex + i] = (byte)c; } @@ -139,7 +138,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) { return count; } - + /// /// /// @@ -155,7 +154,7 @@ public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] { for (int i = 0; i < byteCount; ++i) { - byte b = bytes[byteIndex = i]; + byte b = bytes[byteIndex = i]; if ((b < 32) && (b != 10) && (b != 13) && (b != 9)) { diff --git a/CANAPE/Utils/ColorValue.cs b/CANAPE/Utils/ColorValue.cs index 8f6dd8c..17d827e 100644 --- a/CANAPE/Utils/ColorValue.cs +++ b/CANAPE/Utils/ColorValue.cs @@ -64,7 +64,7 @@ public ColorValue(byte r, byte g, byte b, byte a) /// Red value /// Green value /// Blue value - public ColorValue(byte r, byte g, byte b) + public ColorValue(byte r, byte g, byte b) : this(r, g, b, 255) { } @@ -93,7 +93,7 @@ ColorValue right ColorValue left, ColorValue right ) - { + { return !(left == right); } @@ -104,7 +104,7 @@ ColorValue right /// public override bool Equals(object obj) { - if(obj is ColorValue) + if (obj is ColorValue) { return this == (ColorValue)obj; } @@ -143,7 +143,7 @@ private static bool FindColor(string name, out ColorValue cv) foreach (PropertyInfo pi in typeof(ColorValue).GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Static)) { if (pi.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) - { + { cv = (ColorValue)pi.GetValue(null, null); return true; @@ -171,7 +171,7 @@ public override string ToString() private static bool ParseHex(string s, int index, out byte v) { - return byte.TryParse(s.Substring(index+1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out v); + return byte.TryParse(s.Substring(index + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out v); } /// diff --git a/CANAPE/Utils/DataReader.cs b/CANAPE/Utils/DataReader.cs index b8491a0..41e0f27 100644 --- a/CANAPE/Utils/DataReader.cs +++ b/CANAPE/Utils/DataReader.cs @@ -19,8 +19,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; using System.Reflection; +using System.Text; namespace CANAPE.Utils { @@ -51,9 +51,9 @@ public DataReader(Stream stm) /// Constructor /// /// Byte data to read - public DataReader(byte[] data) + public DataReader(byte[] data) : this(new MemoryStream(data)) - { + { } /// @@ -78,7 +78,7 @@ public byte[] ReadBytes(int len, bool waitForAll, bool throwOnEof) int currLen = 0; if (_eof) - { + { throw new EndOfStreamException(); } @@ -98,7 +98,7 @@ public byte[] ReadBytes(int len, bool waitForAll, bool throwOnEof) _eof = true; break; } - + if (readLen < nextLen) { Array.Resize(ref arr, readLen); @@ -191,7 +191,7 @@ public byte[] ReadToEnd(int chunkSize) byte[] arr = null; int currLength = chunkSize; - while(currLength > 0) + while (currLength > 0) { arr = ReadBytes(currLength, false, false); @@ -204,7 +204,7 @@ public byte[] ReadToEnd(int chunkSize) { break; } - } + } return ret.ToArray(); } @@ -244,7 +244,7 @@ private void ResetStreamTrail(byte[] data) /// The number of trailing characters or bytes /// The read bytes public byte[] ReadToEndTrail(int trail) - { + { byte[] ret = ReadToEnd(); if (trail > 0) @@ -266,7 +266,7 @@ public byte[] ReadToEndTrail(int trail) ResetStreamTrail(t); } - return ret; + return ret; } /// @@ -277,7 +277,7 @@ public byte[] ReadToEndTrail(int trail) /// The number of trailing characters or bytes /// The read string public string ReadToEndTrail(Encoding encoding, int trail) - { + { string s = ReadToEnd(encoding); if (trail > 0) @@ -298,7 +298,7 @@ public string ReadToEndTrail(Encoding encoding, int trail) ResetStreamTrail(encoding.GetBytes(t)); } - return s; + return s; } /// @@ -319,9 +319,9 @@ public char ReadChar(Encoding encoding) for (int i = 0; i < data.Length; ++i) { data[i] = ReadByte(); - if (encoding.GetCharCount(data, 0, i+1) == 1) + if (encoding.GetCharCount(data, 0, i + 1) == 1) { - return encoding.GetChars(data, 0, i+1)[0]; + return encoding.GetChars(data, 0, i + 1)[0]; } } } @@ -348,7 +348,7 @@ public char ReadChar() public string ReadString(int len, bool waitForAll, Encoding encoding) { if (encoding.IsSingleByte) - { + { // We can do it more simply for single byte encoded data return encoding.GetString(ReadBytes(len, waitForAll)); } @@ -384,7 +384,7 @@ public string ReadString(int len, bool waitForAll, Encoding encoding) /// The read string public string ReadString(int len, bool waitForAll) { - return ReadString(len, waitForAll, new BinaryEncoding()); + return ReadString(len, waitForAll, new BinaryEncoding()); } /// @@ -517,16 +517,16 @@ public string ReadLine(Encoding encoding, TextLineEnding lineEnding, int maxLeng break; } - if(currChar == '\n') + if (currChar == '\n') { - if(lineEnding == TextLineEnding.LineFeed) + if (lineEnding == TextLineEnding.LineFeed) { break; } - else if((lineEnding == TextLineEnding.CarriageReturnLineFeed) && hasCr) + else if ((lineEnding == TextLineEnding.CarriageReturnLineFeed) && hasCr) { break; - } + } } else if (currChar == '\r') { @@ -579,7 +579,7 @@ public byte ReadByte() _eof = true; throw new EndOfStreamException(); } - + return (byte)currByte; } @@ -587,7 +587,7 @@ public byte ReadByte() /// Flush out any pending bits /// public void Flush() - { + { _validBits = 0; } @@ -730,7 +730,7 @@ public ulong ReadUInt64() { return ReadUInt64(false); } - + /// /// Read a long from the stream with a specified endian /// @@ -764,7 +764,7 @@ public Int24 ReadInt24(bool littleEndian) for (int i = 0; i < 3; ++i) { - data[i+ofs] = ReadByte(); + data[i + ofs] = ReadByte(); } // Sign the value @@ -840,7 +840,7 @@ public float ReadFloat(bool littleEndian) { byte[] data = ReadBytes(4); - return BitConverter.ToSingle(GeneralUtils.SwapBytes(data, littleEndian), 0); + return BitConverter.ToSingle(GeneralUtils.SwapBytes(data, littleEndian), 0); } /// @@ -948,7 +948,7 @@ public object ReadPrimitive(Type t, bool littleEndian) } return ret; - } + } /// /// Get the underlying stream object @@ -959,7 +959,7 @@ public Stream GetStream() // Clear bits, we cannot ever be certain this won't do harm _validBits = 0; return _stm; - } + } /// /// Gets the number of bytes left in the stream, -1 if not supported @@ -969,7 +969,7 @@ public long DataLeft get { try - { + { return _stm.Length - _stm.Position; } catch (NotSupportedException) @@ -1042,7 +1042,7 @@ public ulong ReadBits(int count) /// /// Specifies how many bytes have been read since the last time the state was cleared /// - public long ByteCount + public long ByteCount { get { diff --git a/CANAPE/Utils/DataWriter.cs b/CANAPE/Utils/DataWriter.cs index a8bdb74..609d059 100644 --- a/CANAPE/Utils/DataWriter.cs +++ b/CANAPE/Utils/DataWriter.cs @@ -15,11 +15,11 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . +using CANAPE.DataAdapters; using System; using System.IO; -using System.Text; using System.Reflection; -using CANAPE.DataAdapters; +using System.Text; namespace CANAPE.Utils { @@ -53,10 +53,10 @@ public DataWriter() /// Initializes a new instance of the class. /// /// The data adapter - public DataWriter(IDataAdapter adapter) + public DataWriter(IDataAdapter adapter) : this(new DataAdapterToStream(adapter)) { - + } /// @@ -109,7 +109,7 @@ public void WriteByte(byte b) /// /// The signed byte to write public void WriteSByte(sbyte sb) - { + { sbyte[] sbs = new sbyte[] { sb }; Flush(); @@ -134,7 +134,7 @@ public void WriteInt16(short s) { WriteInt16(s, false); } - + /// /// Write a 32bit integer to the stream /// @@ -246,7 +246,7 @@ public void WriteInt24(Int24 i, bool littleEndian) else { WriteBytes(data, 1, 3); - } + } } /// @@ -265,7 +265,7 @@ public void WriteUInt24(UInt24 i, bool littleEndian) else { WriteBytes(data, 1, 3); - } + } } /// @@ -387,7 +387,7 @@ public void WriteString(string str, BinaryStringEncoding encoding) /// /// The binary encoded string public void WriteString(string str) - { + { WriteString(str, BinaryEncoding.Instance); } @@ -441,7 +441,7 @@ public void WriteLine(string line, Encoding encoding, TextLineEnding lineEnding) break; case TextLineEnding.CarriageReturnLineFeed: lineEndingString = "\r\n"; - break; + break; } WriteString(line, encoding); @@ -705,23 +705,23 @@ public void WritePrimitive(object value, Type t, bool littleEndian) } else if (t == typeof(sbyte)) { - WriteSByte((sbyte)value); + WriteSByte((sbyte)value); } else if (t == typeof(short)) { - WriteInt16((short)value, littleEndian); + WriteInt16((short)value, littleEndian); } else if (t == typeof(ushort)) { - WriteUInt16((ushort)value, littleEndian); + WriteUInt16((ushort)value, littleEndian); } else if (t == typeof(int)) { - WriteInt32((int)value, littleEndian); + WriteInt32((int)value, littleEndian); } else if (t == typeof(uint)) { - WriteUInt32((uint)value, littleEndian); + WriteUInt32((uint)value, littleEndian); } else if (t == typeof(long)) { @@ -762,7 +762,7 @@ public void WritePrimitive(object value, Type t, bool littleEndian) /// public long BytesWritten { - get { return _stm.BytesWritten; } + get { return _stm.BytesWritten; } set { _stm.BytesWritten = value; } } } diff --git a/CANAPE/Utils/DiffItem.cs b/CANAPE/Utils/DiffItem.cs index be73cc0..f72aeb4 100644 --- a/CANAPE/Utils/DiffItem.cs +++ b/CANAPE/Utils/DiffItem.cs @@ -17,7 +17,7 @@ // along with this program. If not, see . namespace CANAPE.Utils -{ +{ /// details of one difference. public struct DiffItem { @@ -30,5 +30,5 @@ public struct DiffItem public int deletedA; /// Number of changes in Data B. public int insertedB; - } + } } diff --git a/CANAPE/Utils/DynamicConfigObject.cs b/CANAPE/Utils/DynamicConfigObject.cs index 5895589..10ed903 100644 --- a/CANAPE/Utils/DynamicConfigObject.cs +++ b/CANAPE/Utils/DynamicConfigObject.cs @@ -30,7 +30,7 @@ public sealed class DynamicConfigObject : DynamicObject /// /// Default constructor /// - public DynamicConfigObject() : this(new Dictionary()) + public DynamicConfigObject() : this(new Dictionary()) { } diff --git a/CANAPE/Utils/GeneralUtils.cs b/CANAPE/Utils/GeneralUtils.cs index b9818d6..64f4339 100644 --- a/CANAPE/Utils/GeneralUtils.cs +++ b/CANAPE/Utils/GeneralUtils.cs @@ -23,7 +23,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; -using System.Threading; namespace CANAPE.Utils { @@ -33,7 +32,7 @@ namespace CANAPE.Utils public static class GeneralUtils { private static Regex _formatRegex = new Regex("\\$[a-zA-Z_/.*][a-zA-Z0-9_/.*]*"); - + /// /// Generate a MD5 hex string from a byte array /// @@ -51,7 +50,7 @@ public static string GenerateMd5String(byte[] data) return builder.ToString(); } - + /// /// Create a string from a byte array like python does /// @@ -60,7 +59,7 @@ public static string GenerateMd5String(byte[] data) public static string MakeByteString(byte[] data) { if (data != null) - { + { return new BinaryEncoding().GetString(data); } @@ -73,7 +72,7 @@ public static string MakeByteString(byte[] data) /// The string to convert (note any char values > 255 will be masked) /// The byte array, null if s was null public static byte[] MakeByteArray(string s) - { + { if (s != null) { return new BinaryEncoding().GetBytes(s); @@ -89,7 +88,7 @@ public static byte[] MakeByteArray(string s) /// The line /// Throw when no more data availeble public static string ReadLine(Stream stm) - { + { List reqBytes = new List(); int ch = 0; @@ -97,7 +96,7 @@ public static string ReadLine(Stream stm) { reqBytes.Add((byte)ch); if (ch == 10) - { + { break; } } @@ -359,7 +358,7 @@ public static Encoding GetEncodingFromType(BinaryStringEncoding encoding) case BinaryStringEncoding.ShiftJIS: ret = Encoding.GetEncoding(932); break; - default: + default: ret = Encoding.GetEncoding((int)encoding); break; } @@ -449,7 +448,7 @@ public static string DecodeEscapedString(string s) else { StringBuilder builder = new StringBuilder(s); - + int pos = 0; while (pos < builder.Length) @@ -485,15 +484,15 @@ public static string DecodeEscapedString(string s) throw new FormatException(String.Format(Properties.Resources.GeneralUtils_DecodeEscapedInvalidEscape, builder[pos])); } - builder[pos] = val; + builder[pos] = val; } else { throw new FormatException(Properties.Resources.GeneralUtils_DecodeEscapedStringTrailingSlash); } - } - - pos++; + } + + pos++; } return builder.ToString(); @@ -541,7 +540,7 @@ public static int GetBytesHashCode(byte[] ba) foreach (byte b in ba) { hash = (hash * 13) + b; - } + } return hash; } @@ -553,9 +552,9 @@ public static int GetBytesHashCode(byte[] ba) /// The packets public static void WritePacketsToFile(string filename, IEnumerable packets) { - using(var stream = File.OpenWrite(filename)) + using (var stream = File.OpenWrite(filename)) { - foreach(var packet in packets) + foreach (var packet in packets) { packet.WriteToStream(stream); } @@ -567,9 +566,9 @@ public static void WritePacketsToFile(string filename, IEnumerable pa /// /// The packets from file. /// The filename - public static IEnumerable ReadPacketsFromFile(string filename) + public static IEnumerable ReadPacketsFromFile(string filename) { - using(var stream = File.OpenRead(filename)) + using (var stream = File.OpenRead(filename)) { List packets = new List(); try @@ -579,7 +578,7 @@ public static IEnumerable ReadPacketsFromFile(string filename) packets.Add(LogPacket.ReadFromStream(stream)); } } - catch(EndOfStreamException) + catch (EndOfStreamException) { } return packets; diff --git a/CANAPE/Utils/LockedQueue.cs b/CANAPE/Utils/LockedQueue.cs index 1673702..b541bba 100644 --- a/CANAPE/Utils/LockedQueue.cs +++ b/CANAPE/Utils/LockedQueue.cs @@ -16,10 +16,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . using System; +using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; -using System.Collections.Concurrent; -using System.Collections; namespace CANAPE.Utils { @@ -30,7 +30,7 @@ namespace CANAPE.Utils public sealed class LockedQueue : IDisposable, IEnumerable where T : class { private BlockingCollection _queue; - private CancellationToken _token; + private CancellationToken _token; /// /// Constructor diff --git a/CANAPE/Utils/LogPacket.cs b/CANAPE/Utils/LogPacket.cs index 76fe56d..979b01d 100644 --- a/CANAPE/Utils/LogPacket.cs +++ b/CANAPE/Utils/LogPacket.cs @@ -15,10 +15,10 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using System; -using System.IO; using CANAPE.DataFrames; using CANAPE.Nodes; +using System; +using System.IO; namespace CANAPE.Utils { @@ -69,7 +69,7 @@ public string Hash { get { - + return Frame.Hash; } } @@ -127,8 +127,8 @@ public LogPacket(string tag, Guid netid, Guid uuid, string network, DataFrame fr /// /// /// - public LogPacket(string tag, Guid netid, string network, DataFrame frame, ColorValue color) - : this(tag, netid, Guid.NewGuid(), network, frame, color, DateTime.Now) + public LogPacket(string tag, Guid netid, string network, DataFrame frame, ColorValue color) + : this(tag, netid, Guid.NewGuid(), network, frame, color, DateTime.Now) { } @@ -136,8 +136,8 @@ public LogPacket(string tag, Guid netid, string network, DataFrame frame, ColorV /// Constructor from an event object /// /// The event args - public LogPacket(LogPacketEventArgs args) - : this(args.Tag, args.NetId, Guid.NewGuid(), args.NetworkDescription, args.Frame, args.Color, args.Timestamp) + public LogPacket(LogPacketEventArgs args) + : this(args.Tag, args.NetId, Guid.NewGuid(), args.NetworkDescription, args.Frame, args.Color, args.Timestamp) { } diff --git a/CANAPE/Utils/Logger.cs b/CANAPE/Utils/Logger.cs index 42db8f1..aec542b 100644 --- a/CANAPE/Utils/Logger.cs +++ b/CANAPE/Utils/Logger.cs @@ -17,7 +17,6 @@ // along with this program. If not, see . using System; using System.Reflection; -using System.Security.Authentication; namespace CANAPE.Utils { @@ -74,7 +73,7 @@ public EventLogEntry(LogEntryType entryType, string text, Exception ex, string s Timestamp = DateTime.Now; EntryType = entryType; Text = text; - ExceptionObject = ex; + ExceptionObject = ex; SourceName = sourceName; SourceGuid = sourceGuid; } @@ -125,7 +124,7 @@ public enum LogEntryType /// /// Log an error entry /// - Error = 8, + Error = 8, /// /// All the levels /// @@ -136,7 +135,7 @@ public enum LogEntryType /// Specify the level of the logging /// public LogEntryType LogLevel { get; set; } - + /// /// Event when log entry received /// diff --git a/CANAPE/Utils/PipelineStream.cs b/CANAPE/Utils/PipelineStream.cs index 0238b28..2032914 100644 --- a/CANAPE/Utils/PipelineStream.cs +++ b/CANAPE/Utils/PipelineStream.cs @@ -20,7 +20,7 @@ using System.Threading; namespace CANAPE.Utils -{ +{ /// /// Class to implement a thread safe pipe byte stream /// inputs in blocks of bytes @@ -36,7 +36,7 @@ public class PipelineStream : Stream /// /// Default constructor /// - public PipelineStream(CancellationToken token) + public PipelineStream(CancellationToken token) { _dataQueue = new LockedQueue(-1, token); _readTimeout = Timeout.Infinite; @@ -48,7 +48,7 @@ public PipelineStream(CancellationToken token) /// Array of bytes to queue, /// if null is passed this will cause the stream to end when all data has been read public void Enqueue(byte[] frame) - { + { _dataQueue.Enqueue(frame); } @@ -113,7 +113,7 @@ public override bool CanWrite /// Flush the stream (does nothing) /// public override void Flush() - { + { } /// @@ -174,7 +174,7 @@ public override int Read(byte[] buffer, int offset, int count) if (!_endOfStream) { EnsureDataAvailable(); - + if ((_currBuf != null) && (_currBuf.Length > 0)) { int left = _currBuf.Length - _currPos; @@ -187,7 +187,7 @@ public override int Read(byte[] buffer, int offset, int count) return len; } - + /// /// Read a byte /// diff --git a/CANAPE/Utils/PropertyBag.cs b/CANAPE/Utils/PropertyBag.cs index 4b0fb12..08985ef 100644 --- a/CANAPE/Utils/PropertyBag.cs +++ b/CANAPE/Utils/PropertyBag.cs @@ -144,7 +144,7 @@ private PropertyBag GetRelativeBag(IEnumerable parts) { PropertyBag bag = this; - foreach(string name in parts) + foreach (string name in parts) { if (bag._bags.ContainsKey(name)) { @@ -178,7 +178,7 @@ public PropertyBag GetRelativeBag(string name) public dynamic GetRelativeValue(string name) { dynamic ret = null; - string[] parts = name.Split('.'); + string[] parts = name.Split('.'); if (parts.Length > 0) { @@ -235,7 +235,7 @@ public IEnumerator> GetEnumerator() { foreach (KeyValuePair pair in bag.Value) { - yield return new KeyValuePair(String.Format("{0}.{1}", bag.Key, pair.Key), pair.Value); + yield return new KeyValuePair(String.Format("{0}.{1}", bag.Key, pair.Key), pair.Value); } } diff --git a/CANAPE/Utils/TextLineEnding.cs b/CANAPE/Utils/TextLineEnding.cs index 818e15f..56372a3 100644 --- a/CANAPE/Utils/TextLineEnding.cs +++ b/CANAPE/Utils/TextLineEnding.cs @@ -34,6 +34,6 @@ public enum TextLineEnding /// /// Split on carriage return line feed pairs /// - CarriageReturnLineFeed, + CarriageReturnLineFeed, } } diff --git a/CANAPE/Utils/TwentyFourBitIntegers.cs b/CANAPE/Utils/TwentyFourBitIntegers.cs index d98b9ce..e374757 100644 --- a/CANAPE/Utils/TwentyFourBitIntegers.cs +++ b/CANAPE/Utils/TwentyFourBitIntegers.cs @@ -15,7 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -using CANAPE.DataFrames; using System; using System.Globalization; From 136254493c2f18bba26e5f65faf6e75f19acfe4f Mon Sep 17 00:00:00 2001 From: rusal <54377741+trusthat@users.noreply.github.com> Date: Sat, 19 Aug 2023 15:57:33 +0300 Subject: [PATCH 3/3] Readonly client variables --- CANAPE.Net/Clients/SocksProxyClient.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CANAPE.Net/Clients/SocksProxyClient.cs b/CANAPE.Net/Clients/SocksProxyClient.cs index 4924d52..15c3129 100644 --- a/CANAPE.Net/Clients/SocksProxyClient.cs +++ b/CANAPE.Net/Clients/SocksProxyClient.cs @@ -34,11 +34,11 @@ namespace CANAPE.Net.Clients /// public class SocksProxyClient : IpProxyClient { - private string _hostname; - private int _port; - private bool _ipv6; - private bool _sendHostName; - private SupportedVersion _version; + private readonly string _hostname; + private readonly int _port; + private readonly bool _ipv6; + private readonly bool _sendHostName; + private readonly SupportedVersion _version; /// /// Supported versions for SOCKS proxy client